diff --git a/Modules/ado/personal/_/_graph.ado b/Modules/ado/personal/_/_graph.ado
new file mode 100644
index 0000000..a2ab97e
--- /dev/null
+++ b/Modules/ado/personal/_/_graph.ado
@@ -0,0 +1,100 @@
+capture program drop _graph
+program _graph
+syntax varlist, PARTition(numlist integer >0) [SCOrename(string)] calcmethod(string)
+
+qui set autotabgraphs on
+
+local P:word count `partition'
+
+if "`scorename'" == "" {
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local scorename `scorename' `name'
+ }
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+*capture calcscore `varlist', partition(`partition') scorename(`scorename') calcmethod(`calcmethod')
+
+
+if "`calcmethod'" == "stand" local w = 10
+if "`calcmethod'" == "sum" local b = 10
+if "`calcmethod'" == "mean" local w = 0.5
+
+set graphics off
+foreach s in `scorename' {
+ qui hist `s', name("`s'",replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b')
+}
+set graphics on
+
+gr combine `scorename', name("Histograms_scores",replace)
+
+qui biplot `scorename', name("Biplot_dimensions",replace) norow std title("") xtitle("") ytitle("")
+
+qui biplot `varlist', name("temp",replace) norow std nograph
+
+mat a = r(V)
+
+tempvar a1 a2
+mat colnames a = `a1' `a2'
+svmat a, names(col)
+
+tempvar mina1 mina2 maxa1 maxa2
+egen `mina1' = min(`a1')
+egen `mina2' = min(`a2')
+egen `maxa1' = max(`a1')
+egen `maxa2' = max(`a2')
+local mina1 = `mina1'
+local mina2 = `mina2'
+local maxa1 = `maxa1'+1.4
+local maxa1x = `maxa1'+0.3
+local maxa2 = `maxa2'
+
+local colors = "red blue black green ebblue mint erose orange maroon magenta mint gray teal navy olive sienna"
+local i = 1
+foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+}
+
+local i = 1
+local y = 1
+local c = 1
+local bas = `maxa2'+0.2
+local droite = max(`maxa1',0.2)
+
+foreach x in `partition' {
+ tokenize `scorename'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ *local r = round(runiform()*255)
+ *local g = round(runiform()*255)
+ *local b = round(runiform()*255)
+
+ forvalues j=`y'/`s' {
+ local a = `a1'[`j']
+ local b = `a2'[`j']
+ local call `call' || pcarrowi 0 0 `b' `a' "`var`j''", mlabcolor(`col`i'') color(`col`i'') head
+ }
+ local bas = `bas'-0.2
+ *local droite = `droite'
+ local call `call' text(`bas' `droite' "``i''", size(3) color(`col`i'')) /*`bas' `droite' "``i''", mlabcolor("`r' `g' `b'")*/
+ local `++i'
+ local y = `s'+1
+ local `++c'
+}
+
+qui twoway `call' name("Biplot_items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) xtitle("") ytitle("")
+
+
+end
+
+*_graph x1-x40, partition(5 5 5 5 5 5 5 5) scorename(HAaaaaa PSE W BCC AC AE LI MOC)
+*_graph ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(HA PSE W BCC AC AE LI MOC) calcmethod(stand)
diff --git a/Modules/ado/personal/a/anaoption.ado b/Modules/ado/personal/a/anaoption.ado
new file mode 100644
index 0000000..46e436a
--- /dev/null
+++ b/Modules/ado/personal/a/anaoption.ado
@@ -0,0 +1,48 @@
+*! version 1 27may2007
+*! Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Stata program : anaoption
+*
+* Historic
+* Version 1 (2007-05-27): Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2007 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 anaoption ,rclas
+version 7.0
+syntax [, DETails minvi(real .03) siglevel(real 0.05) minsize(real 0)]
+
+return scalar minvi=`minvi'
+return scalar siglevel=`siglevel'
+return scalar minsize=`minsize'
+return local details `details'
+
+
+end
+
diff --git a/Modules/ado/personal/a/anares.ado b/Modules/ado/personal/a/anares.ado
new file mode 100644
index 0000000..ead6c30
--- /dev/null
+++ b/Modules/ado/personal/a/anares.ado
@@ -0,0 +1,36 @@
+program define raschres,rclass
+syntax varlist [, resname(string)]
+
+tempname diff theta
+matrix `diff'=r(beta)
+matrix `theta'=r(theta)
+
+if "`resname'"=="" {
+ local resname=res
+}
+
+tokenize `varlist'
+local nbitems: word count `varlist'
+tempname score lt
+genscore `varlist',score(`score')
+gen `lt'=.
+
+forvalues i=0/`nbitems' {
+ replace `lt'=`theta'[1,`i'] if `score'==`i'
+}
+
+forvalues i=1/`nbitems'{
+ tempname p`i' res`i'
+ gen `p`i''=exp(`lt'-`diff'[1,`i'])/(1+exp(`lt'-`diff'[1,`i'])
+ gen `resname'`i'=(1-`p`i'')/sqrt(`p`i''*(1-`p`i''))
+}
+pca `resname'*
+
+
+
+
+
+
+
+
+end
\ No newline at end of file
diff --git a/Modules/ado/personal/b/backrasch.ado b/Modules/ado/personal/b/backrasch.ado
new file mode 100644
index 0000000..08e958b
--- /dev/null
+++ b/Modules/ado/personal/b/backrasch.ado
@@ -0,0 +1,171 @@
+*! version 3 11june2014
+************************************************************************************************************
+* Backrasch : Backward procedure under a Rasch model
+*
+* Historic
+* Version 1 (2004-02-13) : Jean-Benoit Hardouin
+* Version 2 (2005-05-23) : Jean-Benoit Hardouin
+* Version 3 (2014-06-11) : Jean-Benoit Hardouin /*id for raschtest*/
+*
+* Needed modules :
+* raschtestv7 version 7.2.1 (http://freeirt.free.fr)
+* gammasym version 2.1 (http://freeirt.free.fr)
+* gausshermite version 1 (http://freeirt.free.fr)
+* geekel2d version 4.1 (http://freeirt.free.fr)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.10 (ssc describe gllamm)
+* gllapred version 2.3.2 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2004-2005, 2014 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 backrasch , rclass
+version 8.0
+syntax varlist(min=3 numeric) , [p(real 0.05) Method(string) Test(string) NBSCales(integer 1) nodetail noAUTOGroup]
+local nbitems : word count `varlist'
+tokenize `varlist'
+preserve
+
+
+tempfile saveraschtest
+qui save `saveraschtest'
+
+local autogroup2
+if "`autogroup'"=="" {
+ local autogroup2 autogroup
+}
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+
+tempname select
+matrix `select'=J(1,`nbitems',0)
+local dim=1
+local less3items=0
+
+while `dim'<=`nbscales'&`less3items'!=1 {
+ di
+ di in green _col(25) "subscale : " in yellow `dim'
+ di in green _col(25) "{hline 12}"
+ local nobaditem=0
+ while `nobaditem'!=1 {
+ local varlistscale
+ local nbitemsscale=0
+ forvalues i=1/`nbitems' {
+ if `select'[1,`i']==0 {
+ local nbitemsscale=`nbitemsscale'+1
+ local ssitem`nbitemsscale'=`i'
+ local varlistscale `varlistscale' ``i''
+ }
+ }
+
+ if `nbitemsscale'<3 {
+ if "`detail'"=="" {
+ di in green "The " in yellow "`dim'th " in green "sub-scale can not be created, because there is less than three items remaining"
+ }
+ local `less3items'=1
+ local dim=`dim'-1
+ continue, break
+ }
+ else {
+ tempvar tmp
+ capture gen `tmp'=_n
+ qui raschtestv7 `varlistscale',m(`method') t(`test') `autogroup2' id(`tmp')
+ tempname itemFit
+ matrix `itemFit'=r(itemFit)
+ local minp=`p'
+ local deleteitem
+ local nobaditem=1
+ forvalues i=1/`nbitemsscale' {
+ if `itemFit'[`i',3]<`minp' {
+ local minp=`itemFit'[`i',3]
+ local deleitem=`i'
+ local rowdeleteitem=`ssitem`i''
+ local nobaditem=0
+ }
+ }
+ if `nobaditem'==1 {
+ if "`detail'"=="" {
+ di in green "No more item to remove of the scale " in yellow "`dim'"
+ }
+ continue, break
+ }
+ else {
+ if "`detail'"=="" {
+ di in green "The item " in yellow "``rowdeleteitem'' " in green "is removed of the scale " in yellow "`dim'" in green " (p=" in yellow %6.4f `minp' in green ")"
+ }
+ matrix `select'[1,`rowdeleteitem']=-1
+ }
+ }
+ }
+
+ if `nbitemsscale'>=3 {
+ forvalues i=1/`nbitems' {
+ if `select'[1,`i']==0 {
+ matrix `select'[1,`i']==`dim'
+ }
+ if `select'[1,`i']==-1 {
+ matrix `select'[1,`i']==0
+ }
+ }
+ local scale`dim'
+ forvalues i=1/`nbitems' {
+ if `select'[1,`i']==`dim' {
+ local scale`dim' "`scale`dim'' ``i''"
+ }
+ }
+ if "`scale`dim''"!="" {
+ di
+ di in green _col(4) "Number of selected items : " in yellow "`nbitemsscale'"
+ tempvar tmp2
+ capture gen `tmp2'=_n
+ raschtestv7 `scale`dim'',m(`method') t(`test') `autogroup2' id(`tmp2')
+ di
+ di _dup(70) "-"
+ }
+
+
+ local dim=`dim'+1
+ }
+ if `nbitemsscale'<3{
+ forvalues i=1/`nbitems' {
+ if `select'[1,`i']==-1 {
+ matrix `select'[1,`i']==0
+ }
+ }
+ continue, break
+ }
+
+}
+
+matrix colnames `select'=`varlist'
+matrix rownames `select'=scale
+
+return matrix selection `select'
+end
+
diff --git a/Modules/ado/personal/b/backrasch.hlp b/Modules/ado/personal/b/backrasch.hlp
new file mode 100644
index 0000000..1046692
--- /dev/null
+++ b/Modules/ado/personal/b/backrasch.hlp
@@ -0,0 +1,54 @@
+{smcl}
+{* 23may2005}{...}
+{hline}
+help for {hi:backrasch}
+{hline}
+
+{title:Backward procedure on a Rasch model}
+
+{p 8 14 2}{cmd:backrasch} {it:varlist} {cmd:,} [{cmdab:m:ethod}({it:keyword})
+{cmdab:t:est}({it:keyword}) {cmdab:nodetail}
+{cmdab:p}({it:#.###}) {cmdab:nbsc:ales}({it:#})
+{cmdab:noautog:roup}]
+
+{title:Description}
+
+{p 4 8 2}{cmd:backward} realizes a Backward procedure on a Rasch model: the
+items are removed one per one if they have a bad fit to the Rasch model. The
+fit of the items is valuated by a first-order statistics (test R1c, R1m or Q1)
+It is possible to build several sub-scales of items, the second sub-scale is
+build with the items unselected in the first sub-scales, the third one
+with the items unselected in the two first sub-scales, and so on... By default,
+the parameters of the Rasch model are estimated by conditional maximum
+likelihood (CML), but it is possible to estimate them by marginal maximum
+likelihood (MML) or generalized estimating equations (GEE).
+
+{title:Options}
+
+{p 4 8 2}{cmd:method}({it:cml/mml/gee}) defines the method of estimation of the difficulty parameters among conditional maximum likelihood (cml - by default), marginal maximum likelihood (mml) or generalized estimating equations (gee).
+
+{p 4 8 2}{cmd:test}({it:R/Q}) defines the first order statistics to use between R-type test (R1c or R1m - by default) or the Q1 test of Van den Wollenberg.
+
+{p 4 8 2}{cmd:nodetail} does not display the description of the algorithm.
+
+{p 4 8 2}{cmd:p}({it:#.###}) defines the level of signification who define a significantly bad fitted item (0.05 by default).
+
+{p 4 8 2}{cmd:nbscales}({it:#}) defines the maximal number of sub-scales to build. By default, the program builds only one sub-scale.
+
+{p 4 8 2}{cmd:noautograoup} forces the program to compute the first order fit statistics with the groups defined by the value of the score. by default, the scores are grouped to obtained groups of 30 individuals or more.
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. backrasch item1 item2 item3 item4} /*estimation by CML, test R1c, only one scale is built*/
+
+{p 4 8 2}{cmd:. backrasch item1 item2 item3 item4 , p(0.2) method(mml) nodetail} /*estimation by MML, test R1m, only one scale*/
+
+{p 4 8 2}{cmd:. backrasch item1 item2 item3 item4 , p(0.1) nbsc(5) noautog} /*CLM estimation, R1c tests, 5 scales will be build*/
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte
+Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France. You can contact the author at
+{browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+and visit the websites {browse "http://anaqol.free.fr":AnaQol} and
+{browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/b/biplotvlab.ado b/Modules/ado/personal/b/biplotvlab.ado
new file mode 100644
index 0000000..cc09ac5
--- /dev/null
+++ b/Modules/ado/personal/b/biplotvlab.ado
@@ -0,0 +1,74 @@
+*! version 1.0.1 30sep2005
+*! The first version of this module has been wroten by Ken Higbee (StataCorp)
+*! Improvements by Jean-Benoit Hardouin
+
+program biplotvlab
+
+ version 9
+
+ syntax varlist(numeric min=2) [if] [in] [, LABdes(string) stretch(int 1) *]
+
+ // run biplot quietly (and nograph) so we can get r(V)
+ qui biplot `varlist' `if' `in' , `options' nograph
+ tempname V
+ mat `V' = r(V)
+ local nbvar:word count `varlist'
+ tokenize `varlist'
+
+ // build the -text()- option
+ local topt "text("
+ local i 0
+ local miny=`V'[1,2]
+ local maxy=`V'[1,2]
+ local minx=`V'[1,1]
+ local maxx=`V'[1,1]
+ forvalues i=1/`nbvar' {
+ local miny=min(`V'[`i',2],`miny')
+ local maxy=max(`V'[`i',2],`maxy')
+ local minx=min(`V'[`i',1],`minx')
+ local maxx=max(`V'[`i',1],`maxx')
+ }
+ if `maxx'*`minx'>0 {
+ local coefx=max(abs(`maxx'),abs(`minx'))
+ local coefx=`coefx'/20
+ }
+ else {
+ local coefx=abs(`maxx'-`minx')/20
+ }
+ if `maxx'*`minx'>0 {
+ local coefy=max(abs(`maxy'),abs(`miny'))
+ local coefy=`coefy'/20
+ }
+ else {
+ local coefy=abs(`maxy'-`miny')/20
+ }
+ forvalues i=1/`nbvar' {
+ // y value
+ if `V'[`i',2]>0 {
+ local topt `"`topt' `= (`V'[`i',2]+`coefy')*`stretch''"'
+ }
+ else {
+ local topt `"`topt' `= (`V'[`i',2]-`coefy')*`stretch''"'
+ }
+ // x value
+ if `V'[`i',1]<0 {
+ local topt `"`topt' `= (`V'[`i',1]-`coefx')*`stretch''"'
+ }
+ else {
+ local topt `"`topt' `= (`V'[`i',1]+`coefx')*`stretch''"'
+ }
+ // variable label
+ local lab: var label ``i''
+ if "`lab'"=="" {
+ local lab ``i''
+ }
+ local topt `"`topt' `"`lab'"' "'
+ }
+ if "`labdes'"=="" {
+ local labdes size(vsmall)
+ }
+ local topt `"`topt',`labdes')"'
+
+ // call with -colopts(nolabel)- and -text()- just built
+ biplot `varlist' `if' `in', `options' colopts(nolabel) `topt' stretch(`stretch')
+end
diff --git a/Modules/ado/personal/b/biplotvlab.hlp b/Modules/ado/personal/b/biplotvlab.hlp
new file mode 100644
index 0000000..5eef3de
--- /dev/null
+++ b/Modules/ado/personal/b/biplotvlab.hlp
@@ -0,0 +1,38 @@
+{smcl}
+{* 30sept2005}{...}
+{hline}
+help for {hi:biplotvlab}{right:Jean-benoit Hardouin}
+{hline}
+
+{title:Biplot with variable labels}
+
+{p 8 14 2}{cmd:biplotvlab} {it:varlist} [{cmd:,} {cmdab:lab:des}({help textbox_options}) {help biplot:biplot_options})
+
+{title:Description}
+
+{p 4 8 2}{cmd:biplotvlab} allows displaying on a biplot graph the labels of the
+variables instead of the names of the variables. If none label is defined for one
+or several variables, the names of these variables are displayed instead.
+{cmd:biplotvlab} replaces the official {cmd:biplot} command.
+
+{title:Options}
+
+{p 4 8 2}{cmd:labdes} defines the options to apply to the labels (color, size...).
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. biplotvlab turn trunk mpg,norow}
+
+{p 4 8 2}{cmd:. biplotvlab turn trunk mpg,labdes(size(vsmall) color(blue))}
+
+{p 4 8 2}{cmd:. biplotvlab turn trunk mpg, stretch(12)}
+
+{title:Authors}
+
+{p 4 8 2}Ken Higbee (StataCorp) has wroten the first version of this module.
+
+{p 4 8 2}Improvements by Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte
+Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France. You can contact the author at
+{browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+and visit the websites {browse "http://anaqol.free.fr":AnaQol} and
+{browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/bidon b/Modules/ado/personal/bidon
new file mode 160000
index 0000000..bdcabcb
--- /dev/null
+++ b/Modules/ado/personal/bidon
@@ -0,0 +1 @@
+Subproject commit bdcabcbde5043d31555d7d58758441d90f92f235
diff --git a/Modules/ado/personal/c/calcscore.ado b/Modules/ado/personal/c/calcscore.ado
new file mode 100644
index 0000000..c43587c
--- /dev/null
+++ b/Modules/ado/personal/c/calcscore.ado
@@ -0,0 +1,155 @@
+capture program drop calcscore
+program calcscore,rclass
+syntax varlist, PARTition(numlist integer >0) [CALCmethod(string) SCOrename(string)]
+
+local y = 1
+
+*di "{bf:Calculs des scores}"
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+if "`scorename'" != "" {
+ local P:word count `partition'
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ foreach sco in `scorename' {
+ capture confirm variable `sco'
+ if !_rc {
+ di in red "`sco' is a variable of the dataset. Choose another name"
+ exit 119
+ }
+ }
+}
+
+/*
+local cpt = 0
+if "`sum'" != "" {
+ local cpt `cpt' + 1
+}
+if "`mean'" != "" {
+ local cpt `cpt' + 1
+}
+if "`stand'" != "" {
+ local cpt `cpt' + 1
+}
+if `cpt'>1 {
+ di in red "You must choose between mean, sum or stand (the options are exclusive)"
+ exit 119
+}
+*/
+
+local i = 1
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ tempvar nonmiss
+ qui egen `nonmiss' = rownonmiss(`liste')
+
+ if "`scorename'" != "" {
+ tokenize `scorename'
+ local sc = "``i''"
+ }
+ else local sc = "Dim`i'"
+
+/* if "`calc_method'" == "" {
+ local calc_method = "mean"
+ }
+
+ if "`calc_method'" != "sum" & "`calc_method'" != "mean" {
+ di in red "The calc_method option is invalid. Choose mean or sum."
+ exit 119
+ }
+
+ if "`calc_method'" == "sum" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ if "`calc_stand'" != "" {
+ local maxs = 0
+ foreach var in `liste' {
+ qui levelsof `var', local(levels)
+ local max = 0
+ foreach l in `levels' {
+ if `l'>`max' local max = `l'
+ }
+ local maxs = `maxs' + `max'
+ }
+ di "`sc' : `maxs'"
+ qui replace `sc' = `sc'*`nonmiss'*100/`maxs'
+ }
+ else qui replace `sc' = `sc'*`nonmiss'
+ }
+ else if "`calc_method'" == "mean" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ }
+*/
+ if "`calcmethod'" == "" local calcmethod = "mean"
+
+ if "`calcmethod'" != "mean" & "`calcmethod'" != "sum" & "`calcmethod'" != "stand" {
+ di in red "option calcmethod incorrectly specified (choose among mean, sum and stand)"
+ error 198
+ }
+
+ if "`calcmethod'" == "sum" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`nonmiss'
+ }
+
+ else if "`calcmethod'" == "stand" {
+
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`nonmiss'
+
+ tempvar min max
+ egen `min' = min(`sc')
+ egen `max' = max(`sc')
+
+
+ /*
+ foreach var in `liste' {
+ /*qui levelsof `var', local(levels)
+ local max = 0
+ foreach l in `levels' {
+ if `l'>`max' local max = `l'
+ }
+ local maxs = `maxs' + `max'*/
+
+ local max = max(`levels')
+ }
+
+ */
+ *di "max : "`max'
+ *di "min : "`min'
+
+ qui replace `sc' = (`sc'-`min')/(`max'-`min')*100
+ }
+
+ else {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ }
+
+local `i++'
+local y = `s'+1
+}
+end
+
+*calcscore ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(HA PSE W BCC AC AE LI MOC) calcmethod(stand)
+*calcscore x1-x40, partition(5 5 5 5 5 5 5 5) calcmethod(stand)
+*calcscore sf36_3q_intenses sf36_3q_moderees sf36_3q_soulever sf36_3q_etages sf36_3q_etage sf36_3q_pencher sf36_3q_15km sf36_3q_500m sf36_3q_100m sf36_3q_douche sf36_4q_limite_temps_travail sf36_4q_moins_choses sf36_4q_type_travail sf36_4q_effort sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques sf36_1q sf36_11q_malade sf36_11q_porte_bien sf36_11q_degrade sf36_11q_excellente_sante sf36_9q_enthousiaste sf36_9q_energie sf36_9q_epuise sf36_9q_fatigue sf36_6q_vie_sociale sf36_10q_etat_mental sf36_5q_limite_temps_travail sf36_5q_moins_choses sf36_5q_accomplies_soigneusement sf36_9q_nerveux sf36_9q_triste sf36_9q_calme sf36_9q_maussade sf36_9q_heureux, partition(10 4 2 5 4 2 3 5) scorename(PF RP BP GH VT SF RE MH) calcmethod(mean)
diff --git a/Modules/ado/personal/c/calcul.ado b/Modules/ado/personal/c/calcul.ado
new file mode 100644
index 0000000..a1e15eb
--- /dev/null
+++ b/Modules/ado/personal/c/calcul.ado
@@ -0,0 +1,395 @@
+*program drop calcul
+program define calcul
+syntax, s10(numlist)
+
+matrix define deces=J(140,6,0)
+local j=0
+tcm, s10(`s10') anneepop(1989) annees(1988/1990) sexe(1)
+matrix essai=r(donnees)
+local TCMH89=r(TCM)
+matrix deces[1,1]=essai[2..19,4]
+matrix deces[25,1]=`TCMH89'
+tcm, s10(`s10') anneepop(1989) annees(1988/1990) sexe(2)
+matrix essai=r(donnees)
+local TCMF89=r(TCM)
+matrix deces[1,2]=essai[2..19,4]
+matrix deces[25,2]=`TCMF89'
+tcm, s10(`s10') anneepop(1982) annees(1981/1983) sexe(1)
+matrix essai=r(donnees)
+local TCMH82=r(TCM)
+matrix deces[1,3]=essai[2..19,4]
+matrix deces[20,1]=`TCMH82'
+tcm, s10(`s10') anneepop(1982) annees(1981/1983) sexe(2)
+matrix essai=r(donnees)
+local TCMF82=r(TCM)
+matrix deces[1,4]=essai[2..19,4]
+matrix deces[20,2]=`TCMF82'
+
+
+
+tcm, s10(`s10') anneepop(1983) annees(1982/1984) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[21,1]=`TCMH'
+tcm, s10(`s10') anneepop(1983) annees(1982/1984) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[21,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1984) annees(1983/1985) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[22,1]=`TCMH'
+tcm, s10(`s10') anneepop(1984) annees(1983/1985) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[22,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1985) annees(1984/1986) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[23,1]=`TCMH'
+tcm, s10(`s10') anneepop(1985) annees(1984/1986) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[23,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1986) annees(1985/1987) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[24,1]=`TCMH'
+tcm, s10(`s10') anneepop(1986) annees(1985/1987) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[24,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1992) annees(1991/1993) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[26,1]=`TCMH'
+tcm, s10(`s10') anneepop(1992) annees(1991/1993) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[26,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1993) annees(1992/1994) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[27,1]=`TCMH'
+tcm, s10(`s10') anneepop(1993) annees(1992/1994) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[27,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1994) annees(1993/1995) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[28,1]=`TCMH'
+tcm, s10(`s10') anneepop(1994) annees(1993/1995) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[28,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1995) annees(1994/1996) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[29,1]=`TCMH'
+tcm, s10(`s10') anneepop(1995) annees(1994/1996) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[29,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1996) annees(1995/1997) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[30,1]=`TCMH'
+tcm, s10(`s10') anneepop(1996) annees(1995/1997) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[30,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1997) annees(1996/1998) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[31,1]=`TCMH'
+tcm, s10(`s10') anneepop(1997) annees(1996/1998) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[31,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1998) annees(1997/1999) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+matrix deces[32,1]=`TCMH'
+tcm, s10(`s10') anneepop(1998) annees(1997/1999) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[32,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1)
+matrix essai=r(donnees)
+local TCMH=r(TCM)
+local TCMH9800reg=r(TCM)
+matrix deces[33,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2)
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+local TCMF9800reg=r(TCM)
+matrix deces[33,2]=`TCMF'
+
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(18) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,1]=essai[2..19,2]
+matrix deces[53,1]=r(TCM)
+matrix deces[54,1]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(18) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,1]=essai[2..19,2]
+matrix deces[74,1]=r(TCM)
+matrix deces[75,1]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(28) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,2]=essai[2..19,2]
+matrix deces[53,2]=r(TCM)
+matrix deces[54,2]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(28) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,2]=essai[2..19,2]
+matrix deces[74,2]=r(TCM)
+matrix deces[75,2]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(36) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,3]=essai[2..19,2]
+matrix deces[53,3]=r(TCM)
+matrix deces[54,3]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(36) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,3]=essai[2..19,2]
+matrix deces[74,3]=r(TCM)
+matrix deces[75,3]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(37) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,4]=essai[2..19,2]
+matrix deces[53,4]=r(TCM)
+matrix deces[54,4]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(37) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,4]=essai[2..19,2]
+matrix deces[74,4]=r(TCM)
+matrix deces[75,4]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(41) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,5]=essai[2..19,2]
+matrix deces[53,5]=r(TCM)
+matrix deces[54,5]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(41) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,5]=essai[2..19,2]
+matrix deces[74,5]=r(TCM)
+matrix deces[75,5]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(45) tcmcomp(`TCMH9800reg')
+matrix essai=r(donnees)
+local TCMH18=r(TCM)
+matrix deces[35,6]=essai[2..19,2]
+matrix deces[53,6]=r(TCM)
+matrix deces[54,6]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(45) tcmcomp(`TCMF9800reg')
+matrix essai=r(donnees)
+local TCMF=r(TCM)
+matrix deces[56,6]=essai[2..19,2]
+matrix deces[74,6]=r(TCM)
+matrix deces[75,6]=r(pvalue)
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2411)
+local TCMH=r(TCM)
+matrix deces[77,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2411)
+local TCMF=r(TCM)
+matrix deces[77,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2412)
+local TCMH=r(TCM)
+matrix deces[78,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2412)
+local TCMF=r(TCM)
+matrix deces[78,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2413)
+local TCMH=r(TCM)
+matrix deces[79,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2413)
+local TCMF=r(TCM)
+matrix deces[79,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2414)
+local TCMH=r(TCM)
+matrix deces[80,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2414)
+local TCMF=r(TCM)
+matrix deces[80,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2421)
+local TCMH=r(TCM)
+matrix deces[81,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2421)
+local TCMF=r(TCM)
+matrix deces[81,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2422)
+local TCMH=r(TCM)
+matrix deces[82,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2422)
+local TCMF=r(TCM)
+matrix deces[82,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2423)
+local TCMH=r(TCM)
+matrix deces[83,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2423)
+local TCMF=r(TCM)
+matrix deces[83,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2424)
+local TCMH=r(TCM)
+matrix deces[84,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2424)
+local TCMF=r(TCM)
+matrix deces[84,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2431)
+local TCMH=r(TCM)
+matrix deces[85,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2431)
+local TCMF=r(TCM)
+matrix deces[85,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2432)
+local TCMH=r(TCM)
+matrix deces[86,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2432)
+local TCMF=r(TCM)
+matrix deces[86,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2433)
+local TCMH=r(TCM)
+matrix deces[87,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2433)
+local TCMF=r(TCM)
+matrix deces[87,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2434)
+local TCMH=r(TCM)
+matrix deces[88,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2434)
+local TCMF=r(TCM)
+matrix deces[88,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2441)
+local TCMH=r(TCM)
+matrix deces[89,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2441)
+local TCMF=r(TCM)
+matrix deces[89,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2442)
+local TCMH=r(TCM)
+matrix deces[90,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2442)
+local TCMF=r(TCM)
+matrix deces[90,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2443)
+local TCMH=r(TCM)
+matrix deces[91,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2443)
+local TCMF=r(TCM)
+matrix deces[91,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2444)
+local TCMH=r(TCM)
+matrix deces[92,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2444)
+local TCMF=r(TCM)
+matrix deces[92,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2451)
+local TCMH=r(TCM)
+matrix deces[93,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2451)
+local TCMF=r(TCM)
+matrix deces[93,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2452)
+local TCMH=r(TCM)
+matrix deces[94,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2452)
+local TCMF=r(TCM)
+matrix deces[94,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2453)
+local TCMH=r(TCM)
+matrix deces[95,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2453)
+local TCMF=r(TCM)
+matrix deces[95,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2461)
+local TCMH=r(TCM)
+matrix deces[96,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2461)
+local TCMF=r(TCM)
+matrix deces[96,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2462)
+local TCMH=r(TCM)
+matrix deces[97,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2462)
+local TCMF=r(TCM)
+matrix deces[97,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2463)
+local TCMH=r(TCM)
+matrix deces[98,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2463)
+local TCMF=r(TCM)
+matrix deces[98,2]=`TCMF'
+
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(1) codegeo(2464)
+local TCMH=r(TCM)
+matrix deces[99,1]=`TCMH'
+tcm, s10(`s10') anneepop(1999) annees(1998/2000) sexe(2) codegeo(2464)
+local TCMF=r(TCM)
+matrix deces[99,2]=`TCMF'
+
+use "C:\ado\personal\files\dccentre8000reduit.dta", clear
+tab annee deptdom if S10==`s10' & sexe==1 , matcell(nbH)
+matrix deces[101,1]=nbH
+tab annee deptdom if S10==`s10' & sexe==2 , matcell(nbF)
+matrix deces[121,1]=nbF
+
+matrix list deces
+
+
+end
diff --git a/Modules/ado/personal/c/cfa.ado b/Modules/ado/personal/c/cfa.ado
new file mode 100644
index 0000000..006cbf4
--- /dev/null
+++ b/Modules/ado/personal/c/cfa.ado
@@ -0,0 +1,363 @@
+capture program drop cfa
+program cfa,rclass
+syntax varlist, PARTition(numlist integer >0) [SCOrename(string) CFAMethod(string) CFAStand]
+
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+local name
+local nname
+if "`scorename'"=="" {
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local upscorename = upper("`scorename'")
+
+*capture calcscore `varlist', scorename(`upscorename') partition(`partition')
+
+local i = 0
+local y = 1
+tokenize `upscorename'
+foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ local a = "(``i'' -> `liste')"
+ local z `z' `a'
+
+ local y = `s'+1
+}
+/*
+local cpt = 0
+if "`cfa_ml'" != "" {
+ local method = "ml"
+ local cpt `cpt' + 1
+}
+if "`cfa_mlmv'" != "" {
+ local method = "mlmv"
+ local cpt `cpt' + 1
+}
+if "`cfa_adf'" != "" {
+ local method = "adf"
+ local cpt `cpt' + 1
+}
+else local method = "ml"
+if `cpt'>1 {
+ di in red "You must choose between cfa_ml, cfa_mlmv or cfa_adf (the options are exclusive)"
+ exit 119
+}
+*/
+
+
+if "`cfamethod'" == "" local cfamethod = "ml"
+
+if "`cfamethod'" != "ml" & "`cfamethod'" != "mlmv" & "`cfamethod'" != "adf" {
+ di "`cfamethod'"
+ di in red "option cfamethod incorrectly specified (choose among ml, mlmv and adf)"
+ error 198
+}
+
+
+if "`cfastand'" != "" local cfastand = "stand"
+
+di as result "{hline}"
+di "{bf:Confirmatory factor analysis}"
+di as result "{hline}"
+di
+
+qui sem `z', method(`cfamethod') `cfastand'
+
+/*
+sem (HA -> ioc1-ioc4) (PSE -> ioc5-ioc8) (W -> ioc9-ioc15) ///
+(BCC -> ioc16-ioc18) (AC -> ioc19-ioc21) (AE -> ioc22-ioc25) ///
+(LI -> ioc26-ioc32) (MOC -> ioc33-ioc37)
+,stand
+cov(e.ioc36*e.ioc37
+e.ioc28*e.ioc29 e.ioc14*e.ioc15 e.ioc23*e.ioc25 e.ioc33*e.ioc34 ///
+e.ioc9*e.ioc10 e.ioc6*e.ioc8 e.ioc5*e.ioc7) // method(mlmv)
+*/
+
+/* factor loadings */
+
+matrix r = r(table)
+matrix r = r[1,1...]
+matrix r = r'
+local n = `nbvars'*2
+
+matrix a = r[1,1]
+forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix a = a\b
+}
+
+/* standard error */
+
+matrix r = r(table)
+matrix r = r[2,1...]
+matrix r = r'
+local n = `nbvars'*2
+
+matrix se = r[1,1]
+forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix se = se\b
+}
+
+
+/* intercepts */
+
+matrix r = r(table)
+matrix r = r[1,1...]
+matrix r = r'
+local n = `nbvars'*2
+
+matrix a2 = r[2,1]
+forvalues i=4(2)`n' {
+ matrix b = r[`i',1]
+ matrix a2 = a2\b
+}
+
+/* variances des erreurs */
+
+local m = `n'+1
+matrix r = r(table)
+matrix r = r[1,`m'...]
+matrix r = r'
+
+matrix a3 = r[1,1]
+forvalues i=2/`nbvars' {
+ matrix b = r[`i',1]
+ matrix a3 = a3\b
+}
+
+/* variance des dimensions*/
+
+matrix r = r(table)
+local n = `nbvars'*3+1
+matrix r = r[1,`n'...]
+matrix r = r'
+
+matrix var = r[1,1]
+forvalues i=2/`P' {
+ matrix b = r[`i',1]
+ matrix var = var\b
+}
+
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+
+local i = 1
+foreach s in `scorename' {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+
+}
+
+local max = 10
+local dec = `max'+5
+
+local max2 = 10
+
+local dec2 = `dec'+`max2'+5
+
+local a = e(N)
+di "{text:Number of used individuals: `a'}"
+di
+di _col(`=`dec2'+17+4') "{bf:Estimation:}"
+
+
+di as result "{bf:Item}" _c
+di _col(`dec') "{bf:Dimension}" _c
+*local col = `dec'+17
+di _col(`dec2') "{bf:Factor}" _c
+*local col = `dec2'+17
+di _col(`=`dec2'+14') "{bf:Standard}" _c
+*local col = `col'+17
+di _col(`=`dec2'+28') "{bf:Intercept}" _c
+*local col = `col'+13
+
+
+if "`cfastand'" == "" {
+ di _col(`=`dec2'+42') "{bf:Variance of}" _c
+ di _col(`=`dec2'+56') "{bf:Variance of}"
+
+ di _col(`dec2') "{bf:loading}" _c
+ *local col = `dec2'+17
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ *local col = `col'+30
+
+ di _col(`=`dec2'+42') "{bf:error}" _c
+ di _col(`=`dec2'+56') "{bf:dimension}"
+ local h = `dec2'+66
+}
+else {
+ di _col(`=`dec2'+42') "{bf:Variance of}"
+
+ di _col(`dec2') "{bf:loading}" _c
+ *local col = `dec2'+17
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ *local col = `col'+30
+
+ di _col(`=`dec2'+42') "{bf:errors}"
+ local h = `dec2'+52
+}
+
+
+di "{hline `h'}"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ tokenize `sc'
+ di "{bf:`var`z''}"_c
+ di _col(`dec') "{bf:``i''}" _c
+ local t = a[`z',1]
+ local t : di %7.2f `t'
+ *local col = `dec'+17
+ di _col(`dec2') "{text:`t'}" _c
+
+ local t = se[`z',1]
+ local t : di %8.2f `t'
+ *local col = `dec2'+9
+ di _col(`=`dec2'+14') "{text:`t'}" _c
+
+ local t = a2[`z',1]
+ local t : di %9.2f `t'
+ *local col = `col'+17
+ di _col(`=`dec2'+28') "{text:`t'}" _c
+
+ local t = a3[`z',1]
+ local t : di %11.2f `t'
+ *local col = `col'+13
+
+
+ if "`cfastand'" == "" & `z' == `y'{
+ di _col(`=`dec2'+42') "{text:`t'}" _c
+ local t = var[`i',1]
+ local t : di %11.2f `t'
+ *local col = `dec2'+17+17+13+14
+ di _col(`=`dec2'+56') "{text:`t'}"
+ }
+ else di _col(`=`dec2'+42') "{text:`t'}"
+ }
+ di
+ local `i++'
+ local y = `s'+1
+}
+
+qui estat gof, stats(all)
+
+local chi2 = r(chi2_ms)
+local p = r(p_ms)
+local ddl = r(df_ms)
+local ratio = `chi2'/`ddl'
+local rmsea = r(rmsea)
+local lb = r(lb90_rmsea)
+local ub = r(ub90_rmsea)
+local nfi = 1-(r(chi2_ms)/r(chi2_bs))
+local rni = 1-(r(chi2_ms)-r(df_ms))/(r(chi2_bs)-r(df_bs))
+local cfi = r(cfi)
+local ifi = (r(chi2_bs)-r(chi2_ms))/(r(chi2_bs)-r(df_ms))
+local mci = exp(-0.5*((r(chi2_ms)-r(df_ms))/(e(N)-1)))
+local srmr = r(srmr)
+
+di
+di "{bf:Goodness of fit}"
+di
+
+di as result _col(4) "chi2" _c
+di as result _col(20) "ddl" _c
+di as result _col(28) "chi2/ddl" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI" _c
+di as result _col(94) "CFI" _c
+di as result _col(104) "IFI" _c
+di as result _col(114) "MCI"
+
+*di as result "`P' dimensions" _c
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `up'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}" _c
+local t : di %5.3f `cfi'
+di _col(92) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(102) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(112) "{text:`t'}"
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+
+
+/*
+matrix ind = (`chi2',`ddl',`ratio',`rmsea',`nfi',`rni',`cfi',`ifi',`srmr')
+matrix colnames ind = "chi2" "ddl" "chi2/ddl" "RMSEA" "NFI" "RNI" "CFI" "IFI" "SRMR"
+matrix rownames ind = ""
+di
+di "{bf:Goodness of fit}"
+matrix list ind, format(%6.3f) noheader
+*/
+end
+
+*cfa ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(HAaaaaaaaaaaaaaaaaaaaaaaaaaz PSE W BCC AC AE LI MOC) cfamethod(ml) //cfastand
+*cfa x1-x40, partition(5 5 5 5 5 5 5 5) cfastand
diff --git a/Modules/ado/personal/c/checkfor2.ado b/Modules/ado/personal/c/checkfor2.ado
new file mode 100644
index 0000000..a5e40ff
--- /dev/null
+++ b/Modules/ado/personal/c/checkfor2.ado
@@ -0,0 +1,168 @@
+*!Version 1.1
+*!Data management utility: check for existence of variables in a dataset.
+*!Authors: Amadou Bassirou DIALLO (World Bank) and Jean-Benoit Hardouin (Regional Health Observatory of Orléans)
+
+program checkfor2 , rclass
+version 8
+syntax anything [if] [in] [, noList Tolerance(real 0) TAble noSUm GENMiss(namelist min=1 max=1) MISsing(string)]
+
+marksample touse
+tempname rat
+local av
+local unav
+local manymissings
+local avnum
+
+quietly count if `touse'
+local tot = r(N)
+
+qui isvar `anything'
+local badlist `r(badlist)'
+local varlist `r(varlist)'
+
+di _n
+if "`table'"!="" {
+ if "`badlist'"!="" {
+ di _col(4) in green "{hline 39}"
+ di _col(4)in green "Unavailable variables: "
+ foreach i of local badlist {
+ di _col(4) in ye "`i'"
+ }
+ di _col(4) in green "{hline 39}"
+ di
+ }
+ di _col(4) in green "{hline 39}"
+ display _col(4) in gr "Existing" _col(15) in gr "Rate of"
+ display _col(4) in gr "Variable" _col(14) "missings" _col(26) "Type" _col(34) "Available"
+ di _col(4) in green "{hline 39}"
+}
+
+tokenize `varlist'
+local nbvar : word count `varlist'
+
+forvalues i=1/`nbvar' {
+ capture assert missing(``i'') if `touse'
+ local ty: type ``i''
+ local tty = substr("`ty'", 1, 3)
+ if !_rc {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is empty in the database." in ye " ``i''" in gr " is not added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" _col(15) in ye "100.00%" _col(26) "`ty'"
+ }
+ local manymissings `manymissings' ``i''
+ }
+ else {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " exists and is not empty."
+ }
+ *Consider type
+ if "`tty'" == "str" {
+ qui count if (``i'' == ""|``i''=="`missing'") & `touse'
+ local num = r(N)
+ scalar `rat' = (`num'/`tot')*100
+ }
+ else {
+ local avnum `avnum' ``i''
+ capture confirm number `missing'
+ if _rc!=0 {
+ quietly count if ``i'' >= . & `touse'
+ }
+ else {
+ quietly count if (``i'' >= .|``i''==`missing') & `touse'
+ }
+ local num = r(N)
+ scalar `rat' = (`num'/`tot')*100
+ }
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has " in ye r(N) in gr " missings."
+ display in gr "Ratio number of missings of" in ye " ``i''" in gr " to total number of observations: " in ye %6.2f `rat' "%"
+ }
+
+ if `rat' <= `tolerance' {
+ local av `av' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" in ye _col(15) %6.2f `rat' "%" _col(26) "`ty'" _col(34) "X"
+ }
+ }
+ else {
+ local manymissings `manymissings' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has too many missings, compared to the tolerance level."
+ display in ye "``i''" in gr " is not added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" _col(15) in ye %6.2f `rat' "%" _col(26) "`ty'"
+ }
+ }
+ }
+ if "`table'"=="" {
+ di
+ }
+}
+
+if "`table'"!="" {
+ di _col(4) in green "{hline 39}"
+}
+
+return local available `av'
+return local unavailable `badlist'
+return local manymissings `manymissings'
+
+if "`avnum'" ~= ""&"`sum'"=="" {
+ display _newline
+ display in ye _col(14) "Unweighted summary statistics for available variables:" _n
+ capture confirm number `missing'
+ if _rc!=0 {
+ summarize `avnum' if `touse'
+ }
+ else {
+ foreach i of local avnum {
+ summarize `i' if `touse'&`i'!=`missing'
+ }
+ }
+}
+
+if "`list'"== "" {
+ display _newline
+ display in ye _d(97) "_"
+ display _newline
+ if "`badlist'"~="" {
+ display in gr "Unavailable variables: " in ye _col(45) "`badlist'" _n
+ }
+ if "`av'"~="" {
+ display in gr "Available variables: " in ye _col(45) "`av'" _n
+ }
+ if "`manymissings'"~="" {
+ display in gr "Available variables but with too missings: " in ye _col(45) "`manymissings'" _n
+ }
+ display in ye _d(97) "_"
+}
+
+if "`genmiss'" !="" {
+ capture confirm variable `genmiss'
+ if _rc!=0 {
+ qui gen `genmiss' = 0
+ local nbav : word count `av'
+ tokenize `av'
+ forvalues i=1/`nbav' {
+ local ty: type ``i''
+ local tty = substr("`ty'", 1, 3)
+ if "`tty'" == "str" {
+ qui replace `genmiss'=`genmiss'+1 if ``i''=="."
+ }
+ else {
+ qui replace `genmiss'=`genmiss'+1 if ``i''>=.
+ }
+ }
+ }
+ else {
+ di in green "The variable" in ye " `genmiss' " in green "already exists".
+ }
+}
+
+end
diff --git a/Modules/ado/personal/c/checkfor2.hlp b/Modules/ado/personal/c/checkfor2.hlp
new file mode 100644
index 0000000..462848f
--- /dev/null
+++ b/Modules/ado/personal/c/checkfor2.hlp
@@ -0,0 +1,88 @@
+{smcl}
+{hline}
+help for {cmd:checkfor2} {right:Amadou B. DIALLO}
+ {right:Jean-Benoit HARDOUIN}
+{hline}
+
+{title:Allows checking whether a variable exists or not in a dataset.}
+
+{p 4 8 2}{cmd:checkfor2} {it:anything} [{cmd:,}
+ {cmdab:t:olerance}({it:#}) {cmdab:ta:ble} {cmdab:nol:ist} {cmdab:nosu:m}
+ {cmdab:genm:iss}({it:newvarname}) {cmdab:mis:sing}({it:string})]
+
+{title:Description}
+
+{p 4 4 2}{cmd:checkfor2} is a data management routine to check for existence of variables
+within a (usually big) data set.
+
+{p 4 4 2}{cmd:checkfor2} searchs through the data whether each variable exists.
+The variables are clustered between unavailable variables, available variables with
+a little amount of missing values and available variables with too many missing values.
+
+{p 4 4 2}{cmd:isvar} must be installed ({stata ssc install isvar:ssc install isvar}).
+
+{title:Options}
+
+{p 4 4 2}{it:anything} is composed of variable names or lists of variables,
+
+{p 4 4 2}{cmd:tolerance} is the tolerance level (in percentage) to consider a variable as available, with default 0,
+
+{p 4 4 2}{cmd:nolist} avoids displaying availability status at the end of the process,
+
+{p 4 4 2}{cmd:nosum} avoids displaying summary statistics of available variables,
+
+{p 4 4 2}{cmd:table} displays the results in a table (instead as text),
+
+{p 4 4 2}{cmd:genmiss} creates a new variable containing the number of missing values among the available variables,
+
+{p 4 4 2}{cmd:missing} defines a specific value or string considered as a missing value.
+
+
+{title:Saved results}
+
+{p 4 4 2} {cmd:r(unavailable)} names of unavailable variables.{p_end}
+
+{p 4 4 2} {cmd:r(available)} names of available variables with a small amount of missing values.{p_end}
+
+{p 4 4 2} {cmd:r(manymissings)} names of variables present but with too missings.{p_end}
+
+{title:Examples}
+
+{p 4 4 2}{cmd:. use mydata, clear }{p_end}
+
+{p 4 4 2}{cmd:. checkfor2 x y z , mis(99) genmiss(countmiss) }{p_end}
+
+{p 4 4 2}{cmd:. su `r(available)' }{p_end}
+
+{p 4 4 2}{cmd:. tab countmiss }{p_end}
+
+{p 4 4 2}{cmd:. u bigdataset in 1/100, clear // Big data set}{p_end}
+
+{p 4 4 2}{cmd:. checkfor2 v1 v2 v3 xx yy , nosum tol(5) tab}{p_end}
+
+{p 4 4 2}{cmd:. use `r(available)' using bigdataset, clear }{p_end}
+
+{title:Remarks}
+
+{p 4 4 2}{cmd:checkfor2} and its primary version ({cmd:checkfor}) have been primarily written for comparable surveys such as the Demography and
+Health Surveys (DHS) or the Multiple Indicator Cluster Surveys (MICS). But this could easily applied
+to any other survey.
+
+{title:Authors}
+
+{p 4 4 2}Amadou Bassirou DIALLO.
+Poverty and Health Division, PREM, The World Bank.{p_end}
+{p 4 4 2}Email: {browse "mailto:adiallo5@worldbank.org":adiallo5@worldbank.org}
+
+{p 4 4 2}Jean-Benoit HARDOUIN.
+Regional Health Observatory of Orléans, France.{p_end}
+{p 4 4 2}Email: {browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+
+{title:Aknowledgements}
+
+{p 4 4 2}We would like to thank Christophe Rockmore and also Nick Cox
+and Kit Baum for their comments.
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help checkfor}, {help isvar}, {help nmissing}, {help npresent}, {help missing} and {help dropmiss} if installed.{p_end}
diff --git a/Modules/ado/personal/c/checkvars.ado b/Modules/ado/personal/c/checkvars.ado
new file mode 100644
index 0000000..787c343
--- /dev/null
+++ b/Modules/ado/personal/c/checkvars.ado
@@ -0,0 +1,133 @@
+*!Version 1.1
+*!Data management utility: check for existence of variables in a dataset.
+*!Authors: Amadou Bassirou DIALLO (World Bank) and Jean-Benoit Hardouin (Regional Health Observatory of Orléans)
+
+program checkvars, rclass
+version 8
+syntax anything [if] [in] [, noList Tolerance(real 0) TAble noSUm GENMiss(namelist min=1 max=1)]
+
+marksample touse
+tempname rat
+local av
+local unav
+local manymissings
+
+quietly count if `touse'
+local tot = r(N)
+
+qui isvar `anything'
+local badlist `r(badlist)'
+local varlist `r(varlist)'
+
+if "`table'"!="" {
+ if "`badlist'"!="" {
+ di _col(4)in green "Unavailable variables: " in ye "`badlist'"
+ di
+ }
+ di _col(4) in green "{hline 29}"
+ display _col(4) in gr "Existing" _col(15) in gr "Rate of"
+ display _col(4) in gr "Variable" _col(14) "missings" _col(24) "Available"
+ di _col(4) in green "{hline 29}"
+}
+
+tokenize `varlist'
+local nbvar:word count `varlist'
+
+forvalues i=1/`nbvar' {
+ capture assert missing(``i'') if `touse'
+ if !_rc {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is empty in the database." in ye " ``i''" in gr ///
+ " is not added to the available list"
+ }
+ else {
+ display _col(4) in gr "``i''" _col(14) "100.00%"
+ }
+ }
+ else {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " exists and is not empty."
+ }
+ *if "`available'"~= "" {
+ quietly count if ``i'' >= . & `touse'
+ local num = r(N)
+ scalar `rat' = (`num'/`tot')*100
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has " in ye r(N) in gr " missings."
+ display in gr "Ratio number of missings of" in ye " ``i''" in gr ///
+ " to total number of observations: " in ye %6.2f `rat' "%"
+ }
+ if `rat' <= `tolerance' {
+ local av `av' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is added to the available list."
+ }
+ else {
+ display _col(4) in gr "``i''" in ye _col(15) %6.2f `rat' "%" _col(32) "X"
+ }
+ }
+ else {
+ local manymissings `manymissings' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has too many missings, compared to the tolerance level."
+ display in ye "``i''" in gr " is not added to the available list."
+ }
+ else {
+ display _col(4) in gr "``i''" _col(15) in ye %6.2f `rat' "%"
+ }
+ }
+ *}
+ }
+ if "`table'"=="" {
+ di
+ }
+}
+if "`table'"!="" {
+ di _col(4) in green "{hline 29}"
+}
+
+return local available `av'
+return local unavailable `badlist'
+return local manymissings `manymissings'
+
+if "`av'" ~= ""&"`sum'"=="" {
+ display _newline
+ display in ye _col(14) "Unweighted summary statistics for available variables:" _n
+ summarize `av' if `touse'
+}
+
+
+if "`list'"== "" {
+ display _newline
+ display in ye _d(97) "_"
+ display _newline
+ if "`badlist'"~="" {
+ display in gr "Unavailable variables: " in ye _col(45) "`badlist'" _n
+ }
+ if "`av'"~="" {
+ display in gr "Available variables: " in ye _col(45) "`av'" _n
+ }
+ if "`manymissings'"~="" {
+ display in gr "Available variables but with too missings: " in ye _col(45) "`manymissings'" _n
+ }
+ display in ye _d(97) "_"
+}
+
+if "`genmiss'" !="" {
+ capture confirm variable `genmiss'
+ if _rc!=0 {
+ qui gen `genmiss'=0
+ local nbav:word count `av'
+ tokenize `av'
+ forvalues i=1/`nbav' {
+ qui replace `genmiss'=`genmiss'+1 if ``i''>=.
+ }
+ }
+ else {
+ di in green "The variable" in ye " `genmiss' " in green "already exists".
+ }
+
+}
+
+
+end
diff --git a/Modules/ado/personal/c/checkvars.hlp b/Modules/ado/personal/c/checkvars.hlp
new file mode 100644
index 0000000..fc4d646
--- /dev/null
+++ b/Modules/ado/personal/c/checkvars.hlp
@@ -0,0 +1,90 @@
+{smcl}
+{hline}
+help for {cmd:checkvars} {right:Amadou B. DIALLO}
+ {right:Jean-Benoit HARDOUIN}
+{hline}
+
+{title:Allows checking whether a variable exists or not in a dataset.}
+
+
+{p 4 8 2}{cmd:checkvars} {it:anything} [{cmd:,}
+ {cmdab:t:olerance}({it:#}) {cmdab:ta:ble} {cmdab:nol:ist} {cmdab:nosu:m}
+ {cmdab:genm:iss}({it:newvarname})]
+
+{title:Description}
+
+{p 4 4 2}{cmd:checkvars} is a routine to check for existence of variables
+within a (usually big) data set.
+
+{p 4 4 2}{cmd:checkvars} searchs through the data whether each variable exists.
+The variables are clustered between unavailable variables, available variables with
+a little amount of missing values and available variables with too many missing values.
+
+{p 4 4 2}{cmd:isvar} must be installed ({stata ssc install isvar:ssc install isvar}).
+
+{title:Options}
+
+{p 4 4 2}{it:anything} is composed of variable names or lists of variables,
+
+{p 4 4 2}{cmd:tolerance} is the tolerance level (in percentage) to consider a variable as available, with default 0,
+
+{p 4 4 2}{cmd:nolist} avoids displaying availability status at the end of the process,
+
+{p 4 4 2}{cmd:nosum} avoids displaying summary statistics of available variables,
+
+{p 4 4 2}{cmd:table} displays the results in a table (instead as text),
+
+{p 4 4 2}{cmd:genmiss} creates a new variable containing the number of missing values among the available variables.
+
+
+
+{title:Saved results}
+
+{p 4 4 2} {cmd:r(unavailable)} names of unavailable variables.{p_end}
+
+{p 4 4 2} {cmd:r(available)} names of available variables with a small amount of missing values.{p_end}
+
+{p 4 4 2} {cmd:r(manymissings)} names of variables but with too missings.{p_end}
+
+{title:Examples}
+
+{p 4 4 2}{cmd:. use mydata, clear }{p_end}
+
+{p 4 4 2}{cmd:. checkvars x y z ,genmiss(countmiss) }{p_end}
+
+{p 4 4 2}{cmd:. su `r(available)' }{p_end}
+
+{p 4 4 2}{cmd:. tab countmiss }{p_end}
+
+{p 4 4 2}{cmd:. u bigdataset in 1/100, clear // Big data set}{p_end}
+
+{p 4 4 2}{cmd:. checkvars v1 v2 v3 xx yy , nosum tol(5) tab}{p_end}
+
+{p 4 4 2}{cmd:. use `r(available)' using bigdataset, clear }{p_end}
+
+{title:Remarks}
+
+{p 4 4 2}{cmd:checkvars} and its primary versions ({cmd:checkfor} and {cmd:checkfor2}) have been primarily written for comparable surveys such as the Demography and
+Health Surveys (DHS) or the Multiple Indicator Cluster Surveys (MICS). But this could easily applied
+to any other survey.
+
+{title:Authors}
+
+{p 4 4 2}Amadou Bassirou DIALLO.
+Poverty and Health Specialist. AFTPM, The World Bank.{p_end}
+{p 4 4 2}Email: {browse "mailto:adiallo5@worldbank.org":adiallo5@worldbank.org}
+
+{p 4 4 2}Jean-Benoit HARDOUIN.
+Regional Health Observatory of Orléans, France.{p_end}
+{p 4 4 2}Email: {browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+
+{title:Aknowledgements}
+
+{p 4 4 2}We would like to thank Christophe Rockmore and also Nick Cox
+and Kit Baum for their comments.
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help checkfor}, {help checkfor2}, {help isvar}, {help nmissing}, {help npresent}, {help missing} and {help dropmiss} if installed.{p_end}
+
+
diff --git a/Modules/ado/personal/c/clv.ado b/Modules/ado/personal/c/clv.ado
new file mode 100644
index 0000000..3804708
--- /dev/null
+++ b/Modules/ado/personal/c/clv.ado
@@ -0,0 +1,957 @@
+*! Version 2.17 10July2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.14 : May 20th, 2010 /*dim and std options for biplots*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+* Version 2.9 (2006-01-26): Jean-Benoit Hardouin /*save the latent variables*/
+* Version 2.10 (2006-07-10): Jean-Benoit Hardouin /*2nd order relative variation of the T criterion*/
+* Version 2.11 (2006-10-09): Jean-Benoit Hardouin /*Size of the text in the dendrogram*/
+* Version 2.12 (2006-12-01): Jean-Benoit Hardouin /*savedendro option*/
+* Version 2.13 (2010-05-12): Jean-Benoit Hardouin /*corrections of bugs in KERNEL option and with METHOD(centroid)*/
+* Version 2.14 (2010-05-20): Jean-Benoit Hardouin /*DIM and STD options for biplots*/
+* Version 2.15 (2014-04-14): Jean-Benoit Hardouin /*save and use options*/
+* Version 2.16 (2014-04-30): Jean-Benoit Hardouin, Bastien Perrot /*HTML option*/
+* Version 2.17 (2019-07-10): Jean-Benoit Hardouin /*filesave and dirsave options*/
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.sphere-nantes.fr
+*
+* Copyright 2005-2006, 2010, 2014, 2019 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 clv,rclass
+version 10
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 40) bar CONSolidation(int 0) noDENdro SAVEDendro(string) noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string) replace TEXTSize(string) std dim(string) save(string) use(string) FILESave DIRSave(string)]
+preserve
+tempfile clvfile
+tempvar id
+gen `id'=_n
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"==""&"`use'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+if "`filesave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ local fsb saving(`dirsave'//bar,replace)
+ local fsd saving(`dirsave'//dendrogram,replace)
+ local fsbi saving(`dirsave'//biplot,replace)
+}
+tempname matclus vp indexes
+
+/*********TESTS**********/
+
+if "`use'"!="" {
+ local error=0
+ capture matrix `vp'=`use'_vp
+ if _rc!=0 {
+ local error=_rc
+ }
+ capture matrix `matclus'=`use'_matclus
+ if _rc!=0 {
+ local error=_rc
+ }
+ local varlist $`use'_varlist
+ local method $`use'_method
+ local kernel $`use'_kernel
+ if "`varlist'"==""|"`method'"=="" {
+ local error=1
+ }
+ if `error'!=0 {
+ di in red "You cannot use the {hi:use} option without a preliminary use of the {hi:save} option"
+ error 198
+ exit
+ }
+}
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+
+
+/*******DEFINES THE LABELS AND STANDARDIZED THE VARIABLES (IF NECESSARY)*******/
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+/*COMPUTES THE TOTAL VARIANCE*/
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+/***** DEFINES THE KERNEL IF NECESSARY ********/
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ local eigen2=0
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+
+/*******DISPLAY THE FIRST RESULTS *******/
+
+di
+di in green "{hline 32}"
+di in green "TOTAL VARIANCE: " in ye %16.5f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %9.0f `nbind'
+di in green "METHOD:" in ye _col(`=33-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 32}"
+di
+
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+
+/******** CLASSIFICATION PROCEDURE*******/
+
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',12,0)
+ matrix `indexes'=J(`nbitems',8,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',10]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',10]=1
+ }
+ matrix `vp'[`i',1]=`i'
+ matrix `vp'[`i',2]=`nbitems'
+ matrix `vp'[`i',8]=`totvar'
+ matrix `vp'[`i',9]=100
+ }
+ matrix `vp'[`nbitems',5]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 101}"
+ di in green _col(93) "2nd order"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative" _col(94) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation" _col(93) "Variation"
+ di in green "{hline 101}"
+ }
+ else {
+ local crit T
+ di in green "{hline 111}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal" _col(103) "2nd order"
+ }
+ else {
+ di in green _col(84) "Current" _col(103) "2nd order"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative" _col(104) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation" _col(103) "Variation"
+ di in green "{hline 111}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local ev2=max(`vp'[`j',11],`vp'[`k',11],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ matrix `vp'[`clus',1]=`nbitems'+`i' /*PARENT*/
+ matrix `vp'[`clus',2]=`=`nbitems'-`i'' /*NUMBER OF CLUSTERS*/
+ matrix `vp'[`clus',3]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',4]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',6]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `vp'[`clus',5]=`vp'[`=`clus'-1',5]-`vp'[`clus',6] /*T or G CRITERION*/
+ matrix `vp'[`clus',7]=(`vp'[`clus',6]-`vp'[`=`clus'-1',6])/`vp'[`=`clus'-1',6] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `vp'[`clus',8]=`vp'[`=`clus'-1',8]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',9]=`vp'[`clus',8]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',10]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',11]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ }
+ if `vp'[`=`clus'-1',7]!=0 {
+ matrix `vp'[`clus',12]=(`vp'[`clus',7]-`vp'[`=`clus'-1',7])/abs(`vp'[`=`clus'-1',7]) /*2ND ORDER RELATIVE VARIATION OF THE T or G CRITERION*/
+ }
+ matrix `indexes'[`i',1]=`i' /*PARENT*/
+ matrix `indexes'[`i',2]=`nbitems'-`i' /*NUMBER OF CLUSTERS*/
+ matrix `indexes'[`i',3]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `indexes'[`i',4]=`vp'[`clus',7] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`i',5]=max(`eigen2',`indexes'[`=`i'-1',5]) /*MAXIMUM SECOND EIGENVALUE*/
+ matrix `indexes'[`i',7]=`vp'[`clus',12] /*2nd order RELATIVE VARIATION OF THE T OR G CRITERION*/
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ local varlistgen
+ local nbvarlistgen
+ forvalues j=1/`=`nbitems'+`i'' {
+ local varlist`j'
+ forvalues k=1/`nbitems' {
+ if `matclus'[`k',`=`i'+1']==`j' {
+ local varlist`j' `varlist`j'' ``k''
+ }
+ }
+ local nbvarlist`j': word count `varlist`j''
+ local varlistgen `varlistgen' `varlist`j''
+ local nbvarlistgen `nbvarlistgen' `nbvarlist`j''
+ }
+ local newlist
+ foreach m in `nbvarlistgen' {
+ if `m'!=0 {
+ local newlist `newlist' `m'
+ }
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',8]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ local relv2
+ }
+ else {
+ local relv=`indexes'[`i',4]*100
+ local percent %
+ if `indexes'[`i',7]!=. {
+ local relv2=`indexes'[`i',7]*100
+ }
+ else {
+ local relv2=0
+ }
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv2'
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) _col(84) %5.2f `relv' "`percent'" _col(93) %8.2f `relv2' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) %8.4f `vp'[`clus',11] _col(94) %6.2f `relv' "`percent'" _col(103) %8.2f `relv2' "`percent'"
+ }
+ }
+ }
+ matrix `indexes'[`nbitems',3]=`vp'[`=2*`nbitems'-1',5] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`nbitems',7]=`indexes'[`nbitems',3]/`indexes'[`=`nbitems'-1',3] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ local i=2*`nbitems'-1
+ matrix `threshold'[1,1]=`vp'[`i',5]/`vp'[`i',6]*100-100
+ matrix `threshold'[1,2]=(`threshold'[1,1]-`threshold'[2,1])/abs(`threshold'[2,1])*100
+ matrix `threshold'[1,3]=`vp'[`i',5]
+ if "`method'"=="centroid" {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(83) %6.2f `threshold'[1,1] "`percent'" _col(93) %8.2f `threshold'[1,2] "`percent'"
+ }
+ else {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(94) %6.2f `threshold'[1,1] "`percent'" _col(103) %8.2f `threshold'[1,2] "`percent'"
+ }
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ local demipart=int(`nbitems'/2)+1
+ forvalues i=1/`demipart' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 111}"
+ di
+ di in green "{hline 60}"
+ di in green "PROPOSED BEST PARTITIONS (AMONG THE `demipart' SMALLER PARTITIONS)"
+ di in green "{hline 60}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion: " _col(60) in gr "Partitions in " in ye `best' " or " `best2' in gr " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',1]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',1]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',1]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',1]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold: " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',6]=`totvar'-`T'
+ matrix `vp'[`i',8]=`T'
+ matrix `vp'[`i',9]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold (second order): " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ return local bestthresold2 `bestt' `bestt2'
+}
+/******BAR CHART *******/
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `indexes' ,names(v)
+ qui gen id=`nbitems'-_n
+ qui replace v7=. in 1
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v3 "T variation"
+ qui su v3 if id!=0
+ local maxv3=ceil(r(max)*5)/5
+ local minv3=floor(r(min)*5)/5
+ label variable v4 "Relative T variation"
+ label variable v7 "Relative T variation order 2"
+ qui graph twoway (bar v3 id, name(bar,replace) `fsb' vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+/****** DENDROGRAM********/
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `matclus' ,names(v)
+ local listorder
+ forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+ }
+ qui gen id=_n
+ qui sort `listorder'
+
+ capture cluster delete clv,zap
+ qui cluster complete v* ,name(clv)
+
+ qui replace clv_id=_n
+ qui replace clv_ord=id
+ qui replace clv_hgt=.
+
+ qui gen fait=0
+ qui gen clus=0
+ forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',3]<=`nbitems') {
+ local first=`vp'[`ligne',3]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',4]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',6] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',9] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',1] in 1
+ }
+if "`dendro'"=="" {
+ qui gen label=""
+ forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+ }
+ sort clv_id
+ if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+ }
+ else {
+ local var "Variables"
+ local cut label(label)
+ }
+ qui su clv_hgt
+ local tmp=r(max)
+ local max=floor(`tmp')+.5
+ if `tmp'>`max' {
+ local max=`max'+.5
+ }
+ local maxvar=`max'+5
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`textsize'"=="" {
+ local textsize: word `=min(int(`nbitems'/15)+1,5)' of medium medsmall small vsmall tiny
+ }
+ if "`horizontal'"!="" {
+ *matrix list clv
+ qui cluster dendro clv, name (dendrogram,replace) `fsd' hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut'
+ }
+ else {
+ qui cluster dendro clv, name(dendrogram,replace) `fsd' xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut'
+ }
+ if "`savedendro'"!="" {
+ qui graph save dendrogram `savedendro'
+ }
+}
+
+/***** END DENDROGRAM*****/
+
+/**** TEST ********/
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+
+/***** CONSOLIDATION PROCEDURE ********/
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=13
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "CLUSTER " %2.0f `g' _c
+ local col=`col'+12
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ local trace=e(trace)
+ local explained`g'=`tmp`g''*`var'/`trace'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ local trace=e(trace)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ local trace=0
+ forvalues m=1/`tmp`g''{
+ local trace =`trace'+`r(lambda`m')'
+ }
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local explained`g'=`lambda1'/`trace'
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ local explained`g'=1
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ di _col(1) in green "ITEMS :" _c
+ forvalues i=1/`max' {
+ local col=15
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+12
+ }
+ di
+ }
+ local col=16
+ di _col(1) in green "Expl. Var:" _c
+ forvalues g=1/`cons' {
+ di _col(`col') in ye %6.2f `=`explained`g''*100' in green "%" _c
+ local col= `col'+12
+ }
+ di
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ if "`replace'"!=""{
+ capture drop `genlv'`g'
+ }
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ qui set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ if "`dim'"=="" {
+ local dim 1 2
+ }
+ qui qui biplotvlab `latent' `add', name(biplot,replace) `fsbi' norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1) `std' dim(`dim')
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+/***** END OF THE CONSOLIDATION PROCEDURE********/
+
+qui set matsize `matsize'
+if "`genlv'"!="" {
+ qui keep `id' `genlv'1-`genlv'`cons'
+ tempfile lvfile
+ qui sort `id'
+ qui save `lvfile',replace
+}
+use `clvfile',replace
+if "`genlv'"!="" {
+ qui sort `id'
+ qui merge `id' using `lvfile'
+}
+qui drop `id'
+capture drop _merge
+capture cluster delete clv,zap
+matrix colnames `vp'="Parent" "Number of clusters" "Child 1" "Child 2" "T" "DeltaT" "deltaT" "Explained Variance" "Explained Variance (%)" "First eigenvalue" "Second Eigenvalue" "2nd order deltaT"
+if "`save'"!="" {
+ qui matrix `save'_vp=`vp'
+ qui matrix `save'_matclus=`matclus'
+ qui global `save'_varlist `varlist'
+ qui global `save'_method `method'
+ qui global `save'_kernel `kernel'
+}
+
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+restore,not
+end
diff --git a/Modules/ado/personal/c/clv.sthlp b/Modules/ado/personal/c/clv.sthlp
new file mode 100644
index 0000000..e402a26
--- /dev/null
+++ b/Modules/ado/personal/c/clv.sthlp
@@ -0,0 +1,122 @@
+{smcl}
+{* 29 juillet 2019}{* version 2.17}{...}
+{hline}
+help for {hi:clv}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Clustering around latent variables }
+
+{p 8 14 2}{cmd:clv} [{it:varlist}] [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [{cmd:weight}]
+[{cmd:,} {cmdab:nostand:ardized} {cmdab:ker:nel}({it:numlist}) {cmdab:meth:od}({it:keyword}) {cmdab:cons:olidation}({it:#}) {cmd:genlv}(string) {cmdab:rep:lace}
+{cmdab:noden:dro} {cmdab:saved:endro}({it:filename}[,replace]) {cmdab:cut:number}({it:#}) {cmdab:show:count} {cmdab:texts:ize}({it:string}) {cmdab:deltaT}
+{cmdab:hor:izontal} {cmdab:abb:rev}({it:#}) {cmdab:tit:le}({it:string}) {cmdab:cap:tion}({it:string})
+{cmdab:bar} {cmdab:nobip:lot} {cmdab:add:var} {cmd:std} {cmd:dim}({it:string}) {cmdab:files:ave} {cmdab:dirs:ave}({it:string})]
+
+
+
+
+{title:Description}
+
+{p 4 8 2}{cmd:clv} clusters variables around latent components. The variables are clustered by
+seeking to minimize at each step the decrease of the T criterion, computed as the sum of the
+first eigenvalues of the matrices of data of all the clusters. A hierarchical cluster analysis
+based on this criterion is performed. A iterative consolidation procedure can be subsequently run which
+allows each variable to be assigned to the latent component it is the most correlated with.
+
+{title:Options}
+
+{p 0 8 2}{cmd:Options concerning the method CLV}
+
+{p 4 8 2}{cmd:nostandardized} uses centered variables instead of standardized variables.
+
+{p 4 8 2}{cmd:kernel} defines one or several kernels of variables (variables which are clustered together in an initial step). The first number #k1 indicates that the first #k1 variables are clustered together, the second number #k2 indicates that the following #k2 variables are clustered together...
+
+{p 4 8 2}{cmd:method} indicates the method to cluster the variables among {it:classical} (by default) for the method described by Vigneau and Qannari,
+ {it:polychoric} for a use of the matrix of polychoric coefficients of correlation (instead of Pearson coefficients of correlation), {it:v2} for a modified
+ algorithm wich search to minimize the maximum second eigenvalue among the clusters of 2 variables and more, {it:polychoricv2} which correspond to the {it:v2}
+ option with the matrix of polychoric coefficients of correlation, and {it:centroid} which is defined by Vigneau and Qannari as an adaptation of CLV when
+ the sign of the correlation coefficients between the variables is important.
+
+{p 4 8 2}{cmd:consolidation} performs a consolidation procedure with the obtained partition into the specified number of clusters (by default, no consolidation procedure is performed).
+
+{p 4 8 2}{cmd:genlv} saves the latent variables in new variables with the defined string as prefix (followed by a number). This option must be used in conjonction with the {cmd:consolidation} option.
+
+{p 4 8 2}{cmd:replace} allows replacing the created variables with the {cmd:genlv} option if they already exist.
+
+{p 0 8 2}{cmd:Options concerning the drawing of the dendrogram}
+
+{p 4 8 2}{cmd:nodendro} avoids to display of the dendrogram.
+
+{p 4 8 2}{cmd:savedendro} saves the dendrogram in the file defined by this option. If this file already exists, it is possible to replace it with the {cmd:replace} option.
+
+{p 4 8 2}{cmd:cutnumber} defines the maximal number of clusters displayed in the dendrogram (40 by default).
+
+{p 4 8 2}{cmd:showcount} displays the number of variables in each cluster (useful with the {cmd:cutnumber} option).
+
+{p 4 8 2}{cmd:textsize} defines the size of the labels of the variables on the dendrogram (see {help textsizestyle}).
+
+{p 4 8 2}{cmd:deltaT} uses the variation of the T criterion as height variable for the dendrogram.
+
+{p 4 8 2}{cmd:horizontal} displays an horizontal (instead a vertical) dendrogram.
+
+{p 4 8 2}{cmd:abbrev} defines the length of the variables labels on the dendrogram (15 characters by default).
+
+{p 4 8 2}{cmd:title} defines the title of the dendrogram.
+
+{p 4 8 2}{cmd:caption} defines the caption of the axis of the dendrogram which indicates the names of the variables.
+
+{p 0 8 2}{cmd:Options concerning the others graphs}
+
+{p 4 8 2}{cmd:bar} displays a chart of the decrease in the T criterion at each step.
+
+{p 4 8 2}{cmd:nobiplot} avoids to display a biplot of the latent variables with the {cmd:consolidation} option.
+
+{p 4 8 2}{cmd:addvar} allows drawing the items on the graphical representation on the biplot.
+
+{p 4 8 2}{cmd:std} allows standardizing the latent variables for the graphical representation on the biplot.
+
+{p 4 8 2}{cmd:dim}({it:string}) allows choosing the axes represented on the biplot.
+
+{p 4 8 2}{cmd:filesave} allows saving the graphs in gph files on the default directory or on the directory defined by the {cmd:dirsave} option.
+
+{p 4 8 2}{cmd:dirsave}({it:string}) allows determining the directory to save the graphs (usefull with the {cmd:filesave} option).
+
+{p 4 8 2} If no {it:varlist} is indicated, the procedure uses the varlist from the last {cmd:clv} procedure, but does not perform the hierarchical cluster analysis.
+
+{title:Notes}
+
+{p 4 8 2} The classifications around latent variables (CLV) is defined by its authors (Vigneau and Qannari, 2003) only for continuous variables. Results with binary or ordinal variables must be interpreted with precautions.
+
+{p 4 8 2} Only {cmd:fweights} are allowed. The biplots are disabled if weights are used.
+
+{p 4 8 2} In this procedure, all the individuals with at least one missing value are omitted.
+
+{p 4 8 2} With the {it:polychoric} and {it:polychoricv2} methods, the {cmd:nostandardized} option is disabled.
+
+{p 4 8 2} This module uses the following modules downloadable on SSC: {stata ssc describe polychoric}, {stata ssc describe biplotvlab} and {stata ssc describe genscore}
+
+{title:Example}
+
+ {p 4 8 2}{cmd:. clv var1-var15} /*performs the HCA procedure*/
+
+ {p 4 8 2}{cmd:. clv var1-var15, cons(6) bar nodendro meth(centroid)} /* performs the HCA procedure based on the centroid method followed by a consolidation procedure with 6 clusters*/
+
+ {p 4 8 2}{cmd:. clv, cons(3) addvar} /*performs only the consolidation procedure with 3 clusters, based on the preceeding HCA procedure*/
+
+{title:Aknowledgements}
+
+{p 4 8 2} The author thanks Ronan Conroy for all the propositions of improvements.
+
+{title:Reference}
+
+{p 4 8 2} Vigneau E. and Qannari E. M. Clustering of variables around latent components. Communications in Statistics - Simulation and Computation. 32(4): 1131-1150, 2003.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}INSERM UMR 1246-SPHERE "MethodS in Patients-centered outcomes and HEalth ResEarch"{p_end}
+{p 4 8 2}Nantes University - University of Tours{p_end}
+{p 4 8 2}Institute for Research in Health 2 (IRS2), Nantes, France{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
diff --git a/Modules/ado/personal/c/clv212.ado b/Modules/ado/personal/c/clv212.ado
new file mode 100644
index 0000000..35d7f79
--- /dev/null
+++ b/Modules/ado/personal/c/clv212.ado
@@ -0,0 +1,907 @@
+*! Version 2.12 1December2006
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.12 : December 1st, 2006 /*savedendro option*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+* Version 2.9 (2006-01-26): Jean-Benoit Hardouin /*save the latent variables*/
+* Version 2.10 (2006-07-10): Jean-Benoit Hardouin /*2nd order relative variation of the T criterion*/
+* Version 2.11 (2006-10-09): Jean-Benoit Hardouin /*Size of the text in the dendrogram*/
+* Version 2.12 (2006-12-01): Jean-Benoit Hardouin /*savedendro option*/
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005-2006 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 clv,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 40) bar CONSolidation(int 0) noDENdro SAVEDendro(string) noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string) replace TEXTSize(string)]
+preserve
+tempfile clvfile
+tempvar id
+gen `id'=_n
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+tempname matclus vp indexes
+
+/*********TESTS**********/
+
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+
+
+/*******DEFINES THE LABELS AND STANDARDIZED THE VARIABLES (IF NECESSARY)*******/
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+/*COMPUTES THE TOTAL VARIANCE*/
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+/***** DEFINES THE KERNEL IF NECESSARY ********/
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+
+/*******DISPLAY THE FIRST RESULTS *******/
+
+di
+di in green "{hline 32}"
+di in green "TOTAL VARIANCE: " in ye %16.5f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %9.0f `nbind'
+di in green "METHOD:" in ye _col(`=33-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 32}"
+di
+
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+
+/******** CLASSIFICATION PROCEDURE*******/
+
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',12,0)
+ matrix `indexes'=J(`nbitems',8,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',10]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',10]=1
+ }
+ matrix `vp'[`i',1]=`i'
+ matrix `vp'[`i',2]=`nbitems'
+ matrix `vp'[`i',8]=`totvar'
+ matrix `vp'[`i',9]=100
+ }
+ matrix `vp'[`nbitems',5]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 101}"
+ di in green _col(93) "2nd order"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative" _col(94) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation" _col(93) "Variation"
+ di in green "{hline 101}"
+ }
+ else {
+ local crit T
+ di in green "{hline 111}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal" _col(103) "2nd order"
+ }
+ else {
+ di in green _col(84) "Current" _col(103) "2nd order"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative" _col(104) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation" _col(103) "Variation"
+ di in green "{hline 111}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local ev2=max(`vp'[`j',11],`vp'[`k',11],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ matrix `vp'[`clus',1]=`nbitems'+`i' /*PARENT*/
+ matrix `vp'[`clus',2]=`=`nbitems'-`i'' /*NUMBER OF CLUSTERS*/
+ matrix `vp'[`clus',3]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',4]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',6]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `vp'[`clus',5]=`vp'[`=`clus'-1',5]-`vp'[`clus',6] /*T or G CRITERION*/
+ matrix `vp'[`clus',7]=(`vp'[`clus',6]-`vp'[`=`clus'-1',6])/`vp'[`=`clus'-1',6] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `vp'[`clus',8]=`vp'[`=`clus'-1',8]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',9]=`vp'[`clus',8]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',10]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',11]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ }
+ if `vp'[`=`clus'-1',7]!=0 {
+ matrix `vp'[`clus',12]=(`vp'[`clus',7]-`vp'[`=`clus'-1',7])/abs(`vp'[`=`clus'-1',7]) /*2ND ORDER RELATIVE VARIATION OF THE T or G CRITERION*/
+ }
+ matrix `indexes'[`i',1]=`i' /*PARENT*/
+ matrix `indexes'[`i',2]=`nbitems'-`i' /*NUMBER OF CLUSTERS*/
+ matrix `indexes'[`i',3]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `indexes'[`i',4]=`vp'[`clus',7] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`i',5]=max(`eigen2',`indexes'[`=`i'-1',5]) /*MAXIMUM SECOND EIGENVALUE*/
+ matrix `indexes'[`i',7]=`vp'[`clus',12] /*2nd order RELATIVE VARIATION OF THE T OR G CRITERION*/
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ local varlistgen
+ local nbvarlistgen
+ forvalues j=1/`=`nbitems'+`i'' {
+ local varlist`j'
+ forvalues k=1/`nbitems' {
+ if `matclus'[`k',`=`i'+1']==`j' {
+ local varlist`j' `varlist`j'' ``k''
+ }
+ }
+ local nbvarlist`j': word count `varlist`j''
+ local varlistgen `varlistgen' `varlist`j''
+ local nbvarlistgen `nbvarlistgen' `nbvarlist`j''
+ }
+ local newlist
+ foreach m in `nbvarlistgen' {
+ if `m'!=0 {
+ local newlist `newlist' `m'
+ }
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',8]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ local relv2
+ }
+ else {
+ local relv=`indexes'[`i',4]*100
+ local percent %
+ if `indexes'[`i',7]!=. {
+ local relv2=`indexes'[`i',7]*100
+ }
+ else {
+ local relv2=0
+ }
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv2'
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) _col(84) %5.2f `relv' "`percent'" _col(93) %8.2f `relv2' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) %8.4f `vp'[`clus',11] _col(94) %6.2f `relv' "`percent'" _col(103) %8.2f `relv2' "`percent'"
+ }
+ }
+ }
+ matrix `indexes'[`nbitems',3]=`vp'[`=2*`nbitems'-1',5] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`nbitems',7]=`indexes'[`nbitems',3]/`indexes'[`=`nbitems'-1',3] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ local i=2*`nbitems'-1
+ matrix `threshold'[1,1]=`vp'[`i',5]/`vp'[`i',6]*100-100
+ matrix `threshold'[1,2]=(`threshold'[1,1]-`threshold'[2,1])/abs(`threshold'[2,1])*100
+ matrix `threshold'[1,3]=`vp'[`i',5]
+ if "`method'"=="centroid" {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(83) %6.2f `threshold'[1,1] "`percent'" _col(93) %8.2f `threshold'[1,2] "`percent'"
+ }
+ else {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(94) %6.2f `threshold'[1,1] "`percent'" _col(103) %8.2f `threshold'[1,2] "`percent'"
+ }
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ local demipart=int(`nbitems'/2)+1
+ forvalues i=1/`demipart' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 111}"
+ di
+ di in green "{hline 60}"
+ di in green "PROPOSED BEST PARTITIONS (AMONG THE `demipart' SMALLER PARTITIONS)"
+ di in green "{hline 60}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion: " _col(60) in gr "Partitions in " in ye `best' " or " `best2' in gr " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',1]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',1]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',1]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',1]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold: " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',6]=`totvar'-`T'
+ matrix `vp'[`i',8]=`T'
+ matrix `vp'[`i',9]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold (second order): " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ return local bestthresold2 `bestt' `bestt2'
+}
+/******BAR CHART *******/
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `indexes' ,names(v)
+ qui gen id=`nbitems'-_n
+ qui replace v7=. in 1
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v3 "T variation"
+ qui su v3 if id!=0
+ local maxv3=ceil(r(max)*5)/5
+ local minv3=floor(r(min)*5)/5
+ label variable v4 "Relative T variation"
+ label variable v7 "Relative T variation order 2"
+ graph twoway (bar v3 id, name(bar,replace) vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+/****** DENDROGRAM********/
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `matclus' ,names(v)
+ local listorder
+ forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+ }
+ qui gen id=_n
+ qui sort `listorder'
+
+ capture cluster delete clv,zap
+ qui cluster complete v* ,name(clv)
+
+ qui replace clv_id=_n
+ qui replace clv_ord=id
+ qui replace clv_hgt=.
+
+ qui gen fait=0
+ qui gen clus=0
+ forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',3]<=`nbitems') {
+ local first=`vp'[`ligne',3]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',4]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',6] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',9] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',1] in 1
+ }
+if "`dendro'"=="" {
+ qui gen label=""
+ forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+ }
+ sort clv_id
+ if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+ }
+ else {
+ local var "Variables"
+ local cut label(label)
+ }
+ qui su clv_hgt
+ local tmp=r(max)
+ local max=floor(`tmp')+.5
+ if `tmp'>`max' {
+ local max=`max'+.5
+ }
+ local maxvar=`max'+5
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`textsize'"=="" {
+ local textsize: word `=min(int(`nbitems'/15)+1,5)' of medium medsmall small vsmall tiny
+ }
+ if "`horizontal'"!="" {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut'
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut'
+ }
+ if "`savedendro'"!="" {
+ graph save dendrogram `savedendro'
+ }
+}
+
+/***** END DENDROGRAM*****/
+
+/**** TEST ********/
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+
+/***** CONSOLIDATION PROCEDURE ********/
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=13
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "CLUSTER " %2.0f `g' _c
+ local col=`col'+12
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ local trace=e(trace)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ local trace=0
+ forvalues m=1/`tmp`g''{
+ local trace =`trace'+`r(lambda`m')'
+ }
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local explained`g'=`lambda1'/`trace'
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ local explained`g'=1
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ di _col(1) in green "ITEMS :" _c
+ forvalues i=1/`max' {
+ local col=15
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+12
+ }
+ di
+ }
+ local col=16
+ di _col(1) in green "Expl. Var:" _c
+ forvalues g=1/`cons' {
+ di _col(`col') in ye %6.2f `=`explained`g''*100' in green "%" _c
+ local col= `col'+12
+ }
+ di
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ if "`replace'"!=""{
+ capture drop `genlv'`g'
+ }
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1)
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+/***** END OF THE CONSOLIDATION PROCEDURE********/
+
+set matsize `matsize'
+if "`genlv'"!="" {
+ qui keep `id' `genlv'1-`genlv'`cons'
+ tempfile lvfile
+ qui sort `id'
+ qui save `lvfile',replace
+}
+use `clvfile',replace
+if "`genlv'"!="" {
+ qui sort `id'
+ qui merge `id' using `lvfile'
+}
+qui drop `id'
+capture drop _merge
+capture cluster delete clv,zap
+matrix colnames `vp'="Parent" "Number of clusters" "Child 1" "Child 2" "T" "DeltaT" "deltaT" "Explained Variance" "Explained Variance (%)" "First eigenvalue" "Second Eigenvalue" "2nd order deltaT"
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+restore,not
+end
diff --git a/Modules/ado/personal/c/clv214.ado b/Modules/ado/personal/c/clv214.ado
new file mode 100644
index 0000000..bcb4db5
--- /dev/null
+++ b/Modules/ado/personal/c/clv214.ado
@@ -0,0 +1,916 @@
+*! Version 2.14 20May2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.14 : May 20th, 2010 /*dim and std options for biplots*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+* Version 2.9 (2006-01-26): Jean-Benoit Hardouin /*save the latent variables*/
+* Version 2.10 (2006-07-10): Jean-Benoit Hardouin /*2nd order relative variation of the T criterion*/
+* Version 2.11 (2006-10-09): Jean-Benoit Hardouin /*Size of the text in the dendrogram*/
+* Version 2.12 (2006-12-01): Jean-Benoit Hardouin /*savedendro option*/
+* Version 2.13 (2010-05-12): Jean-Benoit Hardouin /*corrections of bugs in KERNEL option and with METHOD(centroid)*/
+* Version 2.14 (2010-05-20): Jean-Benoit Hardouin /*DIM and STD options for biplots*/
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005-2006, 2010 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 clv,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 40) bar CONSolidation(int 0) noDENdro SAVEDendro(string) noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string) replace TEXTSize(string) std dim(string)]
+preserve
+tempfile clvfile
+tempvar id
+gen `id'=_n
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+tempname matclus vp indexes
+
+/*********TESTS**********/
+
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+
+
+/*******DEFINES THE LABELS AND STANDARDIZED THE VARIABLES (IF NECESSARY)*******/
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+/*COMPUTES THE TOTAL VARIANCE*/
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+/***** DEFINES THE KERNEL IF NECESSARY ********/
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ local eigen2=0
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+
+/*******DISPLAY THE FIRST RESULTS *******/
+
+di
+di in green "{hline 32}"
+di in green "TOTAL VARIANCE: " in ye %16.5f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %9.0f `nbind'
+di in green "METHOD:" in ye _col(`=33-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 32}"
+di
+
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+
+/******** CLASSIFICATION PROCEDURE*******/
+
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',12,0)
+ matrix `indexes'=J(`nbitems',8,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',10]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',10]=1
+ }
+ matrix `vp'[`i',1]=`i'
+ matrix `vp'[`i',2]=`nbitems'
+ matrix `vp'[`i',8]=`totvar'
+ matrix `vp'[`i',9]=100
+ }
+ matrix `vp'[`nbitems',5]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 101}"
+ di in green _col(93) "2nd order"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative" _col(94) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation" _col(93) "Variation"
+ di in green "{hline 101}"
+ }
+ else {
+ local crit T
+ di in green "{hline 111}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal" _col(103) "2nd order"
+ }
+ else {
+ di in green _col(84) "Current" _col(103) "2nd order"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative" _col(104) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation" _col(103) "Variation"
+ di in green "{hline 111}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local ev2=max(`vp'[`j',11],`vp'[`k',11],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ matrix `vp'[`clus',1]=`nbitems'+`i' /*PARENT*/
+ matrix `vp'[`clus',2]=`=`nbitems'-`i'' /*NUMBER OF CLUSTERS*/
+ matrix `vp'[`clus',3]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',4]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',6]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `vp'[`clus',5]=`vp'[`=`clus'-1',5]-`vp'[`clus',6] /*T or G CRITERION*/
+ matrix `vp'[`clus',7]=(`vp'[`clus',6]-`vp'[`=`clus'-1',6])/`vp'[`=`clus'-1',6] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `vp'[`clus',8]=`vp'[`=`clus'-1',8]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',9]=`vp'[`clus',8]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',10]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',11]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ }
+ if `vp'[`=`clus'-1',7]!=0 {
+ matrix `vp'[`clus',12]=(`vp'[`clus',7]-`vp'[`=`clus'-1',7])/abs(`vp'[`=`clus'-1',7]) /*2ND ORDER RELATIVE VARIATION OF THE T or G CRITERION*/
+ }
+ matrix `indexes'[`i',1]=`i' /*PARENT*/
+ matrix `indexes'[`i',2]=`nbitems'-`i' /*NUMBER OF CLUSTERS*/
+ matrix `indexes'[`i',3]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `indexes'[`i',4]=`vp'[`clus',7] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`i',5]=max(`eigen2',`indexes'[`=`i'-1',5]) /*MAXIMUM SECOND EIGENVALUE*/
+ matrix `indexes'[`i',7]=`vp'[`clus',12] /*2nd order RELATIVE VARIATION OF THE T OR G CRITERION*/
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ local varlistgen
+ local nbvarlistgen
+ forvalues j=1/`=`nbitems'+`i'' {
+ local varlist`j'
+ forvalues k=1/`nbitems' {
+ if `matclus'[`k',`=`i'+1']==`j' {
+ local varlist`j' `varlist`j'' ``k''
+ }
+ }
+ local nbvarlist`j': word count `varlist`j''
+ local varlistgen `varlistgen' `varlist`j''
+ local nbvarlistgen `nbvarlistgen' `nbvarlist`j''
+ }
+ local newlist
+ foreach m in `nbvarlistgen' {
+ if `m'!=0 {
+ local newlist `newlist' `m'
+ }
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',8]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ local relv2
+ }
+ else {
+ local relv=`indexes'[`i',4]*100
+ local percent %
+ if `indexes'[`i',7]!=. {
+ local relv2=`indexes'[`i',7]*100
+ }
+ else {
+ local relv2=0
+ }
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv2'
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) _col(84) %5.2f `relv' "`percent'" _col(93) %8.2f `relv2' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) %8.4f `vp'[`clus',11] _col(94) %6.2f `relv' "`percent'" _col(103) %8.2f `relv2' "`percent'"
+ }
+ }
+ }
+ matrix `indexes'[`nbitems',3]=`vp'[`=2*`nbitems'-1',5] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`nbitems',7]=`indexes'[`nbitems',3]/`indexes'[`=`nbitems'-1',3] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ local i=2*`nbitems'-1
+ matrix `threshold'[1,1]=`vp'[`i',5]/`vp'[`i',6]*100-100
+ matrix `threshold'[1,2]=(`threshold'[1,1]-`threshold'[2,1])/abs(`threshold'[2,1])*100
+ matrix `threshold'[1,3]=`vp'[`i',5]
+ if "`method'"=="centroid" {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(83) %6.2f `threshold'[1,1] "`percent'" _col(93) %8.2f `threshold'[1,2] "`percent'"
+ }
+ else {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(94) %6.2f `threshold'[1,1] "`percent'" _col(103) %8.2f `threshold'[1,2] "`percent'"
+ }
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ local demipart=int(`nbitems'/2)+1
+ forvalues i=1/`demipart' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 111}"
+ di
+ di in green "{hline 60}"
+ di in green "PROPOSED BEST PARTITIONS (AMONG THE `demipart' SMALLER PARTITIONS)"
+ di in green "{hline 60}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion: " _col(60) in gr "Partitions in " in ye `best' " or " `best2' in gr " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',1]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',1]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',1]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',1]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold: " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',6]=`totvar'-`T'
+ matrix `vp'[`i',8]=`T'
+ matrix `vp'[`i',9]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold (second order): " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ return local bestthresold2 `bestt' `bestt2'
+}
+/******BAR CHART *******/
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `indexes' ,names(v)
+ qui gen id=`nbitems'-_n
+ qui replace v7=. in 1
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v3 "T variation"
+ qui su v3 if id!=0
+ local maxv3=ceil(r(max)*5)/5
+ local minv3=floor(r(min)*5)/5
+ label variable v4 "Relative T variation"
+ label variable v7 "Relative T variation order 2"
+ graph twoway (bar v3 id, name(bar,replace) vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+/****** DENDROGRAM********/
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `matclus' ,names(v)
+ local listorder
+ forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+ }
+ qui gen id=_n
+ qui sort `listorder'
+
+ capture cluster delete clv,zap
+ qui cluster complete v* ,name(clv)
+
+ qui replace clv_id=_n
+ qui replace clv_ord=id
+ qui replace clv_hgt=.
+
+ qui gen fait=0
+ qui gen clus=0
+ forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',3]<=`nbitems') {
+ local first=`vp'[`ligne',3]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',4]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',6] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',9] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',1] in 1
+ }
+if "`dendro'"=="" {
+ qui gen label=""
+ forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+ }
+ sort clv_id
+ if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+ }
+ else {
+ local var "Variables"
+ local cut label(label)
+ }
+ qui su clv_hgt
+ local tmp=r(max)
+ local max=floor(`tmp')+.5
+ if `tmp'>`max' {
+ local max=`max'+.5
+ }
+ local maxvar=`max'+5
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`textsize'"=="" {
+ local textsize: word `=min(int(`nbitems'/15)+1,5)' of medium medsmall small vsmall tiny
+ }
+ if "`horizontal'"!="" {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut'
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut'
+ }
+ if "`savedendro'"!="" {
+ graph save dendrogram `savedendro'
+ }
+}
+
+/***** END DENDROGRAM*****/
+
+/**** TEST ********/
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+
+/***** CONSOLIDATION PROCEDURE ********/
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=13
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "CLUSTER " %2.0f `g' _c
+ local col=`col'+12
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ local trace=e(trace)
+ local explained`g'=`tmp`g''*`var'/`trace'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ local trace=e(trace)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ local trace=0
+ forvalues m=1/`tmp`g''{
+ local trace =`trace'+`r(lambda`m')'
+ }
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local explained`g'=`lambda1'/`trace'
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ local explained`g'=1
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ di _col(1) in green "ITEMS :" _c
+ forvalues i=1/`max' {
+ local col=15
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+12
+ }
+ di
+ }
+ local col=16
+ di _col(1) in green "Expl. Var:" _c
+ forvalues g=1/`cons' {
+ di _col(`col') in ye %6.2f `=`explained`g''*100' in green "%" _c
+ local col= `col'+12
+ }
+ di
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ if "`replace'"!=""{
+ capture drop `genlv'`g'
+ }
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ qui set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ if "`dim'"=="" {
+ local dim 1 2
+ }
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1) `std' dim(`dim')
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+/***** END OF THE CONSOLIDATION PROCEDURE********/
+
+qui set matsize `matsize'
+if "`genlv'"!="" {
+ qui keep `id' `genlv'1-`genlv'`cons'
+ tempfile lvfile
+ qui sort `id'
+ qui save `lvfile',replace
+}
+use `clvfile',replace
+if "`genlv'"!="" {
+ qui sort `id'
+ qui merge `id' using `lvfile'
+}
+qui drop `id'
+capture drop _merge
+capture cluster delete clv,zap
+matrix colnames `vp'="Parent" "Number of clusters" "Child 1" "Child 2" "T" "DeltaT" "deltaT" "Explained Variance" "Explained Variance (%)" "First eigenvalue" "Second Eigenvalue" "2nd order deltaT"
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+restore,not
+end
diff --git a/Modules/ado/personal/c/clv215.ado b/Modules/ado/personal/c/clv215.ado
new file mode 100644
index 0000000..8839023
--- /dev/null
+++ b/Modules/ado/personal/c/clv215.ado
@@ -0,0 +1,946 @@
+*! Version 2.15 14April2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.14 : May 20th, 2010 /*dim and std options for biplots*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+* Version 2.9 (2006-01-26): Jean-Benoit Hardouin /*save the latent variables*/
+* Version 2.10 (2006-07-10): Jean-Benoit Hardouin /*2nd order relative variation of the T criterion*/
+* Version 2.11 (2006-10-09): Jean-Benoit Hardouin /*Size of the text in the dendrogram*/
+* Version 2.12 (2006-12-01): Jean-Benoit Hardouin /*savedendro option*/
+* Version 2.13 (2010-05-12): Jean-Benoit Hardouin /*corrections of bugs in KERNEL option and with METHOD(centroid)*/
+* Version 2.14 (2010-05-20): Jean-Benoit Hardouin /*DIM and STD options for biplots*/
+* Version 2.15 (2014-04-14): Jean-Benoit Hardouin /*save and use options*/
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.sphere-nantes.fr
+*
+* Copyright 2005-2006, 2010, 2014 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 clv215,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 40) bar CONSolidation(int 0) noDENdro SAVEDendro(string) noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string) replace TEXTSize(string) std dim(string) save(string) use(string)]
+preserve
+tempfile clvfile
+tempvar id
+gen `id'=_n
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"==""&"`use'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+tempname matclus vp indexes
+
+/*********TESTS**********/
+
+if "`use'"!="" {
+ local error=0
+ capture matrix `vp'=`use'_vp
+ if _rc!=0 {
+ local error=_rc
+ }
+ capture matrix `matclus'=`use'_matclus
+ if _rc!=0 {
+ local error=_rc
+ }
+ local varlist $`use'_varlist
+ local method $`use'_method
+ local kernel $`use'_kernel
+ if "`varlist'"==""|"`method'"=="" {
+ local error=1
+ }
+ if `error'!=0 {
+ di in red "You cannot use the {hi:use} option without a preliminary use of the {hi:save} option"
+ error 198
+ exit
+ }
+}
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+
+
+/*******DEFINES THE LABELS AND STANDARDIZED THE VARIABLES (IF NECESSARY)*******/
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+/*COMPUTES THE TOTAL VARIANCE*/
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+/***** DEFINES THE KERNEL IF NECESSARY ********/
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ local eigen2=0
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+
+/*******DISPLAY THE FIRST RESULTS *******/
+
+di
+di in green "{hline 32}"
+di in green "TOTAL VARIANCE: " in ye %16.5f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %9.0f `nbind'
+di in green "METHOD:" in ye _col(`=33-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 32}"
+di
+
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+
+/******** CLASSIFICATION PROCEDURE*******/
+
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',12,0)
+ matrix `indexes'=J(`nbitems',8,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',10]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',10]=1
+ }
+ matrix `vp'[`i',1]=`i'
+ matrix `vp'[`i',2]=`nbitems'
+ matrix `vp'[`i',8]=`totvar'
+ matrix `vp'[`i',9]=100
+ }
+ matrix `vp'[`nbitems',5]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 101}"
+ di in green _col(93) "2nd order"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative" _col(94) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation" _col(93) "Variation"
+ di in green "{hline 101}"
+ }
+ else {
+ local crit T
+ di in green "{hline 111}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal" _col(103) "2nd order"
+ }
+ else {
+ di in green _col(84) "Current" _col(103) "2nd order"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative" _col(104) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation" _col(103) "Variation"
+ di in green "{hline 111}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local ev2=max(`vp'[`j',11],`vp'[`k',11],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ matrix `vp'[`clus',1]=`nbitems'+`i' /*PARENT*/
+ matrix `vp'[`clus',2]=`=`nbitems'-`i'' /*NUMBER OF CLUSTERS*/
+ matrix `vp'[`clus',3]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',4]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',6]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `vp'[`clus',5]=`vp'[`=`clus'-1',5]-`vp'[`clus',6] /*T or G CRITERION*/
+ matrix `vp'[`clus',7]=(`vp'[`clus',6]-`vp'[`=`clus'-1',6])/`vp'[`=`clus'-1',6] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `vp'[`clus',8]=`vp'[`=`clus'-1',8]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',9]=`vp'[`clus',8]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',10]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',11]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ }
+ if `vp'[`=`clus'-1',7]!=0 {
+ matrix `vp'[`clus',12]=(`vp'[`clus',7]-`vp'[`=`clus'-1',7])/abs(`vp'[`=`clus'-1',7]) /*2ND ORDER RELATIVE VARIATION OF THE T or G CRITERION*/
+ }
+ matrix `indexes'[`i',1]=`i' /*PARENT*/
+ matrix `indexes'[`i',2]=`nbitems'-`i' /*NUMBER OF CLUSTERS*/
+ matrix `indexes'[`i',3]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `indexes'[`i',4]=`vp'[`clus',7] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`i',5]=max(`eigen2',`indexes'[`=`i'-1',5]) /*MAXIMUM SECOND EIGENVALUE*/
+ matrix `indexes'[`i',7]=`vp'[`clus',12] /*2nd order RELATIVE VARIATION OF THE T OR G CRITERION*/
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ local varlistgen
+ local nbvarlistgen
+ forvalues j=1/`=`nbitems'+`i'' {
+ local varlist`j'
+ forvalues k=1/`nbitems' {
+ if `matclus'[`k',`=`i'+1']==`j' {
+ local varlist`j' `varlist`j'' ``k''
+ }
+ }
+ local nbvarlist`j': word count `varlist`j''
+ local varlistgen `varlistgen' `varlist`j''
+ local nbvarlistgen `nbvarlistgen' `nbvarlist`j''
+ }
+ local newlist
+ foreach m in `nbvarlistgen' {
+ if `m'!=0 {
+ local newlist `newlist' `m'
+ }
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',8]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ local relv2
+ }
+ else {
+ local relv=`indexes'[`i',4]*100
+ local percent %
+ if `indexes'[`i',7]!=. {
+ local relv2=`indexes'[`i',7]*100
+ }
+ else {
+ local relv2=0
+ }
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv2'
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) _col(84) %5.2f `relv' "`percent'" _col(93) %8.2f `relv2' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) %8.4f `vp'[`clus',11] _col(94) %6.2f `relv' "`percent'" _col(103) %8.2f `relv2' "`percent'"
+ }
+ }
+ }
+ matrix `indexes'[`nbitems',3]=`vp'[`=2*`nbitems'-1',5] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`nbitems',7]=`indexes'[`nbitems',3]/`indexes'[`=`nbitems'-1',3] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ local i=2*`nbitems'-1
+ matrix `threshold'[1,1]=`vp'[`i',5]/`vp'[`i',6]*100-100
+ matrix `threshold'[1,2]=(`threshold'[1,1]-`threshold'[2,1])/abs(`threshold'[2,1])*100
+ matrix `threshold'[1,3]=`vp'[`i',5]
+ if "`method'"=="centroid" {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(83) %6.2f `threshold'[1,1] "`percent'" _col(93) %8.2f `threshold'[1,2] "`percent'"
+ }
+ else {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(94) %6.2f `threshold'[1,1] "`percent'" _col(103) %8.2f `threshold'[1,2] "`percent'"
+ }
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ local demipart=int(`nbitems'/2)+1
+ forvalues i=1/`demipart' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 111}"
+ di
+ di in green "{hline 60}"
+ di in green "PROPOSED BEST PARTITIONS (AMONG THE `demipart' SMALLER PARTITIONS)"
+ di in green "{hline 60}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion: " _col(60) in gr "Partitions in " in ye `best' " or " `best2' in gr " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',1]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',1]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',1]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',1]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold: " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',6]=`totvar'-`T'
+ matrix `vp'[`i',8]=`T'
+ matrix `vp'[`i',9]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold (second order): " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ return local bestthresold2 `bestt' `bestt2'
+}
+/******BAR CHART *******/
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `indexes' ,names(v)
+ qui gen id=`nbitems'-_n
+ qui replace v7=. in 1
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v3 "T variation"
+ qui su v3 if id!=0
+ local maxv3=ceil(r(max)*5)/5
+ local minv3=floor(r(min)*5)/5
+ label variable v4 "Relative T variation"
+ label variable v7 "Relative T variation order 2"
+ graph twoway (bar v3 id, name(bar,replace) vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+/****** DENDROGRAM********/
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `matclus' ,names(v)
+ local listorder
+ forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+ }
+ qui gen id=_n
+ qui sort `listorder'
+
+ capture cluster delete clv,zap
+ qui cluster complete v* ,name(clv)
+
+ qui replace clv_id=_n
+ qui replace clv_ord=id
+ qui replace clv_hgt=.
+
+ qui gen fait=0
+ qui gen clus=0
+ forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',3]<=`nbitems') {
+ local first=`vp'[`ligne',3]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',4]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',6] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',9] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',1] in 1
+ }
+if "`dendro'"=="" {
+ qui gen label=""
+ forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+ }
+ sort clv_id
+ if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+ }
+ else {
+ local var "Variables"
+ local cut label(label)
+ }
+ qui su clv_hgt
+ local tmp=r(max)
+ local max=floor(`tmp')+.5
+ if `tmp'>`max' {
+ local max=`max'+.5
+ }
+ local maxvar=`max'+5
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`textsize'"=="" {
+ local textsize: word `=min(int(`nbitems'/15)+1,5)' of medium medsmall small vsmall tiny
+ }
+ if "`horizontal'"!="" {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut'
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut'
+ }
+ if "`savedendro'"!="" {
+ graph save dendrogram `savedendro'
+ }
+}
+
+/***** END DENDROGRAM*****/
+
+/**** TEST ********/
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+
+/***** CONSOLIDATION PROCEDURE ********/
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=13
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "CLUSTER " %2.0f `g' _c
+ local col=`col'+12
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ local trace=e(trace)
+ local explained`g'=`tmp`g''*`var'/`trace'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ local trace=e(trace)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ local trace=0
+ forvalues m=1/`tmp`g''{
+ local trace =`trace'+`r(lambda`m')'
+ }
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local explained`g'=`lambda1'/`trace'
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ local explained`g'=1
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ di _col(1) in green "ITEMS :" _c
+ forvalues i=1/`max' {
+ local col=15
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+12
+ }
+ di
+ }
+ local col=16
+ di _col(1) in green "Expl. Var:" _c
+ forvalues g=1/`cons' {
+ di _col(`col') in ye %6.2f `=`explained`g''*100' in green "%" _c
+ local col= `col'+12
+ }
+ di
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ if "`replace'"!=""{
+ capture drop `genlv'`g'
+ }
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ qui set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ if "`dim'"=="" {
+ local dim 1 2
+ }
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1) `std' dim(`dim')
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+/***** END OF THE CONSOLIDATION PROCEDURE********/
+
+qui set matsize `matsize'
+if "`genlv'"!="" {
+ qui keep `id' `genlv'1-`genlv'`cons'
+ tempfile lvfile
+ qui sort `id'
+ qui save `lvfile',replace
+}
+use `clvfile',replace
+if "`genlv'"!="" {
+ qui sort `id'
+ qui merge `id' using `lvfile'
+}
+qui drop `id'
+capture drop _merge
+capture cluster delete clv,zap
+matrix colnames `vp'="Parent" "Number of clusters" "Child 1" "Child 2" "T" "DeltaT" "deltaT" "Explained Variance" "Explained Variance (%)" "First eigenvalue" "Second Eigenvalue" "2nd order deltaT"
+if "`save'"!="" {
+ qui matrix `save'_vp=`vp'
+ qui matrix `save'_matclus=`matclus'
+ qui global `save'_varlist `varlist'
+ qui global `save'_method `method'
+ qui global `save'_kernel `kernel'
+}
+
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+restore,not
+end
diff --git a/Modules/ado/personal/c/clv216.ado b/Modules/ado/personal/c/clv216.ado
new file mode 100644
index 0000000..d4fb838
--- /dev/null
+++ b/Modules/ado/personal/c/clv216.ado
@@ -0,0 +1,1005 @@
+*! Version 2.16 30April2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.14 : May 20th, 2010 /*dim and std options for biplots*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+* Version 2.9 (2006-01-26): Jean-Benoit Hardouin /*save the latent variables*/
+* Version 2.10 (2006-07-10): Jean-Benoit Hardouin /*2nd order relative variation of the T criterion*/
+* Version 2.11 (2006-10-09): Jean-Benoit Hardouin /*Size of the text in the dendrogram*/
+* Version 2.12 (2006-12-01): Jean-Benoit Hardouin /*savedendro option*/
+* Version 2.13 (2010-05-12): Jean-Benoit Hardouin /*corrections of bugs in KERNEL option and with METHOD(centroid)*/
+* Version 2.14 (2010-05-20): Jean-Benoit Hardouin /*DIM and STD options for biplots*/
+* Version 2.15 (2014-04-14): Jean-Benoit Hardouin /*save and use options*/
+* Version 2.16 (2014-04-30): Jean-Benoit Hardouin, Bastien Perrot /*HTML option*/
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.sphere-nantes.fr
+*
+* Copyright 2005-2006, 2010, 2014 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 clv216,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 40) bar CONSolidation(int 0) noDENdro SAVEDendro(string) noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string) replace TEXTSize(string) std dim(string) save(string) use(string) HTML(string)]
+preserve
+tempfile clvfile
+tempvar id
+gen `id'=_n
+qui save `clvfile',replace
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+local matsize=c(matsize)
+local none=0
+if "`varlist'"==""&"`use'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+if "`html'"!="" {
+ //set scheme sj
+ //local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di "
"
+}
+
+
+tempname matclus vp indexes
+
+/*********TESTS**********/
+
+if "`use'"!="" {
+ local error=0
+ capture matrix `vp'=`use'_vp
+ if _rc!=0 {
+ local error=_rc
+ }
+ capture matrix `matclus'=`use'_matclus
+ if _rc!=0 {
+ local error=_rc
+ }
+ local varlist $`use'_varlist
+ local method $`use'_method
+ local kernel $`use'_kernel
+ if "`varlist'"==""|"`method'"=="" {
+ local error=1
+ }
+ if `error'!=0 {
+ di in red "You cannot use the {hi:use} option without a preliminary use of the {hi:save} option"
+ error 198
+ exit
+ }
+}
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+
+
+/*******DEFINES THE LABELS AND STANDARDIZED THE VARIABLES (IF NECESSARY)*******/
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+/*COMPUTES THE TOTAL VARIANCE*/
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+/***** DEFINES THE KERNEL IF NECESSARY ********/
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ local eigen2=0
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+
+/*******DISPLAY THE FIRST RESULTS *******/
+
+di
+di in green "{hline 32}"
+di in green "TOTAL VARIANCE: " in ye %16.5f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %9.0f `nbind'
+di in green "METHOD:" in ye _col(`=33-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 32}"
+di
+
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+
+/******** CLASSIFICATION PROCEDURE*******/
+
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',12,0)
+ matrix `indexes'=J(`nbitems',8,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',10]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',10]=1
+ }
+ matrix `vp'[`i',1]=`i'
+ matrix `vp'[`i',2]=`nbitems'
+ matrix `vp'[`i',8]=`totvar'
+ matrix `vp'[`i',9]=100
+ }
+ matrix `vp'[`nbitems',5]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 101}"
+ di in green _col(93) "2nd order"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative" _col(94) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation" _col(93) "Variation"
+ di in green "{hline 101}"
+ }
+ else {
+ local crit T
+ di in green "{hline 111}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal" _col(103) "2nd order"
+ }
+ else {
+ di in green _col(84) "Current" _col(103) "2nd order"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative" _col(104) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation" _col(103) "Variation"
+ di in green "{hline 111}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local ev2=max(`vp'[`j',11],`vp'[`k',11],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',10]+`vp'[`k',10]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ matrix `vp'[`clus',1]=`nbitems'+`i' /*PARENT*/
+ matrix `vp'[`clus',2]=`=`nbitems'-`i'' /*NUMBER OF CLUSTERS*/
+ matrix `vp'[`clus',3]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',4]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',6]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `vp'[`clus',5]=`vp'[`=`clus'-1',5]-`vp'[`clus',6] /*T or G CRITERION*/
+ matrix `vp'[`clus',7]=(`vp'[`clus',6]-`vp'[`=`clus'-1',6])/`vp'[`=`clus'-1',6] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `vp'[`clus',8]=`vp'[`=`clus'-1',8]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',9]=`vp'[`clus',8]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',10]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',11]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ }
+ if `vp'[`=`clus'-1',7]!=0 {
+ matrix `vp'[`clus',12]=(`vp'[`clus',7]-`vp'[`=`clus'-1',7])/abs(`vp'[`=`clus'-1',7]) /*2ND ORDER RELATIVE VARIATION OF THE T or G CRITERION*/
+ }
+ matrix `indexes'[`i',1]=`i' /*PARENT*/
+ matrix `indexes'[`i',2]=`nbitems'-`i' /*NUMBER OF CLUSTERS*/
+ matrix `indexes'[`i',3]=`minegenval' /*VARIATION OF THE T or G CRITERION*/
+ matrix `indexes'[`i',4]=`vp'[`clus',7] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`i',5]=max(`eigen2',`indexes'[`=`i'-1',5]) /*MAXIMUM SECOND EIGENVALUE*/
+ matrix `indexes'[`i',7]=`vp'[`clus',12] /*2nd order RELATIVE VARIATION OF THE T OR G CRITERION*/
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ local varlistgen
+ local nbvarlistgen
+ forvalues j=1/`=`nbitems'+`i'' {
+ local varlist`j'
+ forvalues k=1/`nbitems' {
+ if `matclus'[`k',`=`i'+1']==`j' {
+ local varlist`j' `varlist`j'' ``k''
+ }
+ }
+ local nbvarlist`j': word count `varlist`j''
+ local varlistgen `varlistgen' `varlist`j''
+ local nbvarlistgen `nbvarlistgen' `nbvarlist`j''
+ }
+ local newlist
+ foreach m in `nbvarlistgen' {
+ if `m'!=0 {
+ local newlist `newlist' `m'
+ }
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',8]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ local relv2
+ }
+ else {
+ local relv=`indexes'[`i',4]*100
+ local percent %
+ if `indexes'[`i',7]!=. {
+ local relv2=`indexes'[`i',7]*100
+ }
+ else {
+ local relv2=0
+ }
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv2'
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) _col(84) %5.2f `relv' "`percent'" _col(93) %8.2f `relv2' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',8] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',9] "%" _col(83) %8.4f `vp'[`clus',11] _col(94) %6.2f `relv' "`percent'" _col(103) %8.2f `relv2' "`percent'"
+ }
+ }
+ }
+ matrix `indexes'[`nbitems',3]=`vp'[`=2*`nbitems'-1',5] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ matrix `indexes'[`nbitems',7]=`indexes'[`nbitems',3]/`indexes'[`=`nbitems'-1',3] /*RELATIVE VARIATION OF THE T OR G CRITERION*/
+ local i=2*`nbitems'-1
+ matrix `threshold'[1,1]=`vp'[`i',5]/`vp'[`i',6]*100-100
+ matrix `threshold'[1,2]=(`threshold'[1,1]-`threshold'[2,1])/abs(`threshold'[2,1])*100
+ matrix `threshold'[1,3]=`vp'[`i',5]
+ if "`method'"=="centroid" {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(83) %6.2f `threshold'[1,1] "`percent'" _col(93) %8.2f `threshold'[1,2] "`percent'"
+ }
+ else {
+ di in ye _col(62) %8.4f `threshold'[1,3] _col(94) %6.2f `threshold'[1,1] "`percent'" _col(103) %8.2f `threshold'[1,2] "`percent'"
+ }
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ local demipart=int(`nbitems'/2)+1
+ forvalues i=1/`demipart' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 111}"
+ di
+ di in green "{hline 60}"
+ di in green "PROPOSED BEST PARTITIONS (AMONG THE `demipart' SMALLER PARTITIONS)"
+ di in green "{hline 60}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion: " _col(60) in gr "Partitions in " in ye `best' " or " `best2' in gr " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',1]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',1]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',1]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',1]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold: " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',6]=`totvar'-`T'
+ matrix `vp'[`i',8]=`T'
+ matrix `vp'[`i',9]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`demipart' {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold (second order): " _col(60) in gr "Partitions in " in ye `bestt' " or " `bestt2' in gr " clusters"
+ return local bestthresold2 `bestt' `bestt2'
+}
+/******BAR CHART *******/
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `indexes' ,names(v)
+ qui gen id=`nbitems'-_n
+ qui replace v7=. in 1
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v3 "T variation"
+ qui su v3 if id!=0
+ local maxv3=ceil(r(max)*5)/5
+ local minv3=floor(r(min)*5)/5
+ label variable v4 "Relative T variation"
+ label variable v7 "Relative T variation order 2"
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_bar,replace) nodraw"
+ qui graph twoway (bar v3 id, name(bar,replace) vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1') `saving'
+ qui graph use `c(tmpdir)'/`html'_bar.gph
+ qui graph export `c(tmpdir)'/`html'_bar.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ graph twoway (bar v3 id, name(bar,replace) vert yaxis(1))(line v4 id,yaxis(2))/*(line v6 id,yaxis(3))(line v5 id,yaxis(4))*/(line v7 id,yaxis(5)) if id!=0,ylabel(`minv3'(0.2)`maxv3') xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+ }
+ }
+/****** DENDROGRAM********/
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `matclus' ,names(v)
+ local listorder
+ forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+ }
+ qui gen id=_n
+ qui sort `listorder'
+
+ capture cluster delete clv,zap
+ qui cluster complete v* ,name(clv)
+
+ qui replace clv_id=_n
+ qui replace clv_ord=id
+ qui replace clv_hgt=.
+
+ qui gen fait=0
+ qui gen clus=0
+ forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',3]<=`nbitems') {
+ local first=`vp'[`ligne',3]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',4]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',6] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',9] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',1] in 1
+ }
+if "`dendro'"=="" {
+ qui gen label=""
+ forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+ }
+ sort clv_id
+ if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+ }
+ else {
+ local var "Variables"
+ local cut label(label)
+ }
+ qui su clv_hgt
+ local tmp=r(max)
+ local max=floor(`tmp')+.5
+ if `tmp'>`max' {
+ local max=`max'+.5
+ }
+ local maxvar=`max'+5
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`textsize'"=="" {
+ local textsize: word `=min(int(`nbitems'/15)+1,5)' of medium medsmall small vsmall tiny
+ }
+ if "`horizontal'"!="" {
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_dendrogram,replace) nodraw"
+ qui cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut' `saving'
+ qui graph use `c(tmpdir)'/`html'_dendrogram.gph
+ qui graph export `c(tmpdir)'/`html'_dendrogram.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0) labsize(`textsize')) `cut'
+ }
+ }
+ else {
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_dendrogram,replace) nodraw"
+ qui cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut' `saving'
+ qui graph use `c(tmpdir)'/`html'_dendrogram.gph
+ qui graph export `c(tmpdir)'/`html'_dendrogram.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') xlabel(,labsize(`textsize')) `cut'
+ }
+ }
+ if "`savedendro'"!="" {
+ graph save dendrogram `savedendro'
+ }
+}
+
+/***** END DENDROGRAM*****/
+
+/**** TEST ********/
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+
+/***** CONSOLIDATION PROCEDURE ********/
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=13
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "CLUSTER " %2.0f `g' _c
+ local col=`col'+12
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ local trace=e(trace)
+ local explained`g'=`tmp`g''*`var'/`trace'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ local trace=e(trace)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ local trace=0
+ forvalues m=1/`tmp`g''{
+ local trace =`trace'+`r(lambda`m')'
+ }
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local explained`g'=`lambda1'/`trace'
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ local explained`g'=1
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ di _col(1) in green "ITEMS :" _c
+ forvalues i=1/`max' {
+ local col=15
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+12
+ }
+ di
+ }
+ local col=16
+ di _col(1) in green "Expl. Var:" _c
+ forvalues g=1/`cons' {
+ di _col(`col') in ye %6.2f `=`explained`g''*100' in green "%" _c
+ local col= `col'+12
+ }
+ di
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ if "`replace'"!=""{
+ capture drop `genlv'`g'
+ }
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ qui set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ if "`dim'"=="" {
+ local dim 1 2
+ }
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_biplot,replace) nodraw"
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1) `std' dim(`dim') `saving'
+ qui graph use `c(tmpdir)'/`html'_biplot.gph
+ qui graph export `c(tmpdir)'/`html'_biplot.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1) `std' dim(`dim')
+ }
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+/***** END OF THE CONSOLIDATION PROCEDURE********/
+
+qui set matsize `matsize'
+if "`genlv'"!="" {
+ qui keep `id' `genlv'1-`genlv'`cons'
+ tempfile lvfile
+ qui sort `id'
+ qui save `lvfile',replace
+}
+use `clvfile',replace
+if "`genlv'"!="" {
+ qui sort `id'
+ qui merge `id' using `lvfile'
+}
+qui drop `id'
+capture drop _merge
+capture cluster delete clv,zap
+matrix colnames `vp'="Parent" "Number of clusters" "Child 1" "Child 2" "T" "DeltaT" "deltaT" "Explained Variance" "Explained Variance (%)" "First eigenvalue" "Second Eigenvalue" "2nd order deltaT"
+if "`save'"!="" {
+ qui matrix `save'_vp=`vp'
+ qui matrix `save'_matclus=`matclus'
+ qui global `save'_varlist `varlist'
+ qui global `save'_method `method'
+ qui global `save'_kernel `kernel'
+}
+
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+restore,not
+end
diff --git a/Modules/ado/personal/c/clv27.ado b/Modules/ado/personal/c/clv27.ado
new file mode 100644
index 0000000..2b29ea0
--- /dev/null
+++ b/Modules/ado/personal/c/clv27.ado
@@ -0,0 +1,806 @@
+*! Version 2.7 6October2005
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.7 : October 6, 2005 /*return, multiple graphs, polychoric+consolidation*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005 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 clv,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [, CUTnumber(int 30) bar CONSolidation(int 0) noDENdro noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar]
+preserve
+tempfile clvfile
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"=="" {
+*set trace on
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+tempname matclus vp
+
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+/*
+ if "`method'"=="polychoric" {
+ di in red "The {hi:consolidation} is not possible with the {hi:polychoric} option"
+ error 198
+ exit
+ }
+*/
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i''
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui count
+local nbind=r(N)
+
+local cons=`consolidation'
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i''
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+di
+di in green "{hline 30}"
+di in green "TOTAL VARIANCE: " in ye %14.3f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %7.0f `nbind'
+di in green "METHOD:" in ye _col(`=31-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 30}"
+di
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',10,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i''
+ matrix `vp'[`i',1]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',1]=1
+ }
+ matrix `vp'[`i',8]=`i'
+ matrix `vp'[`i',9]=`totvar'
+ matrix `vp'[`i',10]=100
+ }
+ matrix `vp'[`nbitems',3]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 89}"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation"
+ di in green "{hline 89}"
+ }
+ else {
+ local crit T
+ di in green "{hline 100}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal"
+ }
+ else {
+ di in green _col(84) "Current"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation"
+ di in green "{hline 100}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj'
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk'
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk'
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'',cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k''
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',1]+`vp'[`k',1]-`lambda1'
+/*
+ local t1=`vp'[`j',1]
+ local t2=`vp'[`k',1]
+ di "`ev'=`t1'+`t2'-`lambda1'"
+*/
+ local ev2=max(`vp'[`j',5],`vp'[`k',5],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval=`ev'
+ local minegenval2=`ev2'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`ev2'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'',cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k''
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',1]+`vp'[`k',1]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12'
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ *set trace off
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',1]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',2]=`minegenval' /*VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',3]=`vp'[`=`clus'-1',3]-`vp'[`clus',2] /*T CRITERION*/
+ matrix `vp'[`clus',4]=`vp'[`clus',2]/`vp'[`=`clus'-1',3] /*RELATIVE VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',5]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',6]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',7]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',8]=`nbitems'+`i' /*NUMBER OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',9]=`vp'[`=`clus'-1',9]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',10]=`vp'[`clus',9]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ }
+ else {
+ matrix `vp'[`clus',1]=0 /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',2]=`minegenval' /*VARIATION OF THE G CRITERION*/
+ matrix `vp'[`clus',3]=`vp'[`=`clus'-1',3]-`vp'[`clus',2] /*G CRITERION*/
+ matrix `vp'[`clus',4]=`vp'[`clus',2]/`vp'[`=`clus'-1',3] /*RELATIVE VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',5]=0 /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',6]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',7]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',8]=`nbitems'+`i' /*NUMBER OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',9]=`vp'[`=`clus'-1',9]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',10]=`vp'[`clus',9]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ }
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',9]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ }
+ else {
+ local relv=(`minegenval'-`vp'[`=`clus'-1',2])/`vp'[`=`clus'-1',3]*100
+ local percent %
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `i'>1 {
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv'-`threshold'[`=`nbitems'-`i'+2',1]
+ }
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',9] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',10] "%" _col(83) _col(84) %5.2f `relv' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',9] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',10] "%" _col(83) %8.4f `vp'[`clus',5] _col(95) %5.2f `relv' "`percent'"
+ }
+ }
+ }
+ local i=2*`nbitems'-1
+ local relv=(`vp'[`i',3]-`vp'[`i',2])/`vp'[`i',3]*100
+ if "`method'"=="centroid" {
+ di in ye _col(84) %5.2f `relv' "`percent'"
+ }
+ else {
+ di in ye _col(95) %5.2f `relv' "`percent'"
+ }
+ matrix `threshold'[1,1]=`relv'
+ matrix `threshold'[1,2]=`relv'-`threshold'[2,1]
+ matrix `threshold'[1,3]=`vp'[`i',3]
+ *matrix list `threshold'
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 100}"
+ di in green "Proposed best partitions: "
+ di in green "Based on the variation of the T criterion"
+ di in green _col(10) "1. Partitions in " in ye `best' in green " clusters"
+ di in green _col(10) "2. Partitions in " in ye `best2' in green " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`nbitems'-1 {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in green "Based on a research of a threshold"
+ di in green _col(10) "1. Partitions in " in ye `bestt' in green " clusters"
+ di in green _col(10) "2. Partitions in " in ye `bestt2' in green " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',2]=`totvar'-`T'
+ matrix `vp'[`i',9]=`T'
+ matrix `vp'[`i',10]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+}
+
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `vp' ,names(v)
+ qui drop in 1/`nbitems'
+ qui gen id=`nbitems'-_n
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v2 "T variation"
+ graph twoway bar v2 id, name(bar,replace) vert ,ylabel(0(0.5)2) xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+
+drop _all
+qui set obs `nbitems'
+qui svmat `matclus' ,names(v)
+local listorder
+forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+}
+qui gen id=_n
+qui sort `listorder'
+
+capture cluster delete clv,zap
+qui cluster complete v* ,name(clv)
+
+qui replace clv_id=_n
+qui replace clv_ord=id
+qui replace clv_hgt=.
+
+qui gen fait=0
+qui gen clus=0
+forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',6]<=`nbitems') {
+ local first=`vp'[`ligne',6]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',7]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',2] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',10] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',8] in 1
+}
+qui gen label=""
+forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+}
+sort clv_id
+if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+}
+else {
+ local var "Variables"
+ local cut label(label)
+}
+qui su clv_hgt
+local tmp=r(max)
+local max=floor(`tmp')+.5
+if `tmp'>`max' {
+ local max=`max'+.5
+}
+local maxvar=`max'+5
+if "`dendro'"=="" {
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`horizontal'"!="" {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0)) `cut'
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') `cut'
+ }
+}
+
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+/*
+if `cons'!=0&("`method'"=="polychoric"|"`method'"=="polychoricv2") {
+ di in ye "The {hi:consolidation} is not possible with the {hi:polychoric} methods"
+ local cons=0
+}
+*/
+
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ *cluster generate cut = groups(2/9) , name(clv)
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=1
+ local max=0
+ *set trace on
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "GROUP " %2.0f `g' _c
+ local col=`col'+10
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g''
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'',cov
+ matrix `Ev'=e(Ev)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'',score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ forvalues i=1/`max' {
+ local col=1
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+10
+ }
+ di
+ }
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr''
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g''
+ local tmpcorr=r(rho)
+ if ((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid") {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`cons' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h''
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"=="" {
+ local max=max(`matsize',`nbind')
+ set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1)
+ }
+ else {
+ di in green "There is more than 800 individuals, so the {hi:biplot} is disabled"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+set matsize `matsize'
+use `clvfile',replace
+capture cluster delete clv,zap
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+end
diff --git a/Modules/ado/personal/c/clv29.ado b/Modules/ado/personal/c/clv29.ado
new file mode 100644
index 0000000..4a9180b
--- /dev/null
+++ b/Modules/ado/personal/c/clv29.ado
@@ -0,0 +1,798 @@
+*! Version 2.9 9December2005
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : clv
+* Clustering of variables around latent variables
+* Version 2.9 : December 9, 2005 /*save the latent variables*/
+*
+* Historic
+* Version 1 (2005-06-11): Jean-Benoit Hardouin
+* Version 1.1 (2005-07-07): Jean-Benoit Hardouin /*small bug in the consolidation process with cluster of only one variable*/
+* Version 1.2 (2005-07-08): Jean-Benoit Hardouin /*Bug in the consolidation procedure when there is negative correlation*/
+* Version 2 (2005-09-03): Jean-Benoit Hardouin /*Horizontal dendrograms (with Stata 9)*/
+* Version 2.1 (2005-09-08): Jean-Benoit Hardouin /*More flexibility to abbreviate the names of the variables (with Stata 9)*/
+* Version 2.1.1 (2005-09-08): Jean-Benoit Hardouin /*Integration of some requests of Ronan Conroy*/
+* Version 2.1.2 (2005-09-08): Jean-Benoit Hardouin /*Possibility to give a title and an X/Y caption*/
+* Version 2.2 (2005-09-11): Jean-Benoit Hardouin /*Kernel option*/
+* Version 2.3 (2005-09-12): Jean-Benoit Hardouin /*Polychoric option*/
+* Version 2.4 (2005-09-13): Jean-Benoit Hardouin /*v2 option*/
+* Version 2.5 (2005-09-21): Jean-Benoit Hardouin /*corrections*/
+* Version 2.6 (2005-10-02): Jean-Benoit Hardouin /*centroid method, biplot*/
+* Version 2.7 (2005-10-06): Jean-Benoit Hardouin /*return, multiple graphs, polychoric+consolidation*/
+* Version 2.8 (2005-10-06): Jean-Benoit Hardouin /*fweights*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005 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 clv,rclass
+version 9.0
+syntax [varlist(default=none)] [if] [in] [fweight] [, CUTnumber(int 30) bar CONSolidation(int 0) noDENdro noSTANDardized deltaT HORizontal SHOWcount ABBrev(int 14) TITle(string) CAPtion(string) KERnel(numlist) METHod(string) noBIPlot ADDvar genlv(string)]
+preserve
+tempfile clvfile
+qui save `clvfile',replace
+local matsize=c(matsize)
+local none=0
+if "`varlist'"=="" {
+ capture confirm matrix r(vp)
+ if _rc==0 {
+ capture confirm matrix r(matclus)
+ if _rc ==0 {
+ local none=1
+ }
+ }
+ if `none'==0 {
+ di in red "You cannot use the {hi:clv} command without {hi:varlist} if you have not already run {hi:clv}"
+ error 198
+ exit
+ }
+}
+
+tempname matclus vp
+
+if `none'==1 {
+ matrix `vp'=r(vp)
+ matrix `matclus'=r(matclus)
+ local varlist `r(varlist)'
+ tokenize `varlist'
+ local nbitems=rowsof(`matclus')
+ if "`method'"!="" {
+ di in green "The {hi:method} option can not be modified without specification of the varlist. {hi:method} is omitted."
+ }
+ local method `r(method)'
+ local kernel `r(kernel)'
+}
+if "`method'"=="" {
+ local method classical
+}
+if ("`method'"=="polychoric"|"`method'"=="polychoricv2")&"`standardized'"!="" {
+ di in green "Initial variables are used with the {hi:polychoric} methods"
+ di in green "But the procedure is based on the matrix of the polychoric correlations"
+ di
+}
+if "`method'"!="classical"&"`method'"!="v2"&"`method'"!="centroid"&"`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ di in red "The {hi:method} `method' is unknown"
+ error 198
+ exit
+}
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse
+qui keep if `touse'
+
+local mat=max(`matsize',`=`nbitems'*2')
+qui set matsize `mat'
+
+if `nbitems'<3&`none'!=1 {
+ di in red "You need at least 3 variables"
+ error 198
+ exit
+}
+forvalues i=1/`nbitems'{
+ local label`i':variable label ``i''
+ if "`label`i''"=="" {
+ local label`i' ``i''
+ }
+ if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ qui su ``i'' [`weight'`exp']
+ local mean=r(mean)
+ if "`standardized'"=="" {
+ local sd=r(sd)
+ }
+ else {
+ local sd=1
+ }
+ qui replace ``i''=(``i''-`mean')/`sd'
+ }
+}
+
+tempfile clvfiletmp
+qui save `clvfiletmp',replace
+
+qui su `1' [`weight'`exp']
+local nbind=r(sum_w)
+
+
+local cons=`consolidation'
+
+if "`method'"!="polychoric"&"`method'"!="polychoricv2" {
+ local totvar=0
+ forvalues i=1/`nbitems' {
+ qui su ``i'' [`weight'`exp']
+ local totvar=`totvar'+`r(Var)'
+ }
+}
+else {
+ local totvar `nbitems'
+}
+local nbkerk=0
+local nbkerg=0
+
+if "`kernel'"!="" {
+ local nbkerg:word count `kernel'
+ local fin0=0
+ forvalues i=1/`nbkerg' {
+ local nbi`i':word `i' of `kernel'
+ local nbkerk=`nbkerk'+`nbi`i''
+ local deb`i'=`fin`=`i'-1''+1
+ local fin`i'=`deb`i''+`nbi`i''-1
+ local list`i'
+ forvalues j=`deb`i''/`fin`i'' {
+ local list`i' `list`i'' ``j''
+ }
+ }
+ tempname kerclus
+ matrix `kerclus'=J(`=`nbkerk'-`nbkerg'',3,0)
+ local ligne=1
+ forvalues g=1/`nbkerg' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''
+ matrix `kerclus'[`ligne',3]=`deb`g''+1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ if `nbi`g''>2 {
+ forvalues i=2/`=`nbi`g''-1' {
+ matrix `kerclus'[`ligne',1]=`nbitems'+`ligne'
+ matrix `kerclus'[`ligne',2]=`deb`g''+`i'
+ matrix `kerclus'[`ligne',3]=`nbitems'+`ligne'-1
+ local clus`g'=`nbitems'+`ligne'
+ local ligne=`ligne'+1
+ }
+ }
+ }
+}
+if `nbitems'<`nbkerk' {
+ di in red "You cannot define more variables in the {hi:kernel} option than items in the {hi:varlist}"
+ error 198
+ exit
+}
+di
+di in green "{hline 30}"
+di in green "TOTAL VARIANCE: " in ye %14.3f `totvar'
+di in green "NUMBER OF INDIVIDUALS: " in ye %7.0f `nbind'
+di in green "METHOD:" in ye _col(`=31-length("`method'")') "`=upper("`method'")'"
+di in green "{hline 30}"
+di
+if "`kernel'"!="" {
+ forvalues i=1/`nbkerg' {
+ di in green "The kernel numbered " in ye `clus`i'' in green " is composed of `nbi`i'' variables: " in ye "`list`i''"
+ di
+ }
+}
+else {
+ local nbkerk=0
+ local nbkerg=0
+}
+tempname Ev
+if `none'!=1 {
+ matrix `matclus'=J(`nbitems',`nbitems',0)
+ matrix `vp'=J(`=2*`nbitems'-1',10,0)
+ forvalues i=1/`nbitems' {
+ matrix `matclus'[`i',1]=`i'
+ if "`method'"!="polychoric"&"`method'"!="polychoric" {
+ qui su ``i'' [`weight'`exp']
+ matrix `vp'[`i',1]=r(Var)
+ }
+ else {
+ matrix `vp'[`i',1]=1
+ }
+ matrix `vp'[`i',8]=`i'
+ matrix `vp'[`i',9]=`totvar'
+ matrix `vp'[`i',10]=100
+ }
+ matrix `vp'[`nbitems',3]=`nbitems'
+ if "`method'"=="centroid" {
+ local crit G
+ di in green "{hline 89}"
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(82) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Variation"
+ di in green "{hline 89}"
+ }
+ else {
+ local crit T
+ di in green "{hline 100}"
+ if "`method'"=="v2"|"`method'"=="polychoricv2" {
+ di in green _col(84) "Maximal"
+ }
+ else {
+ di in green _col(84) "Current"
+ }
+ di in green _col(7) "Number of" _col(69) "`crit'" _col(71) "Explained" _col(85) "Second" _col(93) "Relative"
+ di in green "Step" _col(8) "clusters" _col(20) "Child 1" _col(33) "Child 2" _col(46) "Parent" _col(53) "`crit' value" _col(61) "variation" _col(72) "Variance" _col(81) "Eigenvalue" _col(92) "Variation"
+ di in green "{hline 100}"
+ }
+ tempname threshold
+ matrix `threshold'=J(`nbitems',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ local clus=`nbitems'+`i'
+ local minegenval=999999
+ local minegenval2=999999
+ forvalues k=1/`=`clus'-1' {
+ local list`k'
+ local numlist`k'
+ forvalues j=1/`clus' {
+ if (`matclus'[`j',`i']==`k') {
+ local list`k' `list`k'' ``j''
+ local numlist`k' `numlist`k'' `j'
+ }
+ }
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if "`method'"=="centroid" {
+ tempname centrj centrk diffjk
+ }
+ forvalues j=1/`clus' {
+ local nblistj:word count `list`j''
+ forvalues k=`=`j'+1'/`clus' {
+ local nblistk:word count `list`k''
+ if `nblistj'!=0&`nblistk'!=0 {
+ if "`method'"=="centroid" {
+ qui genscore `list`j'',score(`centrj') mean
+ qui su `centrj' [`weight'`exp']
+ local Varj=r(Var)
+ qui genscore `list`k'',score(`centrk') mean
+ qui su `centrk' [`weight'`exp']
+ local Vark=r(Var)
+ qui gen `diffjk'=`centrk'-`centrj'
+ qui su `diffjk' [`weight'`exp']
+ local Varjk=r(Var)
+ drop `centrj' `centrk' `diffjk'
+ local ev=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`Varjk'
+ if `ev'<`minegenval' {
+ local minegenval=`ev'
+ local minj `j'
+ local mink `k'
+ local eigen=0
+ local eigen2=0
+ }
+ }
+ else {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',1]+`vp'[`k',1]-`lambda1'
+ local ev2=max(`vp'[`j',5],`vp'[`k',5],`lambda2')
+ if ("`method'"=="v2"|"`method'"=="polychoricv2")&`ev'<`minegenval' {
+ local eigen2=`lambda2'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ }
+ else if ("`method'"=="classical"|"`method'"=="polychoric")&`ev2'<`minegenval2' {
+ local minegenval2=`ev2'
+ local eigen2=`ev2'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ local ligne=`clus'-`nbitems'
+ local j=`kerclus'[`ligne',2]
+ local k=`kerclus'[`ligne',3]
+ if "`method'"!="centroid" {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`j'' `list`k'' [`weight'`exp'],cov
+ matrix `Ev'=e(Ev)
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoricv2"{
+ qui polychoricpca `list`j'' `list`k'' [`weight'`exp']
+ matrix `Ev'=r(eigenvalues)
+ }
+ local lambda1=`Ev'[1,1]
+ local lambda2=`Ev'[1,2]
+ local ev=`vp'[`j',1]+`vp'[`k',1]-`lambda1'
+ local minegenval=`ev'
+ local eigen=`lambda1'
+ local minj `j'
+ local mink `k'
+ local eigen2=`lambda2'
+ }
+ else if "`method'"=="centroid" {
+ local nblistj:word count `list`j''
+ local nblistk:word count `list`k''
+ tempname v1 v2 v12
+ qui genscore `list`j'',score(`v1') mean
+ qui genscore `list`k'',score(`v2') mean
+ qui gen `v12'=`v1'-`v2'
+ qui su `v12' [`weight'`exp']
+ local varj=r(Var)
+ local minegenval=(`nblistj'*`nblistk')/(`nblistj'+`nblistk')*`varj'
+ local minj `j'
+ local mink `k'
+ }
+ }
+ if `minj'<=`nbitems' {
+ local nomj=abbrev("``minj''",14)
+ }
+ else {
+ local nomj `minj'
+ }
+ *set trace off
+ if `mink'<=`nbitems' {
+ local nomk=abbrev("``mink''",14)
+ }
+ else {
+ local nomk `mink'
+ }
+ forvalues j=1/`nbitems' {
+ matrix `matclus'[`j',`=`i'+1']=`matclus'[`j',`i']
+ }
+ if "`method'"!="centroid" {
+ matrix `vp'[`clus',1]=`eigen' /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',2]=`minegenval' /*VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',3]=`vp'[`=`clus'-1',3]-`vp'[`clus',2] /*T CRITERION*/
+ matrix `vp'[`clus',4]=`vp'[`clus',2]/`vp'[`=`clus'-1',3] /*RELATIVE VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',5]=`eigen2' /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',6]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',7]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',8]=`nbitems'+`i' /*NUMBER OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',9]=`vp'[`=`clus'-1',9]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',10]=`vp'[`clus',9]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ }
+ else {
+ matrix `vp'[`clus',1]=0 /*FIRST EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',2]=`minegenval' /*VARIATION OF THE G CRITERION*/
+ matrix `vp'[`clus',3]=`vp'[`=`clus'-1',3]-`vp'[`clus',2] /*G CRITERION*/
+ matrix `vp'[`clus',4]=`vp'[`clus',2]/`vp'[`=`clus'-1',3] /*RELATIVE VARIATION OF THE T CRITERION*/
+ matrix `vp'[`clus',5]=0 /*SECOND EIGEN VALUE OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',6]=`minj' /*CHILD 1*/
+ matrix `vp'[`clus',7]=`mink' /*CHILD 2*/
+ matrix `vp'[`clus',8]=`nbitems'+`i' /*NUMBER OF THE NEW CLUSTER*/
+ matrix `vp'[`clus',9]=`vp'[`=`clus'-1',9]-`minegenval' /*EXPLAINED VARIANCE*/
+ matrix `vp'[`clus',10]=`vp'[`clus',9]/`totvar'*100 /*% OF EXPLAINED VARIANCE*/
+ }
+ foreach j of numlist `numlist`minj'' `numlist`mink'' {
+ matrix `matclus'[`j',`=`i'+1']=`clus'
+ }
+ if "`kernel'"!=""&`i'==`=`nbkerk'-`nbkerg'+1' {
+ local T=`vp'[`=`clus'-1',9]
+ di _col(0) in ye "init" _col(12) %4.0f `=`nbitems'-`nbkerk'+`nbkerg'' _col(52) %8.4f `T' _col(62) %8.4f `=`totvar'-`T'' _col(72) %7.3f `=`T'/`totvar'*100' "%"
+ }
+ if `clus'>`nbitems'+`nbkerk'-`nbkerg' {
+ if `clus'==`nbitems'+`nbkerk'-`nbkerg'+1 {
+ local relv
+ local percent
+ }
+ else {
+ local relv=(`minegenval'-`vp'[`=`clus'-1',2])/`vp'[`=`clus'-1',3]*100
+ local percent %
+ matrix `threshold'[`=`nbitems'-`i'+1',1]=`relv'
+ matrix `threshold'[`=`nbitems'-`i'+1',3]=`minegenval'
+ if `i'>1 {
+ matrix `threshold'[`=`nbitems'-`i'+1',2]=`relv'-`threshold'[`=`nbitems'-`i'+2',1]
+ }
+ }
+ if "`method'"=="centroid" {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',9] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',10] "%" _col(83) _col(84) %5.2f `relv' "`percent'"
+ }
+ else {
+ di _col(0) in ye %4.0f `=`i'-`nbkerk'+`nbkerg'' _col(12) %4.0f `=`nbitems'-`i'' _col(20) "`nomj'" _col(33) "`nomk'" _col(45) %7.0f `=`i'+`nbitems'' _col(52) %8.4f `vp'[`clus',9] _col(62) %8.4f `minegenval' _col(72) %7.3f `vp'[`clus',10] "%" _col(83) %8.4f `vp'[`clus',5] _col(95) %5.2f `relv' "`percent'"
+ }
+ }
+ }
+ local i=2*`nbitems'-1
+ local relv=(`vp'[`i',3]-`vp'[`i',2])/`vp'[`i',3]*100
+ if "`method'"=="centroid" {
+ di in ye _col(84) %5.2f `relv' "`percent'"
+ }
+ else {
+ di in ye _col(95) %5.2f `relv' "`percent'"
+ }
+ matrix `threshold'[1,1]=`relv'
+ matrix `threshold'[1,2]=`relv'-`threshold'[2,1]
+ matrix `threshold'[1,3]=`vp'[`i',3]
+ *matrix list `threshold'
+ local best=0
+ local maxbest=0
+ local best2=0
+ local maxbest2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',3]>`maxbest2' {
+ if `threshold'[`i',3]>`maxbest' {
+ local maxbest2=`maxbest'
+ local best2=`best'
+ local maxbest=`threshold'[`i',3]
+ local best=`i'
+ }
+ else {
+ local maxbest2=`threshold'[`i',3]
+ local best2=`i'
+ }
+ }
+ }
+ di in green "{hline 100}"
+ di
+ di in green "{hline 24}"
+ di in green "PROPOSED BEST PARTITIONS"
+ di in green "{hline 24}"
+ di
+ di in yellow _col(4) "Based on the variation of the T criterion"
+ di in green _col(10) "1. Partitions in " in ye `best' in green " clusters"
+ di in green _col(10) "2. Partitions in " in ye `best2' in green " clusters"
+ return local bestvariation `best' `best2'
+ local bestt=0
+ local bestt2=0
+ local var=0
+ local var2=0
+ forvalues i=1/`nbitems' {
+ if `threshold'[`i',2]>`var2'&`i'<`nbitems'-1 {
+ if `threshold'[`i',2]>`var' {
+ local bestt2=`bestt'
+ local var2=`var'
+ local var=`threshold'[`i',2]
+ local bestt=`i'
+ }
+ else {
+ local var2=`threshold'[`i',2]
+ local bestt2=`i'
+ }
+ }
+ }
+ di in yellow _col(4) "Based on the research of a threshold"
+ di in green _col(10) "1. Partitions in " in ye `bestt' in green " clusters"
+ di in green _col(10) "2. Partitions in " in ye `bestt2' in green " clusters"
+ forvalues i=`=`nbitems'+1'/`=`nbitems'+`nbkerk'-`nbkerg'' {
+ matrix `vp'[`i',2]=`totvar'-`T'
+ matrix `vp'[`i',9]=`T'
+ matrix `vp'[`i',10]=`T'/`nbitems'*100
+ }
+ return local bestthresold `bestt' `bestt2'
+}
+
+if "`bar'"!="" {
+ drop _all
+ qui set obs `nbitems'
+ qui svmat `vp' ,names(v)
+ qui drop in 1/`nbitems'
+ qui gen id=`nbitems'-_n
+ qui drop if id>`nbitems'-`nbkerk'+`nbkerg'-1
+ label variable id "Number of clusters"
+ label variable v2 "T variation"
+ graph twoway bar v2 id, name(bar,replace) vert ,ylabel(0(0.5)2) xlabel(1(1)`=`nbitems'-`nbkerk'+`nbkerg'-1')
+}
+
+drop _all
+qui set obs `nbitems'
+qui svmat `matclus' ,names(v)
+local listorder
+forvalues i=`nbitems'(-1)1 {
+ local listorder `listorder' v`i'
+}
+qui gen id=_n
+qui sort `listorder'
+
+capture cluster delete clv,zap
+qui cluster complete v* ,name(clv)
+
+qui replace clv_id=_n
+qui replace clv_ord=id
+qui replace clv_hgt=.
+
+qui gen fait=0
+qui gen clus=0
+forvalues i=2/`nbitems' {
+ local ligne=`nbitems'+`i'-1
+ if (`vp'[`ligne',6]<=`nbitems') {
+ local first=`vp'[`ligne',6]
+ gsort +fait -v`i' +clv_id
+ }
+ else {
+ local first=`vp'[`ligne',7]
+ gsort +fait -v`i' +clv_id
+ }
+ if "`deltaT'"!="" {
+ qui replace clv_hgt=`vp'[`ligne',2] in 1
+ }
+ else {
+ qui replace clv_hgt=100-`vp'[`ligne',10] in 1
+ }
+ qui replace fait=1 in 1
+ qui replace clus=`vp'[`ligne',8] in 1
+}
+qui gen label=""
+forvalues i=1/`nbitems' {
+ qui replace label=abbrev("`label`i''",`abbrev') if clv_id==`i'
+}
+sort clv_id
+if `nbitems'>`cutnumber' {
+ local var "Groups of variables"
+ local cut cutnumber(`cutnumber') /*labcutn*/
+}
+else {
+ local var "Variables"
+ local cut label(label)
+}
+qui su clv_hgt
+local tmp=r(max)
+local max=floor(`tmp')+.5
+if `tmp'>`max' {
+ local max=`max'+.5
+}
+local maxvar=`max'+5
+if "`dendro'"=="" {
+ if "`title'"=="" {
+ local title "Clustering around Latent Variables (CLV)"
+ }
+ if "`caption'"!="" {
+ local var "`caption'"
+ }
+ if "`deltaT'"!="" {
+ local titleL "Variation of the T criterion"
+ local yl "0(.5)`max'"
+ }
+ else {
+ local titleL "% Unexplained Variance"
+ local yl "0(25)`maxvar'"
+ }
+ if "`horizontal'"!="" {
+ cluster dendro clv, name (dendrogram,replace) hor ytitle("`var'") `showcount' xtitle("`titleL'") title("`title'",span) xlabel(`yl') ylabel(,angle(0)) `cut'
+ }
+ else {
+ cluster dendro clv, name(dendrogram,replace) xtitle("`var'") `showcount' ytitle("`titleL'") title("`title'",span) ylabel(`yl') `cut'
+ }
+}
+
+if `cons'>`nbitems'-`nbkerk'+`nbkerg' {
+ di in ye "The {hi:consolidation} is not possible for a number of clusters superior to the initial number of clusters"
+ local cons=0
+}
+
+if `cons'!=0 {
+ sort v`=`nbitems'-`cons'+1'
+ gen cut`cons'=1
+ local g=1
+ forvalues i=2/`nbitems' {
+ if v`=`nbitems'-`cons'+1'[`i']!=v`=`nbitems'-`cons'+1'[`=`i'-1'] {
+ local g=`g'+1
+ }
+ qui replace cut`cons'=`g' in `i'
+ }
+ sort id
+ tempname group
+ mkmat cut`cons',matrix(`group')
+
+ *cluster generate cut = groups(2/9) , name(clv)
+ use `clvfiletmp',replace
+
+ local n=1
+ local env=1
+ while (`env'==1) {
+ forvalues g=1/`cons' {
+ local list`g'
+ forvalues i=1/`nbitems' {
+ if `group'[`i',1]==`g' {
+ local list`g' `list`g'' ``i''
+ }
+ }
+ }
+ di
+ if `n'==1 {
+ di in green "{hline 30}"
+ di in green "PARTITION BEFORE CONSOLIDATION"
+ di in green "{hline 30}"
+ }
+ di
+ local col=1
+ local max=0
+ local critT=0
+ forvalues g=1/`cons' {
+ di _col(`col') in green "GROUP " %2.0f `g' _c
+ local col=`col'+10
+ local tmp`g':word count `list`g''
+ if `tmp`g''>`max' {
+ local max `tmp`g''
+ }
+ tempvar f1`g'
+ if "`method'"=="centroid" {
+ qui genscore `list`g'',score(`f1`g'') mean
+ qui su `f1`g'' [`weight'`exp']
+ local var=r(Var)
+ local critT=`critT'+`tmp`g''*`var'
+ }
+ else {
+ if `tmp`g''>1 {
+ if "`method'"=="classical"|"`method'"=="v2" {
+ qui pca `list`g'' [`weight'`exp'] ,cov
+ matrix `Ev'=e(Ev)
+ qui predict `f1`g''
+ }
+ else if "`method'"=="polychoric"|"`method'"=="polychoric" {
+ qui polychoricpca `list`g'' [`weight'`exp'] ,score(`f1`g'') nscore(1)
+ matrix `Ev'=r(eigenvalues)
+ rename `f1`g''1 `f1`g''
+ }
+ local lambda1=`Ev'[1,1]
+ local critT=`critT'+`lambda1'
+ }
+ else {
+ qui gen `f1`g''=`list`g''
+ if "`standardized'"=="" {
+ local critT=`critT'+1
+ }
+ else {
+ qui su [`weight'`exp']
+ local critT=`critT'+`r(Var)'
+ }
+ }
+ }
+ }
+ di
+ forvalues i=1/`max' {
+ local col=1
+ forvalues g=1/`cons' {
+ local tmpv:word `i' of `list`g''
+ local tmpv=abbrev("`tmpv'",8)
+ di _col(`col') in ye %8s "`tmpv'" _c
+ local col= `col'+10
+ }
+ di
+ }
+ di
+ di in green "Variance Explained : " in ye %6.3f `=`critT'/`totvar'*100' in green "%"
+ di in green "T criterion : " in ye %6.4f `critT'
+ di
+ di in green "{hline 21}"
+ di in green "CONSOLIDATION: STEP `n'"
+ di in green "{hline 21}"
+ local n=`n'+1
+ local env=0
+ if "`method'"=="polychoric"|"`method'"=="polychoricv2" {
+ local command polychoric
+ }
+ else {
+ local command corr
+ }
+ forvalues i=1/`nbitems' {
+ local env`i'=0
+ local gr=`group'[`i',1]
+ qui `command' ``i'' `f1`gr'' [`weight'`exp']
+ local corr`i'=r(rho)
+ local corrs`i'=r(rho)
+ forvalues g=1/`cons' {
+ qui `command' ``i'' `f1`g'' [`weight'`exp']
+ local tmpcorr=r(rho)
+ if `g'!=`gr'&(((`corr`i'')<(`tmpcorr')&"`method'"=="centroid")|((`corr`i'')^2<(`tmpcorr')^2& "`method'"!="centroid")) {
+ local env=1
+ local env`i'=1
+ matrix `group'[`i',1]=`g'
+ local corr`i'=`tmpcorr'
+ }
+ }
+ if `env`i''==1 {
+ local g=`group'[`i',1]
+ di in green "The variable " in ye "``i'' " in green "is assigned to the `g'th group" _c
+ if "`method'"!="centroid" {
+ di in green " (corr^2=" %6.4f in ye (`corr`i'')^2 in green " vs " in ye %6.4f (`corrs`i'')^2 in green ")"
+ }
+ else {
+ di in green " (corr=" %6.4f in ye (`corr`i'') in green " vs " in ye %6.4f (`corrs`i'') in green ")"
+ }
+
+ }
+ }
+ if `env'==0 {
+ local latent
+ forvalues g=1/`cons' {
+ label variable `f1`g'' "Latent variable `g'"
+ if "`genlv'"!="" {
+ gen `genlv'`g'=`f1`g''
+ }
+ local latent `latent' `f1`g''
+ return local cluster`g' `list`g''
+ }
+ matrix `group'=`group''
+ matrix colnames `group'=`varlist'
+ return matrix affect=`group'
+ di in ye "Stability of the partition is achieved"
+ if `cons'<=7 {
+ di
+ di in green "{hline 42}"
+ di in green "CORRELATION MATRIX OF THE LATENT VARIABLES"
+ di in green "{hline 42}"
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+23') in green "Latent" _c
+ }
+ di
+ forvalues g=1/`cons' {
+ di _col(`=13*(`g'-1)+19') in green "variable `g'" _c
+ }
+ di
+ di in green "{hline `=(`cons')*13+15'}"
+ forvalues g=1/`cons' {
+ di in green "Latent variable `g'" _c
+ forvalues h=1/`g' {
+ local loc=13*`h'+10
+ qui corr `f1`g'' `f1`h'' [`weight'`exp']
+ local rho=r(rho)
+ di _col(`loc') in ye %6.4f `rho' _c
+ }
+ di
+ }
+ di in green "{hline `=(`cons')*13+15'}"
+ di
+ }
+ if `nbind'<=800&"`biplot'"==""&"`weight'"=="" {
+ local max=max(`matsize',`nbind')
+ set matsize `max'
+ if "`addvar'"!="" {
+ local add `varlist'
+ }
+ qui biplotvlab `latent' `add', name(biplot,replace) norow colopts(name(latent variables)) alpha(0) title(Biplot of the latent variables) labdes(size(vsmall) color(blue)) stretch(1)
+ }
+ else if `nbind'>800&"`biplot'"==""&"`weight'"==""{
+ di in green "There is more than 800 individuals, so the {hi:biplot} option is disabled"
+ }
+ else if "`weight'"!=""&&"`biplot'"==""{
+ di in green "The {hi:biplot} option is disabled because you use weights"
+ }
+ }
+ forvalues g=1/`cons' {
+ drop `f1`g''
+ }
+ }
+}
+set matsize `matsize'
+use `clvfile',replace
+capture cluster delete clv,zap
+return matrix vp=`vp'
+return matrix matclus=`matclus'
+return local varlist `varlist'
+return local method `method'
+return local kernel `kernel'
+end
diff --git a/Modules/ado/personal/c/compart.ado b/Modules/ado/personal/c/compart.ado
new file mode 100644
index 0000000..a74c88d
--- /dev/null
+++ b/Modules/ado/personal/c/compart.ado
@@ -0,0 +1,291 @@
+program define compart,rclass
+version 8
+syntax varlist [if] [in] [fweight iweight] [,part(numlist) Matrix(string) type(string) DETails noSTANDardized VARiables SQUare]
+
+preserve
+unab varlist:`varlist'
+di "`varlist'"
+tokenize `varlist'
+marksample touse
+local nbvar:word count `varlist'
+qui count
+local nbind=r(N)
+tempname p
+qui gen `p'=1
+qui su `p' [`weight'`exp'] if `touse'
+local nbind=r(N)
+if "`square'"=="" {
+ local quad=1
+}
+else {
+ local quad=2
+}
+
+if "`type'"!=""&"`type'"!="polychoric" {
+ di in red "The type of the matrix is not authorized. Please correct your {hi:type} option."
+ error 198
+}
+if "`type'"!=""&"`matrix'"!="" {
+ di in red "You cannot define in the same time the {hi:type} and the {hi:matrix} options"
+ error 198
+}
+
+/* DEFINITION OF THE PARTITION OF THE VARIABLES*/
+
+local newpart
+foreach i in `part' {
+ if `i'!=0 {
+ local newpart `newpart' `i'
+ }
+}
+local part `newpart'
+local meme=0
+local diff=0
+local nbpart:word count `part'
+forvalues i=1/`nbpart' {
+ local iti:word `i' of `part'
+ local meme=`meme'+`iti'*(`iti'-1)/2
+ forvalues j=`=`i'+1'/`nbpart' {
+ local itj:word `j' of `part'
+ local diff=`diff'+`iti'*`itj'
+ }
+}
+
+local perc=`meme'/(`meme'+`diff')
+di "meme: `meme' ; diff: `diff' ; perc: `perc'"
+
+
+local test=0
+local last0=0
+forvalues i=1/`nbpart' {
+ local first`i'=`last`=`i'-1''+1
+ local size`i':word `i' of `part'
+ local last`i'=`first`i''+`size`i''-1
+ local test=`test'+`size`i''
+ local list`i'
+ forvalues j=`first`i''/`last`i'' {
+ local list`i' `list`i'' ``j''
+ }
+}
+if `test'!=`nbvar' {
+ di in red "{p}The described partition of the variables is composed of a number of variables different of the number of variables of varlist.{p_end}"
+ exit 198
+}
+
+/* BY DEFAULT, STANDARDIZATION*/
+if "`standardized'"=="" {
+ forvalues i=1/`nbvar' {
+ qui su ``i'' [`weight'`exp']
+ qui replace ``i''=(``i''-r(mean))/r(sd)
+ }
+}
+
+tempname Cov W
+if "`matrix'"==""&"`type'"!="polychoric" {
+ /* COVARIANCE OR CORRELATION MATRIX*/
+ qui matrix accum `Cov'=`varlist' [`weight'`exp'],nocons dev
+ qui matrix `Cov'=`Cov'/(`nbind'-1)
+}
+else if "`type'"=="polychoric" {
+ qui polychoric `varlist'
+ qui matrix `Cov'=r(R)
+}
+else {
+ qui matrix `Cov'=`matrix'
+}
+ /* WE SAVE THE MATRIX AND WE COMPUTE THE AVERAGE COVARIANCE */
+qui matrix `W'=`Cov'
+local sum=0
+forvalues i=1/`nbvar' {
+ forvalues j=`=`i'+1'/`nbvar' {
+ local sum=`sum'+ `W'[`i',`j']^`quad'
+ }
+}
+
+/* WE SAVE THE DATA AND WE COMPUTES THE USED PERCENTILES OF THE COVARIANCE*/
+
+tempfile compartfile
+qui save `compartfile',replace
+
+drop _all
+set obs `=`nbvar'*(`nbvar'-1)'
+local n=1
+qui gen i=.
+qui gen j=.
+qui gen corr=.
+forvalues i=1/`nbvar' {
+ forvalues j=`=`i'+1'/`nbvar' {
+ qui replace i=`i' in `n'
+ qui replace j=`j' in `n'
+ qui replace corr=`W'[`i',`j']^`quad' in `n'
+ local ++n
+ }
+}
+matrix list `W'
+su corr
+sort corr
+centile corr,centile(`=100-`perc'*100')
+local centile=r(c_1)
+if `diff'!=0 {
+ local perc2=(`meme'+1)/(`meme'+`diff')
+ centile corr,centile(`=100-`perc2'*100')
+ local centile2=r(c_1)
+ local centile=(`centile'+`centile2')/2
+}
+qui use `compartfile',clear
+
+/***************************************************/
+
+if `nbpart'==1 {
+ local mean=0
+* local mean=(2*`sum')/(`nbvar'*(`nbvar'-1))
+}
+else {
+ local mean=(2*`sum')/(`nbvar'*(`nbvar'-1))
+ local mean=0
+ *local mean=`centile'
+}
+
+/*THE MATRIX IS CENTERED*/
+
+forvalues i=1/`nbvar' {
+ matrix `W'[`i',`i']=0
+ forvalues j=`=`i'+1'/`nbvar' {
+ matrix `W'[`i',`j']=(`W'[`i',`j']^`quad'-`mean')
+ matrix `W'[`j',`i']=`W'[`i',`j']
+ }
+}
+
+/*WE COMPUTE THE INDEX D*/
+local C=0
+local C1=0
+local C2=0
+local minrho=2
+local summeme=0
+local sumdiff=0
+if "`square'"!="" {
+ local maxrho=0
+}
+else {
+ local maxrho=-2
+}
+*set trace on
+forvalues i=1/`nbpart' {
+ forvalues j=1/`nbpart' {
+ forvalues k=`first`i''/`last`i'' {
+ forvalues l=`first`j''/`last`j'' {
+ if `i'!=`j' {
+ if `k'>`l' {
+ local sumdiff=`sumdiff'+`Cov'[`k',`l']
+ }
+ if (`Cov'[`k',`l'])^`quad'>(`maxrho')^`quad' {
+ local maxrho=(`Cov'[`k',`l'])
+ }
+ matrix `W'[`k',`l']=-(`W'[`k',`l'])
+ }
+ else if (`Cov'[`k',`l'])^`quad'<(`minrho')^`quad'&`k'!=`l' {
+ local minrho=`Cov'[`k',`l']
+ }
+ if `i'==`j'&`k'>`l' {
+ local summeme=`summeme'+`Cov'[`k',`l']
+ }
+ local C=`C'+`W'[`k',`l']
+ local C1=`C1'+abs(`W'[`k',`l'])
+ if `W'[`k',`l']>+0 {
+ local ++C2
+ }
+ }
+ }
+ }
+}
+if `meme'!=0 {
+ local summeme=`summeme'/`meme'
+}
+if `diff'!=0 {
+ local sumdiff=`sumdiff'/`diff'
+}
+local diffsum=`summeme'-`sumdiff'
+set trace off
+di "Summeme: `summeme' ; Sumdiff: `sumdiff'"
+
+local minrho=(`minrho')^(`quad')
+local maxrho=(`maxrho')^(`quad')
+
+local C=sign(`C')*(abs(`C'))^(1/`quad')/(`nbvar'*(`nbvar'-1))+`mean'
+local C1=(`C1')^(1/`quad')/(`nbvar'*(`nbvar'-1))
+local C2=(`C2')/(`nbvar'*(`nbvar'-1))*100
+return local Pcov=`=`C'/`C1''
+return local Pel=`=`C2'/100'
+
+if `nbpart'==1 {
+ local C=`C'*(`nbvar'+1)/`nbvar'
+}
+
+*di "C:" `C' " C1: " `C1' " C2: " `C2'
+if `nbpart'==1 {
+ local maxrho=0
+}
+if `nbpart'==`nbvar' {
+ local minrho=0
+}
+di " C=(`meme'*`minrho'-`diff'*`maxrho')/(`meme'+`diff')"
+local C=(`meme'*`minrho'-`diff'*`maxrho')/(`meme'+`diff')
+di in green "{hline 80}"
+di in green "Number of individuals: " _col(71) in ye %8.0f `nbind'
+di in green "Number of variables: " _col(71) in ye %8.0f `nbvar'
+di in green "COMPART index: " _col(71) in ye %8.6f `C'
+di in green "Proportion of the covariances explained by the COMPART index: " _col(73) in ye %6.2f `=abs(`C')/`C1'*100' "%"
+di in green "Proportion of positive elements in the matrix: " _col(73) in ye %6.2f `C2' "%"
+di in green "Minimum correlation coefficient for 2 variables of the same group: " _col(74) in ye %5.2f `minrho'
+di in green "Maximum correlation coefficient for 2 variables of two different groups: " _col(74) in ye %5.2f `maxrho'
+di in green "Average correlation coefficient: " _col(74) in ye %5.2f `mean'
+di in green "{hline 80}"
+di
+if "`details'"!="" {
+ di in green "Matrix of the coefficients"
+ di in green "{hline 26}"
+ matrix list `W' ,noheader format(%7.4f)
+ di
+}
+if "`variables'"!="" {
+ di in green "Details for each variable"
+ di in green "{hline 26}"
+ di
+ di in green "{hline 80}"
+ di in green "Items" _col(17) "COMPART" _col(26) "Problematic items"
+ di in green "{hline 80}"
+ tempname Cvar
+ matrix `Cvar'=J(1,`nbvar',0)
+ forvalues i=1/`nbvar' {
+ local C`i'=0
+ local pourri`i'
+ forvalues j=1/`nbvar' {
+ local C`i'=`C`i''+`W'[`i',`j']
+ if `W'[`i',`j']<0 {
+ local pourri`i' `pourri`i'' ``j''
+ }
+ }
+ local C`i'=`C`i''/(`nbvar'-1)
+ matrix `Cvar'[1,`i']=`C`i''
+ di in ye abbrev("``i''",14) _col(15) %9.6f `C`i'' _c
+ if "`pourri`i''"!="" {
+ di in ye _col(26) "`pourri`i''"
+ }
+ else {
+ di
+ }
+ }
+ di in green "{hline 80}"
+ matrix colnames `Cvar'=`varlist'
+ matrix rownames `Cvar'=Compart
+ return matrix Cvar=`Cvar'
+}
+local test=`maxrho'-`minrho'
+local diffsum=(`summeme'*`meme'-`diff'*`sumdiff')/(`meme'+`diff')
+local diffsum=`summeme'/*-`sumdiff'*/
+return local compart `C'
+return local mean `mean'
+return local list `varlist'
+return local part `part'
+restore
+end
diff --git a/Modules/ado/personal/c/compart2.ado b/Modules/ado/personal/c/compart2.ado
new file mode 100644
index 0000000..725b35e
--- /dev/null
+++ b/Modules/ado/personal/c/compart2.ado
@@ -0,0 +1,120 @@
+program define compart2,rclass
+version 9
+syntax varlist [if] [in] [fweight iweight] [,part(numlist) type(string)]
+
+preserve
+unab varlist:`varlist'
+di "`varlist'"
+tokenize `varlist'
+marksample touse
+local nbvar:word count `varlist'
+qui count
+local nbind=r(N)
+tempname p
+qui gen `p'=1
+qui su `p' [`weight'`exp'] if `touse'
+local nbind=r(N)
+if "`square'"=="" {
+ local quad=1
+}
+else {
+ local quad=2
+}
+
+if "`type'"=="" {
+ local type classical
+}
+if "`type'"!="classical"&"`type'"!="centroid"&"`type'"!="polychoric" {
+ di in red "The type of the matrix is not authorized. Please correct your {hi:type} option."
+ error 198
+}
+
+/* DEFINITION OF THE PARTITION OF THE VARIABLES*/
+
+local newpart
+foreach i in `part' {
+ if `i'!=0 {
+ local newpart `newpart' `i'
+ }
+}
+local part `newpart'
+local meme=0
+local diff=0
+local nbpart:word count `part'
+forvalues i=1/`nbpart' {
+ local iti:word `i' of `part'
+ local meme=`meme'+`iti'*(`iti'-1)/2
+ forvalues j=`=`i'+1'/`nbpart' {
+ local itj:word `j' of `part'
+ local diff=`diff'+`iti'*`itj'
+ }
+}
+
+local perc=`meme'/(`meme'+`diff')
+di "meme: `meme' ; diff: `diff' ; perc: `perc'"
+
+
+local test=0
+local last0=0
+forvalues i=1/`nbpart' {
+ local first`i'=`last`=`i'-1''+1
+ local size`i':word `i' of `part'
+ local last`i'=`first`i''+`size`i''-1
+ local test=`test'+`size`i''
+ local list`i'
+ forvalues j=`first`i''/`last`i'' {
+ local list`i' `list`i'' ``j''
+ }
+}
+if `test'!=`nbvar' {
+ di in red "{p}The described partition of the variables is composed of a number of variables different of the number of variables of varlist.{p_end}"
+ exit 198
+}
+
+forvalues g=1/`nbpart' {
+ tempname f1`g'
+ if `size`g''>1 {
+ if "`type'"=="classical" {
+ qui pca `list`g'',cov
+ qui predict `f1`g''
+ }
+ else if "`type'"=="polychoric" {
+ qui polychoricpca `list`g'',score(`f1`g'') nscore(1)
+ rename `f1`g''1 `f1`g''
+ }
+ else if "`type'"=="centroid" {
+ qui genscore `list`g'', score(`f1`g'') mean
+ }
+ }
+ else if `size`g''==1 {
+ qui gen `f1`g''=`list`g''
+ }
+}
+local minrho=2
+local maxrho=-2
+forvalue i=1/`nbvar' {
+ forvalues g=1/`nbpart' {
+ qui corr ``i'' `f1`g''
+ if `i'>=`first`g''&`i'<=`last`g'' {
+ if r(rho)<`minrho' {
+ local minrho=r(rho)
+ }
+ }
+ else if r(rho)>`maxrho' {
+ local maxrho=r(rho)
+ }
+ }
+}
+
+di "C=(`meme'*`minrho'-`diff'*`maxrho')/(`meme'+`diff')"
+local C=(`meme'*`minrho'-`diff'*`maxrho')/(`meme'+`diff')
+local C=(`meme'*`minrho'-`diff'*`maxrho')/(`meme'+`diff')
+*local C=`minrho'
+di "C= `C' min=`minrho' max=`maxrho'"
+
+return local compart `C'
+*return local mean `mean'
+*return local list `varlist'
+return local part `part'
+restore
+end
diff --git a/Modules/ado/personal/c/conc.ado b/Modules/ado/personal/c/conc.ado
new file mode 100644
index 0000000..7c5c377
--- /dev/null
+++ b/Modules/ado/personal/c/conc.ado
@@ -0,0 +1,81 @@
+capture program drop conc
+program conc,rclass
+syntax varlist, comp(varlist) [tconc(real 0.4)]
+
+di as result "{hline}"
+di "{bf:Concurrent validity}"
+di as result "{hline}"
+di
+
+local n : word count `varlist'
+local p : word count `comp'
+
+matrix m = J(`n',`p',.)
+matrix rownames m = `varlist'
+matrix colnames m = `comp'
+local r = 1
+
+foreach i in `varlist' {
+ local c = 1
+ foreach j in `comp' {
+ qui corr `i' `j'
+ mat e = r(C)
+ local f = e[2,1]
+ mat m[`r',`c'] = `f'
+ local `++c'
+ }
+ local `++r'
+}
+
+*mat li m, format(%3.2f) noheader
+
+tokenize `varlist'
+local maxv = length("`1'")
+forvalues i=1/`n' {
+ local lenv = length("``i''")
+ if `lenv' > `maxv' local maxv = `lenv'
+}
+
+local decv = `maxv'+6
+
+tokenize `comp'
+local maxc = length("`1'")
+forvalues i=1/`p' {
+ local lenc = length("``i''")
+ if `lenc' > `maxc' local maxc = `lenc'
+}
+
+local decc = `maxc'+4
+
+local col = `decv'
+foreach c in `comp' {
+ di as result _col(`col') "`c'" _c
+ local col = `col'+`decc'
+}
+di
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+
+forvalues i=1/`n' {
+ di as result "`var`i''" _c
+ local col = `decv'
+ forvalues j=1/`p' {
+ local t = m[`i',`j']
+ if `t' > `tconc' | `t' < -`tconc' {
+ di as result _col(`=`col'-1') %5.2f `t' _c
+ }
+ else di as text _col(`=`col'-1') %5.2f `t' _c
+ local col = `col'+`decc'
+ }
+ di
+}
+
+end
+
+*conc HA-MOC, comp(ioc1 ioc2) tconc(0.4)
+*conc x1-x40, comp(x1 x2) tconc(0.4)
diff --git a/Modules/ado/personal/c/convdiv.ado b/Modules/ado/personal/c/convdiv.ado
new file mode 100644
index 0000000..1e71a7c
--- /dev/null
+++ b/Modules/ado/personal/c/convdiv.ado
@@ -0,0 +1,298 @@
+capture program drop convdiv
+program convdiv
+syntax varlist, PARTition(numlist integer >0) [SCOrename(string) TCONVdiv(real 0.4) convdivboxplots]
+preserve
+
+qui set autotabgraphs on
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+}
+
+qui detect `varlist', partition(`partition')
+
+matrix A = r(Corrrestscores)
+matrix B = r(Corrscores)
+
+local i = 1
+local y = 1
+
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ matrix B[`z',`i'] = A[`z',`i']
+ }
+ local `i++'
+ local y = `s'+1
+}
+
+if "`scorename'"!="" {
+ matrix colnames B = `scorename'
+}
+else {
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+matrix colnames B = `scorename'
+}
+
+/* coupure noms des scores */
+/*
+local i = 1
+foreach s in `scorename' {
+ local len = length("`s'")
+ if `len' > 5 {
+ local c = substr("`s'",1,4)
+ local d = substr("`s'",-1,1)
+ local s`i' "`c'" "~" "`d'"
+ }
+ else local s`i' = "`s'"
+ local sc `sc' `s`i''
+ local `++i'
+}
+*/
+
+/* coupure noms des items */
+/*
+local i = 1
+foreach s in `varlist' {
+ local len = length("`s'")
+ if `len' > 10 {
+ local c = substr("`s'",1,9)
+ local d = substr("`s'",-1,1)
+ local var`i' "`c'" "~" "`d'"
+ }
+ else local var`i' = "`s'"
+ local `++i'
+}
+*/
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+local i = 1
+foreach s in `scorename' {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+di as result "{hline}"
+di "{bf:Correlation matrix}"
+di "{hline}"
+di
+
+/*
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+*/
+ /*
+tokenize `sc'
+local max = 3
+
+forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+}
+
+
+local maxit = 1
+
+forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `maxit' local maxit = `len'
+}
+*/
+local dec = 10
+local col = `dec'
+
+local decit = 14
+local colit = `decit'
+
+
+local col1 = `decit'
+forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+}
+
+di
+local h = (`P'-1)*`dec'+`decit'+4
+di "{hline `h'}"
+
+local i = 1
+local j = 1
+local y = 1
+
+foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [counting cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ di in red _col(`col') "{bf:`t'}" _c
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ di _col(`col') "{bf:`t'}" _c
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ di in red _col(`col') "`t'" _c
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ di as text _col(`col') "{text:`t'}"_c
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+}
+
+local y = 1
+local h = 1
+local np : word count `partition'
+
+foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ *rename C_`h'_`j'
+ *mat li C_`h'_`j'
+ }
+
+ local `++h'
+ local y = `s'+1
+}
+
+if "`convdivboxplots'" != "" {
+ forvalues h = 1/`np' {
+ tokenize `scorename'
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ *rename C_`h'_`j' _``j''
+ *di "`tp_`h'_`j''"
+ local call `call' /*_``j''*/ `tp_`h'_`j''
+ *if `h' == `j' local color = "blue"
+ *else local color = ""
+ local callbox `callbox' box(`j',fcolor(`color') lcolor(`color')) marker(`j', mcolor(`color'))
+
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ *di `"`callleg'"'
+ *di "`call'"
+
+ }
+ graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and dimensions) yline(`tconvdiv', lpattern(dot) lcolor(black))
+ qui set autotabgraphs on
+ *drop `call'
+ }
+}
+
+/*
+foreach var of varlist ioc1 ioc2 ioc3 {
+ loc varlab `""`:var l `var''""'
+ loc varlabs `"`varlabs'`varlab'"'
+ di "`varlab'"
+}
+*/
+
+/*
+svmat B
+
+local y = 1
+local h = 1
+qui gen d = 0
+foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ replace d = `h' in `y'/`s'
+
+ local `++h'
+ local y = `s'+1
+}
+
+twoway (scatter B1 d)
+*/
+local t : di %5.3f `tconvdiv'
+local p1 = (`nbvars'-`cptconv')/`nbvars'*100
+local p1 : di %4.1f `p1'
+local p2 = (`nbvars'-`cptdiv')/`nbvars'*100
+local p2 : di %4.1f `p2'
+
+di
+di as result "Convergent validity:" _c
+di as text " `=`nbvars'-`cptconv''/`nbvars' items (`p1'%) have a correlation coefficient with the score of "
+di _col(22) "their own dimension greater than `t'"
+di
+di as result "Divergent validity:" _c
+di as text " `=`nbvars'-`cptdiv''/`nbvars' items (`p2'%) have a correlation coefficient with the score"
+di _col(22) "of their own dimension greater than those computed with other scores."
+
+
+end
+
+*convdiv ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(Hddfdfdffda PSE W BCC Afdfdfererdfc AE LI MOC) tconvdiv(0.4) // convdivboxplots
+*convdiv x1-x40, partition(5 5 5 5 5 5 5 5) scorename(Hdfda PSE W BCC Afdfdfererdfc AE LI MOC) tconvdiv(0.4) // convdivboxplots
diff --git a/Modules/ado/personal/d/dege.ado b/Modules/ado/personal/d/dege.ado
new file mode 100644
index 0000000..c21030b
--- /dev/null
+++ b/Modules/ado/personal/d/dege.ado
@@ -0,0 +1,16 @@
+program define dege
+syntax anything [, i(string)]
+preserve
+if "`i'"=="" {
+ local i ind
+}
+qui reshape long `anything',i(`i') j(item)
+qui rename `anything' response
+qui inspect item
+local nbvalues=r(N_unique)
+forvalues j=1/`nbvalues' {
+ qui gen `anything'`j'=item==`j'
+ qui replace `anything'`j'=-`anything'`j'
+}
+restore,not
+end
diff --git a/Modules/ado/personal/d/delta.ado b/Modules/ado/personal/d/delta.ado
new file mode 100644
index 0000000..5f431bf
--- /dev/null
+++ b/Modules/ado/personal/d/delta.ado
@@ -0,0 +1,108 @@
+*! Delta version 1.5 - 5 March 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* DELTA: delta coefficient
+* Version 1.5: March 5, 2008
+*
+* Historic
+* Version 1 (2007-05-21): Jean-Benoit Hardouin
+* Version 1.1 (2007-05-22): Jean-Benoit Hardouin /* if in and possibility to use the score*/
+* Version 1.2 (2007-05-22): Jean-Benoit Hardouin /*bug when a score is missing*/
+* Version 1.3 (2007-06-16): Jean-Benoit Hardouin /*change in the options*/
+* Version 1.4 (2007-07-03): Jean-Benoit Hardouin /*correct a bug in the options*/
+* Version 1.5 (2008-03-05): Jean-Benoit Hardouin /*correct a bug in the ci option*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007-2008 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 delta , rclass
+version 7.0
+syntax varlist(min=1 numeric) [if] [in] [,ci(integer 0) noDots MINscore(int 0) MAXscore(int 0)]
+
+preserve
+tempfile deltafile
+qui save `deltafile'
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+local scoremin=`minscore'
+local scoremax=`maxscore'
+
+
+
+tempvar score
+if `nbitems'==1&`scoremax'==0 {
+ di in red "If you indicate only the score variable, you must define the {cmd:scoremax} option"
+ error 198
+}
+else if `nbitems'==1&`scoremax'!=0 {
+ qui gen `score'=`varlist'
+}
+else {
+ qui genscore `varlist',score(`score')
+}
+qui drop if `score'==.
+qui count
+local nbind=r(N)
+
+if `scoremax'==0 {
+ qui su `score'
+ local scoremax=r(max)
+}
+
+tempname error
+gen `error'=`score'<`scoremin'|`score'>`scoremax'
+qui count if `error'==1
+local err=r(N)
+if `err'!=0 {
+ di in red "`err' individuals has(have) a score inferior to `scoremin' or superior to `scoremax'"
+ error 198
+}
+
+local sumsqscore=0
+forvalues i=`scoremin'/`scoremax' {
+ qui count if `score'==`i'
+ local score`i'=r(N)
+ local sumsqscore=`sumsqscore'+`score`i''^2
+}
+local delta=(1+`scoremax')*(`nbind'^2-`sumsqscore')/(`nbind'^2*`scoremax')
+
+di in green "Range of the scores : " in ye `scoremin' in gr "/" in ye `scoremax'
+di in green "Number of used individuals : " in ye `nbind'
+
+if `ci'!=0 {
+ bootstrap delta=r(delta), reps(`ci') nowarn noheader nolegend `dots': delta `varlist' ,minscore(`scoremin') maxscore(`scoremax')
+}
+else {
+ display in green "Delta= " in yellow %8.6f `delta'
+}
+return scalar delta=`delta'
+qui use `deltafile',clear
+restore,not
+
+end
diff --git a/Modules/ado/personal/d/descitems.ado b/Modules/ado/personal/d/descitems.ado
new file mode 100644
index 0000000..283b29e
--- /dev/null
+++ b/Modules/ado/personal/d/descitems.ado
@@ -0,0 +1,250 @@
+capture program drop descitems
+program descitems
+syntax varlist, PARTition(numlist integer >0)
+local i = 1
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+/*
+qui su `var1'
+local min = r(min)
+local max = r(max)
+
+forvalue i=2/`nbvars' {
+ qui su `var`i''
+ local minloc = r(min)
+ local maxloc = r(max)
+ if `minloc'<`min' local min = `minloc'
+ if `maxloc'>`max' local max = `maxloc'
+}
+*/
+
+foreach var in `varlist' {
+ qui replace `var' = round(`var')
+}
+
+local lev = ""
+foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ foreach l in `levels' {
+ if strpos("`lev'","`l'") == 0 {
+ local lev `lev' `l'
+ }
+ }
+}
+
+_qsort_index `lev'
+local lev = r(slist1)
+
+local i = 1
+matrix d = J(`nbvars',4,.)
+
+foreach var in `varlist'{
+ qui count if missing(`var')
+ local ct=r(N)
+
+ local tx`i'=`ct'/_N
+ matrix d[`i',1] = `tx`i''
+ local `i++'
+}
+
+matrix rownames d = `varlist'
+matrix colnames d = "missing" "alpha" "Hj"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ qui capture alpha `liste', asi item std
+
+ mat a = r(Alpha)
+ mat at = a'
+
+ qui capture loevh `liste', pairwise
+ matrix e = r(loevHj)
+ matrix et = e'
+ matrix ns = r(nbHjkNS)
+ matrix nst = ns'
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',2] = at[`k',1]
+ matrix d[`j',3] = et[`k',1]
+ matrix d[`j',4] = nst[`k',1]
+
+ }
+ local `i++'
+ local y = `s'+1
+}
+
+/* coupure noms des items */
+/*
+local i = 1
+foreach s in `varlist' {
+ local len = length("`s'")
+ if `len' > 10 {
+ local c = substr("`s'",1,9)
+ local d = substr("`s'",-1,1)
+ local var`i' "`c'" "~" "`d'"
+ }
+ else local var`i' = "`s'"
+ *local v `v' `var`i''
+ local `++i'
+}
+
+
+local max = 3
+forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `max' local max = `len'
+}
+*/
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",8)
+ local `++i'
+}
+
+local dec = 10
+local col = `dec'
+local b : word count `lev'
+
+local i = 1
+local j = 1
+local y = 1
+di in blue _col(`dec') "{bf:Missing}" _c
+local col = `col'+11
+di in blue _col(`=`col'+2') "{bf:N}" _c
+
+local col = `col'+9
+di _col(`col') "{bf:Response categories}" _c
+local col = `dec'+18+8*`b'
+di _col(`col') "{bf:Alpha}" _c
+local col = `col'+9
+di _col(`col') "{bf:Loevinger}" _c
+local col = `col'+12
+di _col(`col') "{bf:Number of}"
+
+local col = `dec'-1
+di _col(`col') "{bf:data rate}" _c
+local col = `dec'+18
+foreach m in `lev' {
+ di _col(`=`col'+2') "`m'" _c
+ local col = `col'+8
+}
+local col = `dec'+17+8*`b'
+di as result _col(`col') "- item" _c
+local col = `col'+10
+di as result _col(`col') "Hj coeff" _c
+local col = `col'+12
+di as result _col(`col') "NS Hjk"
+
+
+
+local ch = `dec'+18+8*`b'+29
+di "{hline `ch'}"
+
+local i = 1
+foreach x in `varlist' {
+ local varo`i' = "`x'"
+ local `++i'
+}
+
+
+local y = 1
+foreach p in `partition' {
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ local col = `dec'
+ di "{bf:`var`z''}" _c
+ local t = d[`z',1]
+ local t : di %8.2f `t'
+ di _col(`col') "{text:`t'}" _c
+ qui count if missing(`varo`z'')
+ local m = r(N)
+ local N = _N-`m'
+ local N : di %4.0f `N'
+ local col = `col'+10
+ di _col(`col') "{text:`N'}" _c
+
+ local col = `col'+8
+ foreach m in `lev' {
+
+ local f = 0
+ qui levelsof `varo`z'', local(levels)
+ foreach l in `levels' {
+ if strpos("`levels'","`m'") == 0 {
+ local f = 1
+ }
+ }
+ /*if `f' == 1 {
+ di _col(`=`col'+2') "_" _c
+ }*/
+ *else {
+ qui count if round(`varo`z'') == `m'
+ local n = r(N)
+ qui count if `varo`z'' != .
+ local d = r(N)
+ local e = `n'/`d'
+ local e : di %4.2f `e'
+ if `e' != 0 di _col(`=`col'-1')"{text:`e'}" _c
+ else di _col(`=`col'-1')"{text: -}" _c
+
+ *}
+ local col = `col'+8
+ }
+ local col = `dec'+18+8*`b'
+ local a = d[`z',2]
+ local a : di %4.2f `a'
+ di _col(`=`col'+1') "{text:`a'}" _c
+ local h = d[`z',3]
+ local h : di %5.2f `h'
+ local col = `col'+10
+ di _col(`=`col'+3') "{text:`h'}" _c
+ local ns = d[`z',4]
+ local ns : di %1.0f `ns'
+ local col = `col'+12
+ di _col(`=`col'+7') "{text:`ns'}"
+
+
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di "{dup `ch':-}"
+}
+end
+
+*descitems iociociociociocicocio1-ioc37, part(4 4 7 3 3 4 7 5)
+*descitems ptgi1-peur16, part(4 4 7 3 3 4 7 5)
+*descitems x1-x30, part(5 5 5 5 5 4 1)
diff --git a/Modules/ado/personal/d/descscale.ado b/Modules/ado/personal/d/descscale.ado
new file mode 100644
index 0000000..a3f1829
--- /dev/null
+++ b/Modules/ado/personal/d/descscale.ado
@@ -0,0 +1,293 @@
+*! Version 1.2 29 August 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : descscale
+* Description of a scale and covariates
+* Release 1.1 : June 4, 2019
+*
+*
+* Historic :
+* Version 1 (April 12, 2019) [Jean-Benoit Hardouin]
+* Version 1.1 (June 4, 2019) [Jean-Benoit Hardouin]
+* Version 1.2 (August 29, 2019) [Jean-Benoit Hardouin] /*correction of bugs*/
+*
+* Jean-benoit Hardouin, PhD, Assistant Professor
+* Team of Methods in Patient Centered Outcomes and Health Research (INSERM U1246-SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2019 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 descscale , rclass
+version 8.2
+syntax varlist [if] [in] [,MIN(int 0) CONTinuous(varlist) CATegorical(varlist) All PARTition(numlist) Large MEAN MAXlevels(int 20)]
+
+preserve
+marksample touse,novarlist
+label variable `touse' "selection"
+
+tokenize `varlist'
+local nbitems: word count `varlist'
+if "`partition'"=="" {
+ local partition `nbitems'
+}
+local nbdim:word count `partition'
+forvalues i=1/`nbdim' {
+ local nbitemsdim`i': word `i' of `partition'
+}
+qui count if `touse'
+local N=r(N)
+local maxr=0
+forvalues i=1/`nbitems' {
+ qui levelsof ``i'' if `touse'
+ local r`i'=r(r)
+ qui su ``i'' if `touse'
+ local max`i'=r(max)
+ local mean`i'=r(mean)
+ qui count if ``i''!=0&``i''!=1&``i''!=2&``i''!=3&``i''!=4&``i''!=5&``i''!=6&``i''!=7&``i''!=8&``i''!=9&``i''!=10&``i''!=.
+ local ninc=r(N)
+ local ok`i'=1
+ if `r`i''>11&"`large'"=="" {
+ di in red "The number of answer categories to the items ``i'' is large (>11). Use the -large- option or correct the list of items."
+ local ok`i'=0
+ exit
+ }
+ if `ninc'>0 {
+ di in red "The variable ``i'' has incompatible values with an items (integers between 0 and 10)."
+ local ok`i'=0
+ exit
+ }
+ if `max`i''>`maxr' {
+ local maxr `max`i''
+ }
+}
+di "maxr=`maxr'"
+di
+di in green "Number of individuals : " as result `N'
+
+di
+di in green "Description of the items"
+local long=(`maxr'+1-`min')*8+40
+di in green "{hline `long'}"
+
+di in green "Items" _col(23) "Obs" _c
+local col=33
+forvalues j=`min'/`maxr' {
+ di _col(`col') "`j'" _c
+ local col=`col'+8
+}
+di _col(`col') "." _col(`=`col'+4') "Mean"
+di in green "{hline `long'}"
+
+local deb=1
+forvalues d=1/`nbdim' {
+ local loi`d'
+ *di "local fin=`deb'+`nbitemsdim`d''-1"
+ local fin=`deb'+`nbitemsdim`d''-1
+ forvalues i=`deb'/`fin' {
+ if `ok`i''==1 {
+ local loi`d' `loi`d'' ``i''
+ qui count if `touse'&``i''!=.
+ local k=abbrev("``i''",20)
+ di in green "`k'" _col(22) as result %4.0f `r(N)' _c
+ local col=28
+ forvalues j=`min'/`maxr' {
+ qui count if `touse'&``i''==`j'
+ local per=round(`r(N)'/`N'*100, 0.1)
+ di _col(`col') %5.1f `per' "%" _c
+ local col=`col'+8
+ }
+ qui count if `touse'&``i''==.
+ local per=round(`r(N)'/`N'*100,0.1)
+ di _col(`col') %5.1f `per' "%" _col(`=`col'+9') %4.2f `mean`i''
+ }
+ }
+ if `d'!=`nbdim' {
+ di in green "{dup `long':-}"
+ }
+ local deb=`fin'+1
+}
+di in green "{hline `long'}"
+
+di
+di in green "Description of the scores"
+local long2=72
+di in green "{hline `long2'}"
+di in green "Scores" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+di in green "{hline `long2'}"
+
+forvalues d=1/`nbdim' {
+ tempname score`d'
+ genscore `loi`d'' if `touse', score(`score`d'') `mean' `standardized'
+ qui su `score`d'' if `touse'
+ di in green "score`d'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+}
+di in green "{hline `long2'}"
+
+
+if "`continuous'"!="" {
+ local continuous2
+ foreach i of varlist `continuous' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local continuous2 `continuous2' `i'
+ }
+ }
+ local continuous `continuous2'
+}
+if "`categorical'"!="" {
+ local categorical2
+ foreach i of varlist `categorical' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local categorical2 `categorical2' `i'
+ }
+ }
+ local categorical `categorical2'
+}
+
+if "`all'"!="" {
+ *local continuous
+ *local categorial
+ foreach i of varlist * {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ if `r'>7&`candidate'==1 {
+ local continuous `continuous' `i'
+ }
+ else {
+ local categorical `categorical' `i'
+ }
+ }
+}
+
+*di "CONTINUOUS : `continuous'"
+*di "CATEGORICAL : `categorical'"
+
+if "`continuous'"!="" {
+ di
+ di "Descriptive analysis of continuous covariates"
+ local long2=72
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+ di in green "{hline `long2'}"
+ foreach i of varlist `continuous' {
+ qui su `i' if `touse'
+ local k=abbrev("`i'",18)
+ *di in green "`k'" _c
+ di in green "`k'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+ }
+ di in green "{hline `long2'}"
+}
+if "`categorical'"!="" {
+ di
+ *set trace on
+ di "Descriptive analysis of categorical covariates"
+ local long2=55
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(25) "Levels" _col(37) "Freq." _col(49) "Percent"
+ di in green "{hline `long2'}"
+ local nbc: word count `categorical'
+ local m=1
+ local nonret
+ foreach i of varlist `categorical' {
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ qui levelsof `i'
+ local lev "`r(levels)'"
+ local nblev=r(r)
+ if (`maxlevels'>=`nblev') {
+ local k=abbrev("`i'",20)
+ di in green "`k'" _c
+ if "`type'"=="str" {
+ foreach j in `lev' {
+ qui count if `touse'&`i'=="`j'"
+ local k=abbrev("`j'",10)
+ di _col(21) %10s in green "`k'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==""
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ else {
+ foreach j in `lev' {
+ qui count if `touse'&`i'==`j'
+ di _col(21) %10s in green "`j'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==.
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ else {
+ di in green "{dup `long2':-}"
+ }
+ }
+ else {
+ local nonret `nonret' `i'
+ *di "local nonret `nonret' `i'"
+ *di "non retenu `i'"
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ }
+ local ++m
+ }
+ if "`nonret'"!="" {
+ di in green "Not described variables (too more levels) : " as result "`nonret'"
+ }
+}
+end
diff --git a/Modules/ado/personal/d/descscalev1.1.ado b/Modules/ado/personal/d/descscalev1.1.ado
new file mode 100644
index 0000000..6508346
--- /dev/null
+++ b/Modules/ado/personal/d/descscalev1.1.ado
@@ -0,0 +1,290 @@
+*! Version 1.1 4 June 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : descscale
+* Description of a scale and covariates
+* Release 1.1 : June 4, 2019
+*
+*
+* Historic :
+* Version 1 (April 12, 2019) [Jean-Benoit Hardouin]
+* Version 1.1 (June 4, 2019) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, PhD, Assistant Professor
+* Team of Methods in Patient Centered Outcomes and Health Research (INSERM U1246-SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2019 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 descscale , rclass
+version 8.2
+syntax varlist [if] [in] [,MIN(int 0) CONTinuous(varlist) CATegorical(varlist) All PARTition(numlist) Large MEAN MAXlevels(int 20)]
+
+preserve
+marksample touse,novarlist
+label variable `touse' "selection"
+
+tokenize `varlist'
+local nbitems: word count `varlist'
+if "`partition'"=="" {
+ local partition `nbitems'
+}
+local nbdim:word count `partition'
+forvalues i=1/`nbdim' {
+ local nbitemsdim`i': word `i' of `partition'
+}
+qui count if `touse'
+local N=r(N)
+local maxr=0
+forvalues i=1/`nbitems' {
+ qui levelsof ``i'' if `touse'
+ local r`i'=r(r)
+ qui su ``i'' if `touse'
+ local max`i'=r(max)
+ local mean`i'=r(mean)
+ qui count if ``i''!=0&``i''!=1&``i''!=2&``i''!=3&``i''!=4&``i''!=5&``i''!=6&``i''!=7&``i''!=8&``i''!=9&``i''!=10&``i''!=.
+ local ninc=r(N)
+ local ok`i'=1
+ if `r`i''>11&"`large'"=="" {
+ di in red "The number of answer categories to the items ``i'' is large (>11). Use the -large- option or correct the list of items."
+ local ok`i'=0
+ exit
+ }
+ if `ninc'>0 {
+ di in red "The variable ``i'' has incompatible values with an items (integers between 0 and 10)."
+ local ok`i'=0
+ exit
+ }
+ if `r`i''>`maxr' {
+ local maxr `r`i''
+ }
+}
+*di "maxr=`maxr'"
+di
+di in green "Number of individuals : " as result `N'
+
+di
+di in green "Decription of the items"
+local long=(`maxr'+1-`min')*8+40
+di in green "{hline `long'}"
+
+di in green "Items" _col(23) "Obs" _c
+local col=33
+forvalues j=`min'/`maxr' {
+ di _col(`col') "`j'" _c
+ local col=`col'+8
+}
+di _col(`col') "." _col(`=`col'+4') "Mean"
+di in green "{hline `long'}"
+
+local deb=1
+forvalues d=1/`nbdim' {
+ local loi`d'
+ *di "local fin=`deb'+`nbitemsdim`d''-1"
+ local fin=`deb'+`nbitemsdim`d''-1
+ forvalues i=`deb'/`fin' {
+ if `ok`i''==1 {
+ local loi`d' `loi`d'' ``i''
+ qui count if `touse'&``i''!=.
+ local k=abbrev("``i''",20)
+ di in green "`k'" _col(22) as result %4.0f `r(N)' _c
+ local col=28
+ forvalues j=`min'/`maxr' {
+ qui count if `touse'&``i''==`j'
+ local per=round(`r(N)'/`N'*100, 0.1)
+ di _col(`col') %5.1f `per' "%" _c
+ local col=`col'+8
+ }
+ qui count if `touse'&``i''==.
+ local per=round(`r(N)'/`N'*100,0.1)
+ di _col(`col') %5.1f `per' "%" _col(`=`col'+9') %4.2f `mean`i''
+ }
+ }
+ if `d'!=`nbdim' {
+ di in green "{dup `long':-}"
+ }
+ local deb=`fin'+1
+}
+di in green "{hline `long'}"
+
+di
+di in green "Decription of the scores"
+local long2=72
+di in green "{hline `long2'}"
+di in green "Scores" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+di in green "{hline `long2'}"
+
+forvalues d=1/`nbdim' {
+ tempname score`d'
+ genscore `loi`d'' if `touse', score(`score`d'') `mean' `standardized'
+ qui su `score`d'' if `touse'
+ di in green "score`d'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+}
+di in green "{hline `long2'}"
+
+
+if "`continuous'"!=""|"`categorical'"!="" {
+ local continuous2
+ foreach i of varlist `continuous' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local continuous2 `continuous2' `i'
+ }
+ }
+ local continuous `continuous2'
+ local categorical2
+ foreach i of varlist `categorical' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local categorical2 `categorical2' `i'
+ }
+ }
+ local categorical `categorical2'
+}
+
+if "`all'"!="" {
+ *local continuous
+ *local categorial
+ foreach i of varlist * {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ if `r'>7&`candidate'==1 {
+ local continuous `continuous' `i'
+ }
+ else {
+ local categorical `categorical' `i'
+ }
+ }
+}
+
+*di "CONTINUOUS : `continuous'"
+*di "CATEGORICAL : `categorical'"
+
+if "`continuous'"!="" {
+ di
+ di "Descriptive analysis of continuous covariates"
+ local long2=72
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+ di in green "{hline `long2'}"
+ foreach i of varlist `continuous' {
+ qui su `i' if `touse'
+ local k=abbrev("`i'",18)
+ *di in green "`k'" _c
+ di in green "`k'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+ }
+ di in green "{hline `long2'}"
+}
+if "`categorical'"!="" {
+ di
+ *set trace on
+ di "Descriptive analysis of categorical covariates"
+ local long2=55
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(25) "Levels" _col(37) "Freq." _col(49) "Percent"
+ di in green "{hline `long2'}"
+ local nbc: word count `categorical'
+ local m=1
+ local nonret
+ foreach i of varlist `categorical' {
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ qui levelsof `i'
+ local lev "`r(levels)'"
+ local nblev=r(r)
+ if (`maxlevels'>=`nblev') {
+ local k=abbrev("`i'",20)
+ di in green "`k'" _c
+ if "`type'"=="str" {
+ foreach j in `lev' {
+ qui count if `touse'&`i'=="`j'"
+ local k=abbrev("`j'",10)
+ di _col(21) %10s in green "`k'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==""
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ else {
+ foreach j in `lev' {
+ qui count if `touse'&`i'==`j'
+ di _col(21) %10s in green "`j'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==.
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ else {
+ di in green "{dup `long2':-}"
+ }
+ }
+ else {
+ local nonret `nonret' `i'
+ *di "local nonret `nonret' `i'"
+ *di "non retenu `i'"
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ }
+ local ++m
+ }
+ if "`nonret'"!="" {
+ di in green "Not described variables (too more levels) : " as result "`nonret'"
+ }
+}
+end
diff --git a/Modules/ado/personal/d/descscalev1.ado b/Modules/ado/personal/d/descscalev1.ado
new file mode 100644
index 0000000..8c842a1
--- /dev/null
+++ b/Modules/ado/personal/d/descscalev1.ado
@@ -0,0 +1,279 @@
+*! Version 1 11 April 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : descscale
+* Description of a scale and covariates
+* Release 1 : April 12, 2019
+*
+*
+* Historic :
+* Version 1 (April 12, 2019) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, PhD, Assistant Professor
+* Team of Methods in Patient Centered Outcomes and Health Research (INSERM U1246-SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2019 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 descscale , rclass
+version 8.2
+syntax varlist [if] [in] [,MIN(int 0) CONTinuous(varlist) CATegorical(varlist) All PARTition(numlist) Large MEAN MAXlevels(int 20)]
+
+preserve
+marksample touse,novarlist
+label variable `touse' "selection"
+
+tokenize `varlist'
+local nbitems: word count `varlist'
+if "`partition'"=="" {
+ local partition `nbitems'
+}
+local nbdim:word count `partition'
+forvalues i=1/`nbdim' {
+ local nbitemsdim`i': word `i' of `partition'
+}
+qui count if `touse'
+local N=r(N)
+local maxr=0
+forvalues i=1/`nbitems' {
+ qui levelsof ``i'' if `touse'
+ local r`i'=r(r)
+ qui su ``i'' if `touse'
+ local max`i'=r(max)
+ local mean`i'=r(mean)
+ if `r`i''>11&"`large'"=="" {
+ di in red "The number of answer categories to the items is large (>11). Use the -large- option or correct the list of items."
+ exit
+ }
+ if `r`i''>`maxr' {
+ local maxr `r`i''
+ }
+}
+*di "maxr=`maxr'"
+di
+di in green "Number of individuals : " as result `N'
+
+di
+di in green "Decription of the items"
+local long=(`maxr'+1-`min')*8+40
+di in green "{hline `long'}"
+
+di in green "Items" _col(23) "Obs" _c
+local col=33
+forvalues j=`min'/`maxr' {
+ di _col(`col') "`j'" _c
+ local col=`col'+8
+}
+di _col(`col') "." _col(`=`col'+4') "Mean"
+di in green "{hline `long'}"
+
+local deb=1
+forvalues d=1/`nbdim' {
+ local loi`d'
+ *di "local fin=`deb'+`nbitemsdim`d''-1"
+ local fin=`deb'+`nbitemsdim`d''-1
+ forvalues i=`deb'/`fin' {
+ local loi`d' `loi`d'' ``i''
+ qui count if `touse'&``i''!=.
+ local k=abbrev("``i''",20)
+ di in green "`k'" _c
+ di in green "`k'" _col(22) as result %4.0f `r(N)' _c
+ local col=28
+ forvalues j=`min'/`maxr' {
+ qui count if `touse'&``i''==`j'
+ local per=round(`r(N)'/`N'*100, 0.1)
+ di _col(`col') %5.1f `per' "%" _c
+ local col=`col'+8
+ }
+ qui count if `touse'&``i''==.
+ local per=round(`r(N)'/`N'*100,0.1)
+ di _col(`col') %5.1f `per' "%" _col(`=`col'+9') %4.2f `mean`i''
+ }
+ if `d'!=`nbdim' {
+ di in green "{dup `long':-}"
+ }
+ local deb=`fin'+1
+}
+di in green "{hline `long'}"
+
+di
+di in green "Decription of the scores"
+local long2=72
+di in green "{hline `long2'}"
+di in green "Scores" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+di in green "{hline `long2'}"
+
+forvalues d=1/`nbdim' {
+ tempname score`d'
+ genscore `loi`d'' if `touse', score(`score`d'') `mean' `standardized'
+ qui su `score`d'' if `touse'
+ di in green "score`d'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+}
+di in green "{hline `long2'}"
+
+
+if "`continuous'"!=""|"`categorical'"!="" {
+ local continuous2
+ foreach i of varlist `continuous' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local continuous2 `continuous2' `i'
+ }
+ }
+ local continuous `continuous2'
+ local categorical2
+ foreach i of varlist `categorical' {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ if `candidate'==1 {
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ local categorical2 `categorical2' `i'
+ }
+ }
+ local categorical `categorical2'
+}
+
+if "`all'"!="" {
+ *local continuous
+ *local categorial
+ foreach i of varlist * {
+ local candidate=1
+ forvalues j=1/`nbitems' {
+ if "`i'"=="``j''" {
+ local candidate=0
+ }
+ }
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ if "`type'"=="str" {
+ local candidate=0
+ }
+ qui levelsof `i' if `touse'
+ local r=r(r)
+ if `r'>7&`candidate'==1 {
+ local continuous `continuous' `i'
+ }
+ else {
+ local categorical `categorical' `i'
+ }
+ }
+}
+
+*di "CONTINUOUS : `continuous'"
+*di "CATEGORICAL : `categorical'"
+
+if "`continuous'"!="" {
+ di
+ di "Descriptive analysis of continuous covariates"
+ local long2=72
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(22) "Obs" _col(33) "Mean" _col(40) "Std. Dev." _col(58) "Min" _col(70) "Max"
+ di in green "{hline `long2'}"
+ foreach i of varlist `continuous' {
+ qui su `i' if `touse'
+ local k=abbrev("`i'",18)
+ *di in green "`k'" _c
+ di in green "`k'" _col(20) as result %5.0f `r(N)' _col(30) %7.2f `r(mean)' _col(42) %7.2f `r(sd)' _col(54) %7.2f `r(min)' _col(66) %7.2f `r(max)'
+ }
+ di in green "{hline `long2'}"
+}
+if "`categorical'"!="" {
+ di
+ *set trace on
+ di "Descriptive analysis of continuous covariates"
+ local long2=55
+ di in green "{hline `long2'}"
+ di in green "Variables" _col(25) "Levels" _col(37) "Freq." _col(49) "Percent"
+ di in green "{hline `long2'}"
+ local nbc: word count `categorical'
+ local m=1
+ local nonret
+ foreach i of varlist `categorical' {
+ local type : type `i'
+ local type=substr("`type'",1,3)
+ qui levelsof `i'
+ local lev "`r(levels)'"
+ local nblev=r(r)
+ if (`maxlevels'>=`nblev') {
+ local k=abbrev("`i'",20)
+ di in green "`k'" _c
+ if "`type'"=="str" {
+ foreach j in `lev' {
+ qui count if `touse'&`i'=="`j'"
+ local k=abbrev("`j'",10)
+ di _col(21) %10s in green "`k'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==""
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ else {
+ foreach j in `lev' {
+ qui count if `touse'&`i'==`j'
+ di _col(21) %10s in green "`j'" as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ qui count if `touse'&`i'==.
+ if `r(N)'!=0 {
+ di as result %5.0f _col(37) `r(N)' %6.2f _col(49) `=`r(N)'/`N'*100' "%"
+ }
+ }
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ else {
+ di in green "{dup `long2':-}"
+ }
+ }
+ else {
+ local nonret `nonret' `i'
+ *di "local nonret `nonret' `i'"
+ *di "non retenu `i'"
+ if `m'==`nbc' {
+ di in green "{hline `long2'}"
+ }
+ }
+ local ++m
+ }
+ if "`nonret'"!="" {
+ di in green "Not described variables (too more levels) : " as result "`nonret'"
+ }
+}
+end
diff --git a/Modules/ado/personal/d/detect.ado b/Modules/ado/personal/d/detect.ado
new file mode 100644
index 0000000..6162a4a
--- /dev/null
+++ b/Modules/ado/personal/d/detect.ado
@@ -0,0 +1,302 @@
+************************************************************************************************************
+* DETECT: detect, Iss and R indexes
+* Version 3.1: May 13, 2004
+*
+* Historic
+* Version 1 (2003-06-20): Jean-Benoit Hardouin
+* Version 2 (2004-01-18): Jean-Benoit Hardouin
+* Version 3 (2004-01-26): Jean-Benoit Hardouin
+* Version 3.1 (2004-05-13): Jean-Benoit Hardouin
+* Version 4 (2009-11-24): Jean-Benoit Hardouin /*corrections*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003, 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 detect , rclass
+version 7.0
+syntax varlist(min=2 numeric), PARTition(numlist integer >0) [noSCOres noRESTscores]
+
+local nbitemstest=0
+tokenize `partition'
+local Q:word count `partition'
+local firstitem=0
+local dim0=1
+forvalues i=1/`Q' {
+ local dim`i'=``i''
+ local firstitem`i'=`firstitem`=`i'-1''+`dim`=`i'-1''
+ local nbitemstest=`nbitemstest'+`dim`i''
+ tempvar score`i'
+ qui gen `score`i''=0
+ forvalues j=`firstitem`i''/`=`firstitem`i''+`dim`i''-1' {
+ local item`j': word `j' of `varlist'
+ qui replace `score`i''=`score`i''+`item`j''
+ }
+}
+
+
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+if `nbitems'!=`nbitemstest' {
+ di in red "The sum of the numbers of items in all the dimensions is different of the total number of items precised in varlist"
+exit
+}
+
+tempname Corrscores Corrrestscores
+
+matrix define `Corrscores'=J(`nbitems',`Q',0)
+matrix define `Corrrestscores'=J(`nbitems',`Q',0)
+
+
+forvalues i=1/`nbitems' {
+ forvalues j=1/`Q' {
+ tempvar restscore`i's`j'
+ qui gen `restscore`i's`j''=`score`j''-``i''
+ qui corr ``i'' `score`j''
+ local corr`i's`j'=r(rho)
+ qui corr ``i'' `restscore`i's`j''
+ local corr`i'rs`j'=r(rho)
+ matrix `Corrscores'[`i',`j']=`corr`i's`j''
+ matrix `Corrrestscores'[`i',`j']=`corr`i'rs`j''
+ }
+}
+
+
+qui count
+local nbind=r(N)
+
+tempvar score
+qui gen `score'=0
+forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i''
+}
+
+forvalues i=1/`nbitems' {
+ local tmp=`i'+1
+ forvalues j=`tmp'/`nbitems' {
+ tempvar restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ }
+}
+
+forvalues k=0/`nbitems'{
+ tempname Tcov`k'
+ qui count if `score'==`k'
+ local n`k'=r(N)
+ if `n`k''>1 {
+ qui matrix accum `Tcov`k''=`varlist' if `score'==`k',nocons dev
+ }
+ else {
+ matrix `Tcov`k''=J(`nbitems',`nbitems',0)
+ }
+ if `n`k''!=0 {
+ matrix `Tcov`k''=`Tcov`k''/`n`k''
+ }
+}
+
+
+forvalues i=1/`nbitems'{
+ local tmp=`i'+1
+ forvalues j=`tmp'/`nbitems' {
+ local tmp=`nbitems'-2
+ forvalues k=0/`tmp' {
+ tempname Rcovi`i'j`j'k`k'
+ qui count if `restscorei`i'j`j''==`k'
+ local ni`i'j`j'k`k'=r(N)
+ if `ni`i'j`j'k`k''>1 {
+ qui matrix accum `Rcovi`i'j`j'k`k''=`varlist' if `restscorei`i'j`j''==`k',nocons dev
+ }
+ else {
+ matrix `Rcovi`i'j`j'k`k''=J(`nbitems',`nbitems',0)
+ }
+ if `ni`i'j`j'k`k''!=0 {
+ matrix `Rcovi`i'j`j'k`k''=`Rcovi`i'j`j'k`k''/`ni`i'j`j'k`k''
+ }
+ }
+ }
+}
+
+
+tempname delta
+matrix `delta'=J(`nbitems',`nbitems',-1)
+
+local debut=1
+local fin=0
+forvalues i=1/`Q' {
+ local fin=`fin'+`dim`i''
+ forvalues j=`debut'/`fin' {
+ forvalues k=`debut'/`fin' {
+ matrix `delta'[`j',`k']=1
+ }
+ }
+ local debut=`debut'+`dim`i''
+}
+
+tempname Tcov Rcov Covfin Issm Abscov
+
+matrix `Tcov'=J(`nbitems',`nbitems',0)
+matrix `Rcov'=J(`nbitems',`nbitems',0)
+forvalues k=0/`nbitems' {
+ matrix `Tcov'=`Tcov'+`Tcov`k''*`n`k''
+}
+forvalues i=1/`nbitems'{
+ local tmp=`i'+1
+ forvalues j=`tmp'/`nbitems' {
+ local tmp=`nbitems'-2
+ forvalues k=0/`tmp' {
+ matrix `Rcov'[`i',`j']=`Rcov'[`i',`j']+`Rcovi`i'j`j'k`k''[`i',`j']*`ni`i'j`j'k`k''
+ matrix `Rcov'[`j',`i']=`Rcov'[`i',`j']
+ }
+ }
+}
+
+
+matrix `Covfin'=J(`nbitems',`nbitems',0)
+matrix `Issm'=J(`nbitems',`nbitems',0)
+matrix `Abscov'=J(`nbitems',`nbitems',0)
+forvalues i=1/`nbitems' {
+ forvalues j=1/`nbitems' {
+ matrix `Covfin'[`i',`j']=(`Tcov'[`i',`j']+`Rcov'[`i',`j'])/2*`delta'[`i',`j']
+ matrix `Issm'[`i',`j']=sign(`Tcov'[`i',`j']+`Rcov'[`i',`j'])*`delta'[`i',`j']
+ matrix `Abscov'[`i',`j']=abs(`Tcov'[`i',`j']+`Rcov'[`i',`j'])/2
+ }
+}
+
+local somme=0
+local Iss=0
+local R=0
+forvalues i=1/`nbitems' {
+ local tmp=`i'+1
+ forvalues j=`tmp'/`nbitems' {
+ local somme=`somme'+`Covfin'[`i',`j']
+ local Iss=`Iss'+`Issm'[`i',`j']
+ local R=`R'+`Abscov'[`i',`j']
+ }
+}
+local DETECT=`somme'/(`nbind'*`nbitems'*(`nbitems'-1))
+local DETECT=`somme'/(`nbitems'*(`nbitems'-1))
+local Iss=`Iss'*2/(`nbitems'*(`nbitems'-1))
+*local R=`DETECT'/(`R'/(`nbind'*`nbitems'*(`nbitems'-1)))
+local R=`DETECT'/(`R'/(`nbitems'*(`nbitems'-1)))
+
+
+di
+di in green _col(20) "DETECT : " as result %5.4f `DETECT'
+di in green _col(23) "Iss : " as result %5.4f `Iss'
+di in green _col(25) "R : " as result %5.4f `R'
+
+di
+
+if "`scores'"=="" {
+ di _col(5) in green "Correlations Items-Scores"
+ di in green _col(5) "{hline 25}"
+ di
+ di in green _col(5) "Items" _continue
+ local col=10
+ forvalues q=1/`Q' {
+ local col=`col'+10
+ di in green _col(`col') "dim `q'" _continue
+ }
+ di
+ local length=`Q'*10+10
+ di in green _col(5) "{hline `length'}"
+ forvalues i=1/`nbitems' {
+ forvalues q=2/`Q' {
+ if `i'==`firstitem`q'' {
+ di _col(5) in green _dup(`length') "-"
+ }
+ }
+ di in green _col(5) "``i''" _continue
+ local col=5
+ forvalues q=1/`Q' {
+ local col=`col'+10
+ di in yellow _col(`col') %10.4f `corr`i's`q'' _continue
+ }
+ di
+ }
+ di in green _col(5) "{hline `length'}"
+ di
+}
+
+
+if "`restscore'"=="" {
+ di _col(5) in green "Correlations Items-Rest-Scores"
+ di in green _col(5) "{hline 30}"
+ di
+ di in green _col(5) "Items" _continue
+ local col=10
+ forvalues q=1/`Q' {
+ local col=`col'+10
+ di in green _col(`col') "dim `q'" _continue
+ }
+ di
+ local length=`Q'*10+10
+ di in green _col(5) "{hline `length'}"
+ forvalues i=1/`nbitems' {
+ forvalues q=2/`Q' {
+ if `i'==`firstitem`q'' {
+ di _col(5) in green _dup(`length') "-"
+ }
+ }
+ di in green _col(5) "``i''" _continue
+ local col=5
+ forvalues q=1/`Q' {
+ local col=`col'+10
+ di in yellow _col(`col') %10.4f `corr`i'rs`q'' _continue
+ }
+ di
+ }
+ di in green _col(5) "{hline `length'}"
+ di
+}
+
+local namesdim
+forvalues q=1/`Q' {
+ local namesdim "`namesdim' dim`q'"
+}
+
+matrix rownames `Tcov'=`varlist'
+matrix rownames `Rcov'= `varlist'
+matrix rownames `Covfin'= `varlist'
+matrix rownames `Corrscores'= `varlist'
+matrix rownames `Corrrestscores'= `varlist'
+matrix colnames `Tcov'= `varlist'
+matrix colnames `Rcov' =`varlist'
+matrix colnames `Covfin'= `varlist'
+matrix colnames `Corrscores'= `namesdim'
+matrix colnames `Corrrestscores'= `namesdim'
+
+
+return scalar DETECT=`DETECT'
+return scalar Iss=`Iss'
+return scalar R=`R'
+return matrix Tcov `Tcov'
+return matrix Rcov `Rcov'
+return matrix Covfin `Covfin'
+return matrix Corrscores `Corrscores'
+return matrix Corrrestscores `Corrrestscores'
+
+
+end
diff --git a/Modules/ado/personal/d/detect.hlp b/Modules/ado/personal/d/detect.hlp
new file mode 100644
index 0000000..b94f0df
--- /dev/null
+++ b/Modules/ado/personal/d/detect.hlp
@@ -0,0 +1,48 @@
+{smcl}
+{* 26jan2004}{...}
+{hline}
+help for {hi:detect}
+{hline}
+
+{title:DETECT Index}
+
+{p 8 14 2}{cmd:detect} {it:varlist} {cmd:,} {cmdab:part:ition}({it:numlist}) [{cmdab:nosco:res} {cmdab:norest:scores}]
+
+
+{p 4 4 2}{it:varlist} is a list of two existing dichotomous variables (items) or more. The first items of this list compose the first dimension, the following items define the second dimension, as so on.
+
+{p 4 4 2}{cmd:partition} permit to define the number of items in each dimension. The user must precise in the {it:numlist} the number of items in each dimension.
+
+{Options}
+
+{p 4 4 2}{cmd:noscores} permit to remove the table of the correlations between the items and the scores
+
+{p 4 4 2}{cmd:norestscores} permit to remove the table of the correlations between the items and the rest-scores
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:detect} permit to compute the DETECT index (Dimensionality Evaluation to Enumerate Contributing Traits), as the Iss (Approximate Simple Structure Index) and the R indexes defined by Zhang and Stout (1999).
+
+
+{title:Remarks}
+
+{p 4 4 2}For detailed information on the DETECT, Iss and R indexes, see Zhang and Stout (1999).
+
+{p 4 4 2}{cmd:detect} don't permit the use of polytomous items.
+
+{title:Example}
+
+ {cmd:. detect item1 item2 item3 item4 , partition(2 2) nosco norest}
+
+ {cmd:. detect item1 item2 item3 item4 item 5 item6 item7 , partition(3 2 2)}
+
+
+{title:References}
+
+{p 4 4 2}Zhang J. and Stout W., The theorical DETECT index of dimensionality and its application to approximate simple structure, {it: Psychometrika}, vol.64(2), 1999, pp. 213-249.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@neuf.fr":jean-benoit.hardouin@neuf.fr} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/d/detect2.ado b/Modules/ado/personal/d/detect2.ado
new file mode 100644
index 0000000..d2510d4
--- /dev/null
+++ b/Modules/ado/personal/d/detect2.ado
@@ -0,0 +1,68 @@
+************************************************************************************************************
+* based on the command "detect" by Jean-Benoit Hardouin
+************************************************************************************************************
+program define detect2 , rclass
+version 7.0
+syntax varlist(min=2 numeric), PARTition(numlist integer >0) [noSCOres noRESTscores]
+
+local nbitemstest=0
+tokenize `partition'
+local Q:word count `partition'
+local firstitem=0
+local dim0=1
+forvalues i=1/`Q' {
+ local dim`i'=``i''
+ local firstitem`i'=`firstitem`=`i'-1''+`dim`=`i'-1''
+ local nbitemstest=`nbitemstest'+`dim`i''
+ tempvar score`i'
+ qui gen `score`i''=0
+ forvalues j=`firstitem`i''/`=`firstitem`i''+`dim`i''-1' {
+ local item`j': word `j' of `varlist'
+ qui replace `score`i''=`score`i''+`item`j''
+ }
+}
+
+
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+if `nbitems'!=`nbitemstest' {
+ di in red "The sum of the numbers of items in all the dimensions is different of the total number of items precised in varlist"
+exit
+}
+
+
+tempname Corrscores Corrrestscores
+
+matrix define `Corrscores'=J(`nbitems',`Q',0)
+matrix define `Corrrestscores'=J(`nbitems',`Q',0)
+
+
+forvalues i=1/`nbitems' {
+ forvalues j=1/`Q' {
+ tempvar restscore`i's`j'
+ qui gen `restscore`i's`j''=`score`j''-``i''
+ qui corr ``i'' `score`j''
+ local corr`i's`j'=r(rho)
+ qui corr ``i'' `restscore`i's`j''
+ local corr`i'rs`j'=r(rho)
+ matrix `Corrscores'[`i',`j']=`corr`i's`j''
+ matrix `Corrrestscores'[`i',`j']=`corr`i'rs`j''
+ }
+}
+
+
+
+local namesdim
+forvalues q=1/`Q' {
+ local namesdim "`namesdim' dim`q'"
+}
+
+matrix colnames `Corrscores'= `namesdim'
+matrix colnames `Corrrestscores'= `namesdim'
+return matrix Corrscores `Corrscores'
+return matrix Corrrestscores `Corrrestscores'
+
+
+end
diff --git a/Modules/ado/personal/d/dropmissing.ado b/Modules/ado/personal/d/dropmissing.ado
new file mode 100644
index 0000000..15f3a77
--- /dev/null
+++ b/Modules/ado/personal/d/dropmissing.ado
@@ -0,0 +1,23 @@
+program define dropmissing
+syntax varlist [, missing(string) delete]
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+if "`missing'"=="" {
+ local missing="."
+}
+
+local nbmissing:word count `missing'
+
+forvalues i=1/`nbitems' {
+ forvalues j=1/`nbmissing' {
+ local miss:word `j' of `missing'
+ if "`delete'"!="" {
+ drop if ``i''==`miss'
+ }
+ else {
+ replace ``i'=. if ``i''==`miss'
+ }
+ }
+}
+end
diff --git a/Modules/ado/personal/e/estpop.ado b/Modules/ado/personal/e/estpop.ado
new file mode 100644
index 0000000..9cf9453
--- /dev/null
+++ b/Modules/ado/personal/e/estpop.ado
@@ -0,0 +1,344 @@
+************************************************************************************************************
+* Estpop : Estimation de la population d'une commune, d'un canton, d'un département de la région Centre
+* (ou de la région Centre toute entière)
+*
+* Version 2.1: 7 décembre 2004
+* Version 2: 2 décembre 2004
+* Version 1.5: 2 décembre 2004
+* Version 1.4: 21 octobre 2004
+* Version 1.3: 16 aout 2004
+* Version 1.2: 20 juillet 2004
+* Version 1.1: 16 juillet 2004
+* Version 1: 16 juillet 2004
+*
+* Jean-benoit Hardouin, Observatoire Régional de la Santé du Centre - Orléans - France
+* jean-benoit.hardouin@neuf.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 estpop,rclass
+version 7.0
+syntax , [annee(int 1999) codegeo(int 1) sexe(int 0) quinq juillet]
+capture su *
+if _rc==0 {
+ tempfile saveestpop
+ qui save `saveestpop',replace
+}
+preserve
+
+if `annee'>=1900&`annee'<2000 {
+ local annee=`annee'-1900
+}
+local sannee=1900+`annee'
+if `sannee'<1982 {
+ local `sannee'=`sannee'+100
+}
+
+
+if `annee'<82|`annee'>99 {
+ di in red "Vous devez indiquer une annee entre 1982 et 1999 (ou entre 82 et 99)"
+ exit
+}
+
+if `sexe'==0 {
+ local sexel hf
+}
+else if `sexe'==1 {
+ local sexel h
+}
+else if `sexe'==2 {
+ local sexel f
+}
+else {
+ di in red "Vous devez indiquer un sexe parmi 0 (2 sexes confondus), 1 (hommes) et 2 (femmes)"
+ exit
+}
+
+if `codegeo'>100 {/*SI COMMUNE OU ZE OU CANTON */
+ use "C:\ado\personal\files\rp`sexel'829099.dta", clear
+ sort codecom
+ merge codecom using "C:\ado\personal\files\nais8002.dta"
+
+ if `sexe'!=0 {
+ foreach i of numlist 80/99 00/02 {
+ if `sexe'==1 {
+ local ratio=1.05/2.05
+ }
+ else if `sexe'==2 {
+ local ratio=1/2.05
+ }
+ if `i'<10 {
+ qui replace naiss0`i'=naiss0`i'*`ratio'
+ }
+ else if `i'>=10 {
+ qui replace naiss`i'=naiss`i'*`ratio'
+ }
+ }
+ }
+
+ tempvar flag
+ gen `flag'=0
+
+
+ if `codegeo'==0 {
+ qui replace `flag'=1 if codecom==0
+ }
+ if `codegeo'==1 {
+ qui replace `flag'=1 if codecom!=0
+ }
+ if `codegeo'<100 {
+ qui replace `flag'=1 if dep==`codegeo'
+ }
+ if `codegeo'<1000&`codegeo'>100 {
+ qui replace `flag'=1 if arr==`codegeo'
+ }
+ if `codegeo'<10000&`codegeo'>1000&int(`codegeo'/100)!=24 {
+ qui replace `flag'=1 if pct==`codegeo'
+ }
+ if int(`codegeo'/100)==24 {
+ qui replace `flag'=1 if ze94==`codegeo'
+ }
+ if `codegeo'<100000&`codegeo'>10000 {
+ qui replace `flag'=1 if codecom==`codegeo'
+ }
+ qui keep if `flag'==1
+
+
+ if `annee'==82|`annee'==90|`annee'==99 {
+ forvalues i=1/95 {
+ qui su rp`annee'`sexel'`i'
+ local popr`i'=r(sum)
+ return scalar popr`i'=`popr`i''
+ }
+ }
+ if (`annee'>90&`annee'<99)|(`annee'>82&`annee'<90) {
+ if `annee'>90&`annee'<99 {
+ local first=`annee'-90
+ local last=98-`annee'
+ local anc=90
+ local suiv=99
+ local nbans=9
+ }
+ if `annee'>82&`annee'<90 {
+ local first=`annee'-82
+ local last=89-`annee'
+ local anc=82
+ local suiv=90
+ local nbans=8
+ }
+
+ forvalues i=1/`first' {
+ local tmp=`suiv'-`annee'+`i'
+ local tmp2=`suiv'-`annee'+1
+ tempvar rp`annee'`sexel'`i'
+ qui gen `rp`annee'`sexel'`i''=naiss`=`annee'-`i''+`i'*(rp`suiv'`sexel'`tmp'-naiss`=`annee'-`i'')/`tmp'
+ qui su `rp`annee'`sexel'`i''
+ local popr`i'=r(sum)
+ return scalar popr`i'=`popr`i''
+ }
+ local rp`annee'`sexel'94 rp`annee'`sexel'95
+ forvalues i=`=`anc'+1'/`=`suiv'-1' {
+ tempname rp`i'`sexel'94 rp`i'`sexel'95
+ qui gen `rp`i'`sexel'94'=rp`anc'`sexel'94+(rp`suiv'`sexel'94-rp`anc'`sexel'94)/`nbans'*(`i'-`anc')
+ qui gen `rp`i'`sexel'95'=rp`anc'`sexel'95+(rp`suiv'`sexel'95-rp`anc'`sexel'95)/`nbans'*(`i'-`anc')
+ }
+ qui su `rp`annee'`sexel'94'
+ local popr94=r(sum)
+ return scalar popr94=`popr94'
+ qui su `rp`annee'`sexel'95'
+ local popr95=r(sum)
+ return scalar popr95=`popr95'
+ forvalues i=`=`first'+1'/`=95-`nbans'' {
+ tempvar rp`annee'`sexel'`i'
+ local tmp=`anc'+`i'-`annee'
+ local tmp2=`suiv'+`i'-`annee'
+ qui gen `rp`annee'`sexel'`i''=rp`anc'`sexel'`tmp'+(`annee'-`anc')*(rp`suiv'`sexel'`tmp2'-rp`anc'`sexel'`tmp')/`nbans'
+ qui su `rp`annee'`sexel'`i''
+ local popr`i'=r(sum)
+ return scalar popr`i'=`popr`i''
+ }
+ forvalues i=`=95-`nbans'+1'/93 {
+ tempvar rp`annee'`sexel'`i'
+ local tmp=`anc'+`i'-`annee'
+ local tmp2=94-`i'+`annee'
+ qui gen `rp`annee'`sexel'`i''=rp`anc'`sexel'`tmp'+`=`annee'-`anc''*(`rp`tmp2'`sexel'94'-rp`anc'`sexel'`tmp')/`=`tmp2'-`anc''
+ qui su `rp`annee'`sexel'`i''
+ local popr`i'=r(sum)
+ return scalar popr`i'=`popr`i''
+ }
+ /*qui su naiss`annee'
+ local popr0=r(sum)
+ return scalar popr0=`popr0'*/
+
+ }
+ qui su naiss`annee'
+ local popr0=r(sum)
+
+ return scalar popr0=`popr0'
+}/*FIN SI COMMUNE ZE OU CANTON OU ANNEE<1990*/
+
+
+else if `codegeo'<100 { /*FRANCE, REGION OU DEPT*/
+ use "C:\ado\personal\files\popfrregdept8201.dta", clear
+ if `sexe'==0 {
+ replace sexe=0
+ }
+ if "`juillet'"=="" {
+ forvalues i=0/95 {
+ qui su age`i' if annee==`sannee'&codegeo==`codegeo'&sexe==`sexe'
+ local popr`i'=r(sum)
+ return scalar popr`i'=`popr`i''
+ }
+ }
+ else if "`juillet'"!="" {
+ local pannee=`sannee'+1
+ forvalues i=0/95 {
+ qui su age`i' if annee==`pannee'&codegeo==`codegeo'&sexe==`sexe'
+ local poppr`i'=r(sum)
+ qui su age`i' if annee==`sannee'&codegeo==`codegeo'&sexe==`sexe'
+ local popsr`i'=r(sum)
+ local popr`i'=(`poppr`i''+`popsr`i'')/2
+ return scalar popr`i'=`popr`i''
+ }
+ }
+}/*FIN FRANCE, REGION OU DEPT ET ANNEE>=1990*/
+
+
+local popr=0
+forvalues i=0/95 {
+ local popr=`popr'+`popr`i''
+}
+
+return scalar popr=`popr'
+local poprq1=`popr1'+`popr2'+`popr3'+`popr4'
+return scalar poprq1=`poprq1'
+
+foreach i of numlist 5(5)90 {
+ local poprq`i'=`popr`i''+`popr`=`i'+1''+`popr`=`i'+2''+`popr`=`i'+3''+`popr`=`i'+4''
+ return scalar poprq`i'=`poprq`i''
+}
+return scalar poprq0=`popr0'
+return scalar poprq95=`popr95'
+
+
+if `codegeo'==0 {
+ local libgeo France metropolitaine
+}
+else if `codegeo'==1 {
+ local libgeo Region Centre
+}
+else if `codegeo'==18 {
+ local libgeo Cher
+}
+else if `codegeo'==28 {
+ local libgeo Eure-et-Loir
+}
+else if `codegeo'==36 {
+ local libgeo Indre
+}
+else if `codegeo'==37 {
+ local libgeo Indre-et-Loire
+}
+else if `codegeo'==41 {
+ local libgeo Loir-et-Cher
+}
+else if `codegeo'==45 {
+ local libgeo Loiret
+}
+else {
+ qui trouve `codegeo'
+ local libgeo=r(trouve`codegeo')
+}
+di
+if `codegeo'>1000&`codegeo'<10000 {
+ di in green "Niveau geographique : Canton de " in yellow "`libgeo'"
+}
+else if `codegeo'>10000&`codegeo'<100000 {
+ di in green "Niveau geographique : Commune de " in yellow "`libgeo'"
+}
+else {
+ di in green "Niveau geographique : " in yellow "`libgeo'"
+}
+if `sexe'==0 {
+ local libsexe Deux sexes
+}
+else if `sexe'==1 {
+ local libsexe Hommes
+}
+else if `sexe'==2 {
+ local libsexe Femmes
+}
+if "`juillet'"==""&`codegeo'<100{
+ local comm="Estimation au 1er janvier"
+}
+else if "`juillet'"!=""&`codegeo'<100{
+ local comm="Estimation au 1er juillet"
+}
+else if `codegeo'>100 {
+ local comm="Retropolation entre deux recensements pour"
+}
+
+di in green "Sexe : " in yellow "`libsexe'"
+di in green "Annee : " in yellow "`comm' `=`annee'+1900'"
+
+
+di
+di in green _col(4) "{hline 22}"
+di in green _col(4) "Age" _col(16) "Population"
+di in green _col(4) "{hline 22}"
+if "`quinq'"=="" {
+ forvalues i=0/95 {
+ if `i'<2 {
+ di in green _col(4) "`i' an" _col(18) in yellow %8.0f `popr`i''
+ }
+ else if `i'==95 {
+ di in green _col(4) "95 ans et plus" _col(18) in yellow %8.0f `popr`i''
+ }
+ else {
+ di in green _col(4) "`i' ans" _col(18) in yellow %8.0f `popr`i''
+ }
+ }
+}
+else {
+ di in green _col(4) "0 an" _col(18) in yellow %8.0f `popr0'
+ di in green _col(4) "1-4 ans" _col(18) in yellow %8.0f `poprq1'
+
+ foreach i of numlist 5(5)90 {
+ di in green _col(4) "`i'-`=`i'+4' ans" _col(18) in yellow %8.0f `poprq`i''
+ }
+ di in green _col(4) "95 ans et plus" _col(18) in yellow %8.0f `popr95'
+}
+
+di in green _col(4) "{hline 22}"
+di in green _col(4) "Total" _col(18) in yellow %8.0f `popr'
+
+restore , not
+qui drop _all
+if "`saveestpop'"!="" {
+ qui use `saveestpop'
+}
+
+end
+
+
+
+
+
+
+
diff --git a/Modules/ado/personal/files/Pop8204Dep.dta b/Modules/ado/personal/files/Pop8204Dep.dta
new file mode 100644
index 0000000..d4c046b
Binary files /dev/null and b/Modules/ado/personal/files/Pop8204Dep.dta differ
diff --git a/Modules/ado/personal/files/cantons.dta b/Modules/ado/personal/files/cantons.dta
new file mode 100644
index 0000000..97f2d8f
Binary files /dev/null and b/Modules/ado/personal/files/cantons.dta differ
diff --git a/Modules/ado/personal/files/commpct.dta b/Modules/ado/personal/files/commpct.dta
new file mode 100644
index 0000000..fd0a54d
Binary files /dev/null and b/Modules/ado/personal/files/commpct.dta differ
diff --git a/Modules/ado/personal/files/communes.dta b/Modules/ado/personal/files/communes.dta
new file mode 100644
index 0000000..dabb6f2
Binary files /dev/null and b/Modules/ado/personal/files/communes.dta differ
diff --git a/Modules/ado/personal/files/commze.dta b/Modules/ado/personal/files/commze.dta
new file mode 100644
index 0000000..1597219
Binary files /dev/null and b/Modules/ado/personal/files/commze.dta differ
diff --git a/Modules/ado/personal/files/dccentre8002.dta b/Modules/ado/personal/files/dccentre8002.dta
new file mode 100644
index 0000000..15639ec
Binary files /dev/null and b/Modules/ado/personal/files/dccentre8002.dta differ
diff --git a/Modules/ado/personal/files/dcfrance8002.dta b/Modules/ado/personal/files/dcfrance8002.dta
new file mode 100644
index 0000000..cdfa54f
Binary files /dev/null and b/Modules/ado/personal/files/dcfrance8002.dta differ
diff --git a/Modules/ado/personal/files/nais8003.dta b/Modules/ado/personal/files/nais8003.dta
new file mode 100644
index 0000000..5fcdccc
Binary files /dev/null and b/Modules/ado/personal/files/nais8003.dta differ
diff --git a/Modules/ado/personal/files/rpf829099.dta b/Modules/ado/personal/files/rpf829099.dta
new file mode 100644
index 0000000..9739edb
Binary files /dev/null and b/Modules/ado/personal/files/rpf829099.dta differ
diff --git a/Modules/ado/personal/files/rph829099.dta b/Modules/ado/personal/files/rph829099.dta
new file mode 100644
index 0000000..b629089
Binary files /dev/null and b/Modules/ado/personal/files/rph829099.dta differ
diff --git a/Modules/ado/personal/files/rphf829099.dta b/Modules/ado/personal/files/rphf829099.dta
new file mode 100644
index 0000000..fb4ac01
Binary files /dev/null and b/Modules/ado/personal/files/rphf829099.dta differ
diff --git a/Modules/ado/personal/g/gammasym.ado b/Modules/ado/personal/g/gammasym.ado
new file mode 100644
index 0000000..961de2c
--- /dev/null
+++ b/Modules/ado/personal/g/gammasym.ado
@@ -0,0 +1,113 @@
+*! version 2.2 09march2007
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Gammasym : Symmetric gamma function
+*
+* Historic:
+* Version 1 (2004-01-29): Jean-Benoit Hardouin
+* Version 2 (2004-02-01): Jean-Benoit Hardouin
+* Version 2.1 (2005-04-04) : Jean-benoit Hardouin
+* Version 2.2 (2007-03-09) : Jean-benoit Hardouin /*Weights*/
+*
+* Jean-benoit Hardouin, University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2004-2007 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 gammasym,rclass
+version 7
+syntax anything [, Weight(string) DISplay]
+
+local B `weight'
+
+if "`B'"!="" {
+ numlist "`B'"
+ local B=r(numlist)
+ local nbw:word count `B'
+ local score=0
+ forvalues i=1/`nbw' {
+ local B`i':word `i' of `B'
+ local score=`score'+`B`i''
+ }
+}
+
+local nbgroups:word count `anything'
+if "`B'"=="" {
+ forvalues i=1/`nbgroups' {
+ local B`i'=1
+ }
+ local nbw=`nbgroups'
+ local score=`nbgroups'
+}
+if `nbgroups'!=`nbw' {
+ di in red "There is not the same number of values and of weights. Please correct that."
+ error
+}
+
+
+
+tokenize `anything'
+local list
+forvalues i=1/`nbgroups' {
+ local tmp=``i''
+ local list "`list' `tmp'"
+}
+
+tokenize `list'
+
+tempname G
+matrix `G'=J(`=`score'+4',`nbgroups',0)
+
+local poids=`score'+2
+local epsilon=`score'+3
+local max=`score'+4
+
+forvalues j=1/`nbgroups' {
+ matrix `G'[`poids',`j']=`B`j''
+ matrix `G'[`epsilon',`j']=exp(-``j'')^`B`j''
+ if `j'!=1 {
+ matrix `G'[`max',`j']=`G'[`max',`=`j'-1']+`B`j''
+ }
+ matrix `G'[1,`j']=1
+}
+matrix `G'[`=`B1'+1',1]=exp(-`1')^`B1'
+
+forvalues j=2/`nbgroups' {
+ local w=`B`j''
+ forvalues s=2/`=`score'+1' {
+ matrix `G'[`s',`j']=`G'[`s',`j']+`G'[`s',`=`j'-1']
+ }
+ forvalues s=`=`w'+1'/`=`score'+1' {
+ matrix `G'[`s',`j']=`G'[`s',`j']+exp(-``j'')^`w'*`G'[`=`s'-`w'',`=`j'-1']
+ }
+}
+forvalues r=0/`score' {
+ if "`display'"!="" {
+ display in green "Level: " in ye `r' in green _col(25) " Gamma=" in ye %10.5f `G'[`=`r'+1',`nbgroups']
+ }
+ return scalar gamma`r'= `G'[`=`r'+1',`nbgroups']
+}
+*return matrix G=`G'
+end
+
+
diff --git a/Modules/ado/personal/g/gammasym.hlp b/Modules/ado/personal/g/gammasym.hlp
new file mode 100644
index 0000000..46fc637
--- /dev/null
+++ b/Modules/ado/personal/g/gammasym.hlp
@@ -0,0 +1,40 @@
+{smcl}
+{* 9march2007}{...}
+{hline}
+help for {hi:gammasym}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:The symmetric gamma function}
+
+{p 8 14 2}{cmd:gamma} {it:list} [,{cmdab:w:eight}({it:string}) {cmdab:dis:play}]
+
+
+{p 4 4 2}{it:list} is a list of the values to use.
+
+{title:Description}
+
+{p 4 4 2}{cmd:gammasym} compute the values of the symmetric gamma function for all the possible level.
+
+{title:Options}
+
+{p 4 4 2}{cmd:weight} defines weights for each value (by default, all the values have a weight of 1)
+
+{p 4 4 2}{cmd:display} displays the value of the symmetric gamma function for each level.
+
+{title:Example}
+
+ {cmd:. gammasym -2.1 -1.5 -.7 -.6 1.1 1.00024 2.232447}
+
+ {cmd:. gammasym .3 .4 -.1 -.5 0 .6 , weight(1 2 1 1 2 1)}
+
+ {cmd:. gammasym 1 1 1 1 1 , w(1 2 3 4 5)}
+
+
+{title:Outputs}
+
+{p 4 4 2}{cmd:r(gamma#)} return the value of the symmetric gamma function at the level #.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@neuf.fr":jean-benoit.hardouin@neuf.fr} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/g/gausshermite.ado b/Modules/ado/personal/g/gausshermite.ado
new file mode 100644
index 0000000..e277a17
--- /dev/null
+++ b/Modules/ado/personal/g/gausshermite.ado
@@ -0,0 +1,181 @@
+*! version 2 15jan2013
+************************************************************************************************************
+* gausshermite : Estimate an integral of the form |f(x)g(x/mu,sigma)dx or f(x,y)g(x,y/mu,Sigma)dxdy where g(x/mu,sigma) is the distribution function
+* of the gaussian distribution of mean mu and variance sigma^2 and g(x,y/mu,Sigma) is the distribution function
+* of the bivariate normal distribution of mean mu and covariance matrix Sigma by Gauss Hermite quadratures
+*
+* Version 1 : May 5, 2005 (Jean-Benoit Hardouin)
+* Version 1.1: June 14, 2012 /*name option*/ (Jean-Benoit Hardouin)
+* Version 2: January 15, 2013 /*bivariate normal distribution*/ (Jean-Benoit Hardouin, Mohand-Larbi Feddag, Myriam Blanchin)
+*
+* Jean-Benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005, 2013 Jean-Benoit Hardouin, Mohand-Larbi Feddag, Myriam Blanchin
+*
+* 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 gausshermite,rclass
+version 7
+syntax anything [, Sigma(real -1) Var(string) MU(string) Nodes(integer 12) Display Name(string)]
+tempfile gauss
+qui capture save `gauss',replace
+local save=0
+if _rc==0 {
+ qui save `gauss',replace
+ local save=1
+}
+
+tokenize `anything'
+drop _all
+tempname mean variance C
+
+qui set obs `=`nodes'*`nodes''
+if "`name'"=="" {
+ if `sigma'!=-1{
+ if "`var'"==""{
+ local name x
+ local nb=1
+ }
+ else{
+ di in red "{p}Please fill in the {hi:name} option{p_end}"
+ error 198
+ exit
+ }
+ }
+ else{
+ if "`var'"!=""{
+ local name1 x1
+ local name2 x2
+ local nb=2
+ }
+ else{
+ di in red "{p}Please fill in the {hi:name} option{p_end}"
+ error 198
+ exit
+ }
+ }
+}
+else {
+ local nb=wordcount("`name'")
+ if `nb'==2{
+ local name1=word("`name'",1)
+ local name2=word("`name'",2)
+ }
+}
+
+
+if `nb'==2{
+ capture confirm matrix `var'
+ if !_rc{
+ if colsof(`var')==2 & rowsof(`var')==2{
+ matrix `C'=cholesky(`var')
+ }
+ else{
+ di in red "{p}The covariance matrix in the {hi:var} option should be a 2x2 matrix for a bivariate distribution{p_end}"
+ error 198
+ exit
+ }
+ }
+ else{
+ matrix `variance'=(1,0\0,1)
+ matrix `C'=cholesky(`variance')
+ }
+}
+else{
+ if `sigma'==-1{
+ local sig=1
+ }
+ else{
+ local sig=`sigma'
+ }
+}
+
+capture confirm matrix `mu'
+if !_rc{
+ if colsof(`mu')==1 & rowsof(`mu')==1{
+ local `mean'=`mu'[1,1]
+ }
+ else{
+ matrix `mean'=`mu'
+ }
+}
+else{
+ if "`mu'"==""{
+ if `nb'==1{
+ local `mean'=0
+ }
+ else{
+ matrix `mean'=(0,0)
+ }
+ }
+ else{
+ local `mean'=`mu'
+ }
+}
+
+tempname noeuds poids
+qui ghquadm `nodes' `noeuds' `poids'
+
+if `nb'==1{
+ qui gen `name'=.
+ qui gen poids=.
+ forvalues i=1/`nodes' {
+ qui replace `name'=`noeuds'[1,`i'] in `i'
+ qui replace poids=`poids'[1,`i'] in `i'
+ }
+ qui replace `name'=`name'*(sqrt(2)*`sig')+``mean''
+ qui gen f=poids/sqrt(_pi)*(`1')
+ *list `name' poids f in 1/5
+}
+else{
+ forvalues i=1/`nb'{
+ qui gen `name`i''=.
+ qui gen poids`i'=.
+ }
+ local line=1
+ forvalues i=1/`nodes' {
+ forvalues j=1/`nodes' {
+ qui replace `name1'=`noeuds'[1,`i'] *(sqrt(2)*`C'[1,1])+`mean'[1,1] in `line'
+ qui replace `name2'=`noeuds'[1,`i'] *(sqrt(2)*`C'[2,1])+`noeuds'[1,`j'] *(sqrt(2)*`C'[2,2])+`mean'[1,2] in `line'
+ qui replace poids1=`poids'[1,`i'] in `line'
+ qui replace poids2=`poids'[1,`j'] in `line'
+ local ++line
+ }
+ }
+ qui gen f=poids1*poids2*(`1')/(_pi)
+ *list `name1' `name2' poids1 poids2 f in 10/20
+}
+
+qui su f
+return scalar int=r(sum)
+if "`display'"!="" {
+ di in green "int_R (`1')g(`name'/sigma=`sig')d`name'=" in yellow %12.8f `r(sum)'
+}
+drop _all
+if `save'==1 {
+ qui use `gauss',clear
+}
+end
+
+
diff --git a/Modules/ado/personal/g/gausshermite.hlp b/Modules/ado/personal/g/gausshermite.hlp
new file mode 100644
index 0000000..1884439
--- /dev/null
+++ b/Modules/ado/personal/g/gausshermite.hlp
@@ -0,0 +1,43 @@
+{smcl}
+{* 5may2005}{...}
+{hline}
+help for {hi:gausshermite}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Estimation of integrals using Gauss Hermite quadratures}
+
+{p 8 14 2}{cmd:gausshermite} {it:function} , {cmdab:s:igma}({it:#}) {cmd:mu}({it:#}) {cmdab:n:odes}({it:#}) {cmdab:d:isplay}
+
+{title:Description}
+
+{p 4 4 2}{cmd:gausshermite} approximates the integrals of the form f(x)g(x/mu,sigma) on all the reals where g(x/mu,sigma) is the gaussian distribution function with mean mu and variance sigma^2.
+
+{title:Options}
+
+{p 4 4 2}{it:function} defines f(x). For example, if f(x)=x^2, {it:function} is x^2. It is necessary to use x for the variable of integration.
+
+{p 4 4 2}{cmd:mu} defines the mean of x (0 by default).
+
+{p 4 4 2}{cmd:sigma} defines the standard deviation of x (1 by default).
+
+{p 4 4 2}{cmd:nodes} defines the number of quadrature nodes (12 by default).
+
+{p 4 4 2}{cmd:display} allows automatically displaying the estimation.
+
+{p 4 4 2}Note that the quadrature nodes and the associated weights are computed using the {cmd:ghquadm} Stata command. Find this command with {stata findit ghquadm:findit ghquadm}.
+
+{title:Example}
+
+ {cmd:. gausshermite x^2}
+
+ {cmd:. gausshermite x^4+exp(x)-2, sigma(1.5) mu(-.4) d n(10)}
+
+
+{title:Outputs}
+
+{p 4 4 2}The estimated value of the integral is saved in {cmd:r(int)}.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/g/gausshermite1.ado b/Modules/ado/personal/g/gausshermite1.ado
new file mode 100644
index 0000000..5d46cf3
--- /dev/null
+++ b/Modules/ado/personal/g/gausshermite1.ado
@@ -0,0 +1,72 @@
+*! version 1 5may2005
+************************************************************************************************************
+* gausshermite : Estimate an integral of the form |f(x)g(x/mu,sigma)dx where g(x/mu,sigma) is the distribution function
+* of the gaussian distribution of mean mu and variance sigma^2 by Gauss Hermite quadratures
+*
+* Version 1: May 5, 2005
+*
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005 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 gausshermite,rclass
+version 7
+syntax anything [, Sigma(real 1) MU(real 0) Nodes(integer 12) Display]
+tempfile gauss
+qui capture save `gauss',replace
+local save=0
+if _rc==0 {
+ qui save `gauss',replace
+ local save=1
+}
+
+tokenize `anything'
+
+drop _all
+qui set obs 100
+tempname noeuds poids
+qui ghquadm `nodes' `noeuds' `poids'
+qui gen x=.
+qui gen poids=.
+forvalues i=1/`nodes' {
+ qui replace x=`noeuds'[1,`i'] in `i'
+ qui replace poids=`poids'[1,`i'] in `i'
+}
+qui replace x=x*(sqrt(2)*`sigma')+`mu'
+
+qui gen f=poids/sqrt(_pi)*(`1')
+qui su f
+return scalar int=r(sum)
+
+if "`display'"!="" {
+ di in green "int_R (`1')g(x/sigma=`sigma')dx=" in yellow %12.8f `r(sum)'
+}
+drop _all
+if `save'==1 {
+ qui use `gauss',clear
+}
+end
+
+
diff --git a/Modules/ado/personal/g/gausshermite2.ado b/Modules/ado/personal/g/gausshermite2.ado
new file mode 100644
index 0000000..2548679
--- /dev/null
+++ b/Modules/ado/personal/g/gausshermite2.ado
@@ -0,0 +1,104 @@
+*! version 1 03 January 2012
+************************************************************************************************************
+* gausshermite2 : Estimate an integral of the form : f(x,y)g(x,y/mu,Sigma)dxdy where g(x,y/mu,Sigma) is the distribution function
+* of the bivariate normal distribution of mean mu and covariance matrix Sigma by Gauss Hermite quadratures
+*
+* Version 1: 03 January 2012
+*
+*
+* Mohand Feddag, University of Nantes - France
+* Mohand-Larbi.Feddag@univ-nantes.fr *
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2012 Mohand Feddag
+*
+* 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 gausshermite2,rclass
+version 11
+syntax anything [, Mu(string) Sigma(string) Nodes(integer 12) Display]
+tempfile gauss2
+qui capture save `gauss2',replace
+local save=0
+if _rc==0 {
+ qui save `gauss2',replace
+ local save=1
+}
+if "`mu'"=="" {
+ tempname mu
+ matrix `mu'=[0,0]
+}
+if "`sigma'"=="" {
+ tempname sigma
+ matrix `sigma'=[1,0\0,1]
+}
+tokenize `anything'
+
+drop _all
+qui set obs `=`nodes'*`nodes''
+tempname noeuds poids
+qui ghquadm `nodes' `noeuds' `poids'
+
+* Cholesky transformation for the covariance matrix sigma
+
+matrix C=cholesky(`sigma')
+*matrix list C
+local line=1
+qui gen x1=.
+qui gen x2=.
+qui gen poids1=.
+qui gen poids2=.
+forvalues i=1/`nodes' {
+ forvalues j=1/`nodes' {
+ qui replace x1=`noeuds'[1,`i'] *(sqrt(2)*C[1,1])+`mu'[1,1] in `line'
+ qui replace x2=`noeuds'[1,`i'] *(sqrt(2)*C[2,1])+`noeuds'[1,`j'] *(sqrt(2)*C[2,2])+`mu'[1,2] in `line'
+ qui replace poids1=`poids'[1,`i'] in `line'
+ qui replace poids2=`poids'[1,`j'] in `line'
+ local ++line
+ }
+}
+
+* Double somme du produit poids[i]*poids[j]*f(x1,x2) qui est affecté a la variable sum
+
+qui gen f=poids1*poids2*(`1')/(_pi)
+*list x1 x2 poids1 f (sqrt(2)*_pi)
+qui su f
+local sum=r(sum)
+ return scalar int=`sum'
+
+ if "`display'"!="" {
+ di in green "int_R^2 (`1')g(x1,x2/mu=`mu',Sigma=`Sigma')dx1dx2=" in yellow %12.8f `sum'
+}
+drop _all
+if `save'==1 {
+ qui use `gauss2',clear
+}
+end
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Modules/ado/personal/g/gausshermite3.ado b/Modules/ado/personal/g/gausshermite3.ado
new file mode 100644
index 0000000..c31540f
--- /dev/null
+++ b/Modules/ado/personal/g/gausshermite3.ado
@@ -0,0 +1,134 @@
+*! version 2 11dec2012
+************************************************************************************************************
+* gausshermite : Estimate an integral of the form |f(x)g(x/mu,sigma)dx or f(x,y)g(x,y/mu,Sigma)dxdy where g(x/mu,sigma) is the distribution function
+* of the gaussian distribution of mean mu and variance sigma^2 and g(x,y/mu,Sigma) is the distribution function
+* of the bivariate normal distribution of mean mu and covariance matrix Sigma by Gauss Hermite quadratures
+*
+* Version 1: May 5, 2005
+* Version 1.1: June 14, 2012 /*name option*/
+* Version 2: December 11, 2012 /*bivariate normal distribution*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005, 2012 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 gausshermite3,rclass
+version 7
+syntax anything [, Sigma(string) MU(string) Nodes(integer 12) Display Name(string)]
+tempfile gauss
+qui capture save `gauss',replace
+local save=0
+if _rc==0 {
+ qui save `gauss',replace
+ local save=1
+}
+
+tokenize `anything'
+
+drop _all
+qui set obs `=`nodes'*`nodes''
+if "`name'"=="" {
+ local name x
+ local nb=1
+}
+else {
+ local nb=wordcount("`name'")
+ if `nb'==2{
+ di word("`name'",1)
+ local name1=word("`name'",1)
+ local name2=word("`name'",2)
+ }
+}
+
+capture confirm matrix `sigma'
+if !_rc{
+ if colsof(`sigma')==1 & rowsof(`sigma')==1{
+ local sig=`sigma'[1,1]
+ }
+ else{
+ matrix C=cholesky(`sigma')
+ }
+}
+else{
+ local sig=`sigma'
+}
+
+capture confirm matrix `mu'
+if !_rc{
+ if colsof(`mu')==1 & rowsof(`mu')==1{
+ local mean=`mu'[1,1]
+ }
+ else{
+ matrix mean=`mu'
+ }
+}
+else{
+ local mean=`mu'
+}
+
+tempname noeuds poids
+qui ghquadm `nodes' `noeuds' `poids'
+
+if `nb'==1{
+ qui gen `name'=.
+ qui gen poids=.
+ forvalues i=1/`nodes' {
+ qui replace `name'=`noeuds'[1,`i'] in `i'
+ qui replace poids=`poids'[1,`i'] in `i'
+ }
+ qui replace `name'=`name'*(sqrt(2)*`sig')+`mean'
+ qui gen f=poids/sqrt(_pi)*(`1')
+ *list `name' poids f in 1/5
+}
+else{
+ forvalues i=1/`nb'{
+ qui gen `name`i''=.
+ qui gen poids`i'=.
+ }
+ local line=1
+ forvalues i=1/`nodes' {
+ forvalues j=1/`nodes' {
+ qui replace `name1'=`noeuds'[1,`i'] *(sqrt(2)*C[1,1])+mean[1,1] in `line'
+ qui replace `name2'=`noeuds'[1,`i'] *(sqrt(2)*C[2,1])+`noeuds'[1,`j'] *(sqrt(2)*C[2,2])+mean[1,2] in `line'
+ qui replace poids1=`poids'[1,`i'] in `line'
+ qui replace poids2=`poids'[1,`j'] in `line'
+ local ++line
+ }
+ }
+ qui gen f=poids1*poids2*(`1')/(_pi)
+ *list `name1' `name2' poids1 poids2 f in 10/20
+}
+
+qui su f
+return scalar int=r(sum)
+if "`display'"!="" {
+ di in green "int_R (`1')g(`name'/sigma=`sigma')d`name'=" in yellow %12.8f `r(sum)'
+}
+drop _all
+if `save'==1 {
+ qui use `gauss',clear
+}
+end
+
+
diff --git a/Modules/ado/personal/g/geekel2d.ado b/Modules/ado/personal/g/geekel2d.ado
new file mode 100644
index 0000000..12f3c03
--- /dev/null
+++ b/Modules/ado/personal/g/geekel2d.ado
@@ -0,0 +1,503 @@
+*! version 4.3 18january2006
+************************************************************************************************************
+* GEEkel2d: GEE for estimation of unidimensional or 2-dimensional Latent Trait models (Kelderman and Rijkes 1994)
+*
+* Version 4.3: January 18, 2006 /*Faster version*/
+*
+* Historic:
+* Version 1 (2003-06-23): Jean-Benoit Hardouin
+* Version 2 (2003-08-13): Jean-Benoit Hardouin
+* version 3 (2003-11-06): Jean-Benoit Hardouin
+* Version 4 (2004-06-08): Jean-Benoit Hardouin
+* Version 4.1 (2005-04-02): Jean-Benoit Hardouin
+* Version 4.2 (2005-07-02): Jean-Benoit Hardouin
+*
+* Use the ghquadm program (findit ghquadm)
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003-2006 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 geekel2d ,rclass
+version 7.0
+syntax varlist(min=2 numeric) [, coef(string) novar ll nbit(integer 30) critconv(real 1e-15) quad(integer 12) ]
+
+preserve
+local nbitems: word count `varlist'
+tokenize `varlist'
+
+qui count
+local N=r(N)
+
+forvalues i=1/`nbitems' {
+ qui drop if ``i''==.
+}
+
+qui count
+local Naf=r(N)
+
+di _col(3) in green "Initial step (N=" in yellow `Naf' in green ")"
+di _col(3) in yellow `=`N'-`Naf'' in green " observations are not used for missing values"
+di
+
+qui count
+local N=r(N)
+tempname B Q
+if "`coef'"!="" {
+ matrix `B'=`coef'
+}
+else {
+ matrix `B'=J(`nbitems',1,1)
+}
+
+scalar `Q'=colsof(`B')
+
+/* CALCUL INITIAUX DES PARAMETRES DELTA ET SIGMA ET DE LA MATRICE BETA*/
+
+local sigmath11=0.25
+
+if `Q'==2 {
+ local sigmath22=.25
+ local sigmath12=0.125
+}
+
+tempname beta
+matrix `beta'=J(`nbitems'+`Q'*(`Q'+1)/2,1,0)
+forvalues i=1/`nbitems' {
+ qui count if ``i''==1
+ local si`i'=r(N)
+ local delta``i''=-log(`si`i''/(`N'-`si`i''))
+ matrix `beta'[`i',1]=`delta``i'''
+ forvalues j=`i'/`nbitems' {
+ quiet count if ``j''==1&``i''==1
+ local si`i'j`j'=r(N)
+ local si`j'j`i'=r(N)
+ if "`var'"=="" {
+ forvalues k=`j'/`nbitems' {
+ quiet count if ``i''==1&``j''==1&``k''==1
+ local si`i'j`j'k`k'=r(N)
+ local si`i'j`k'k`j'=r(N)
+ local si`j'j`i'k`k'=r(N)
+ local si`j'j`k'k`i'=r(N)
+ local si`k'j`i'k`j'=r(N)
+ local si`k'j`j'k`i'=r(N)
+ forvalues l=`k'/`nbitems' {
+ quiet count if ``i''==1&``j''==1&``k''==1&``l''==1
+ local si`i'j`j'k`k'l`l'=r(N)
+ local si`i'j`j'k`l'l`k'=r(N)
+ local si`i'j`k'k`j'l`l'=r(N)
+ local si`i'j`k'k`l'l`j'=r(N)
+ local si`i'j`l'k`j'l`k'=r(N)
+ local si`i'j`l'k`k'l`j'=r(N)
+
+ local si`j'j`i'k`k'l`l'=r(N)
+ local si`j'j`i'k`l'l`k'=r(N)
+ local si`j'j`k'k`i'l`l'=r(N)
+ local si`j'j`k'k`l'l`i'=r(N)
+ local si`j'j`l'k`i'l`k'=r(N)
+ local si`j'j`l'k`k'l`i'=r(N)
+
+ local si`k'j`i'k`j'l`l'=r(N)
+ local si`k'j`i'k`l'l`j'=r(N)
+ local si`k'j`j'k`i'l`l'=r(N)
+ local si`k'j`j'k`l'l`i'=r(N)
+ local si`k'j`l'k`i'l`j'=r(N)
+ local si`k'j`l'k`j'l`i'=r(N)
+
+ local si`l'j`i'k`j'l`k'=r(N)
+ local si`l'j`i'k`k'l`j'=r(N)
+ local si`l'j`j'k`i'l`k'=r(N)
+ local si`l'j`j'k`k'l`i'=r(N)
+ local si`l'j`k'k`i'l`j'=r(N)
+ local si`l'j`k'k`j'l`i'=r(N)
+ }
+ }
+ }
+ }
+}
+
+local l=`nbitems'+1
+matrix `beta'[`l',1]=`sigmath11'
+
+if `Q'==2 {
+ local l=`nbitems'+2
+ matrix `beta'[`l',1]=`sigmath22'
+ local l=`nbitems'+3
+ matrix `beta'[`l',1]=`sigmath12'
+}
+
+tempname variat V11 V12 V21 V22 D11 D12 D21 D22 V D
+matrix `variat'=(1)
+local compteur=0
+local conv=1
+
+
+/*********ITERATIONS******************/
+
+
+
+while (`variat'[1,1]>`critconv'&`compteur'<=`nbit'&`conv'==1) {
+ if `compteur'==0{
+ di in green _col(3) "First iteration"
+ }
+ else {
+ di in green _col(3) "iteration:" in yellow _col(14) "`compteur'" in green _col(25) "Convergence index:" in yellow _col(44) %10.7e "`macrovariat'"
+ }
+ local compteur=`compteur'+1
+
+ forvalues j=1/`nbitems' {
+
+ /* CALCUL DES DERIVEES 1 A 6 POUR CHAQUE ITEM*/
+ local l1``j''=1/(1+exp(`beta'[`j',1]))
+ local l2``j''=exp(`beta'[`j',1])/(1+exp(`beta'[`j',1]))^2
+ local l3``j''=exp(`beta'[`j',1])*(exp(`beta'[`j',1])-1)/(1+exp(`beta'[`j',1]))^3
+ local l4``j''=exp(`beta'[`j',1])*(exp(2*`beta'[`j',1])-4*exp(`beta'[`j',1])+1)/(1+exp(`beta'[`j',1]))^4
+ local l5``j''=exp(`beta'[`j',1])*(exp(3*`beta'[`j',1])-11*exp(2*`beta'[`j',1])+11*exp(`beta'[`j',1])-1)/(1+exp(`beta'[`j',1]))^5
+ local l6``j''=exp(`beta'[`j',1])*(exp(4*`beta'[`j',1])-26*exp(3*`beta'[`j',1])+66*exp(2*`beta'[`j',1])-26*exp(`beta'[`j',1])+1)/(1+exp(`beta'[`j',1]))^6
+
+ if `Q'==2 {
+ local H2i`j'=`B'[`j',1]^2*`sigmath11'+`B'[`j',1]*`B'[`j',2]*`sigmath12'+`B'[`j',2]^2*`sigmath22'
+ local H4i`j'=3*`B'[`j',1]^4*`sigmath11'^2+12*`B'[`j',1]^3*`B'[`j',2]*`sigmath11'*`sigmath12'+6*`B'[`j',1]^2*`B'[`j',2]^2*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+12*`B'[`j',1]*`B'[`j',2]^3*`sigmath22'*`sigmath12'+3*`B'[`j',2]^4*`sigmath22'^2
+ }
+ else if `Q'==1 {
+ local H2i`j'=`B'[`j',1]^2*`sigmath11'
+ local H4i`j'=3*`B'[`j',1]^4*`sigmath11'^2
+ }
+
+ /* CALCUL DES MOMENTS D'ORDRE 1 ET 2 ET DE LA MATRICE V11*/
+ local mui`j'=`l1``j'''+`H2i`j''/2*`l3``j'''+`H4i`j''/24*`l5``j'''
+ local sigmai`j'j`j'=`l2``j'''+`H2i`j''/2*(`l3``j'''-2*`l1``j'''*`l3``j''')+`H4i`j''/24*(`l5``j'''-2*(`l3``j''')^2-2*`l1``j'''*`l5``j''')
+ }
+
+
+ matrix `V11'=J(`nbitems',`nbitems',0)
+
+ forvalues j=1/`nbitems' {
+ matrix `V11'[`j',`j']=`sigmai`j'j`j''
+ forvalues l=`=`j'+1'/`nbitems' {
+ if `Q'==2 {
+ local H2i`j'j`l'=`B'[`j',1]*`B'[`l',1]*`sigmath11'+(`B'[`j',1]*`B'[`l',2]+`B'[`j',2]*`B'[`l',1])*`sigmath12'+`B'[`j',2]*`B'[`l',2]*`sigmath22'
+ local H4i`j'1j`l'3=3*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'^2+3*(3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath11'*`sigmath12'+(3*`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+3*`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+3*(`B'[`j',1]*`B'[`l',2]^3+3*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]^2)*`sigmath22'*`sigmath12'+3*`B'[`j',2]*`B'[`l',2]^3*`sigmath22'^2
+ local H4i`j'2j`l'2=3*`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'^2+6*(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath11'*`sigmath12'+(`B'[`j',1]^2*`B'[`l',2]^2+4*`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]+`B'[`j',2]^2*`B'[`l',1]^2)*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+6*(`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2+`B'[`j',2]^2*`B'[`l',1]*`B'[`l',2])*`sigmath22'*`sigmath12'+3*`B'[`j',2]^2*`B'[`l',2]^2*`sigmath22'^2
+ local H4i`j'3j`l'1=3*`B'[`l',1]*`B'[`j',1]^3*`sigmath11'^2+3*(3*`B'[`l',1]*`B'[`j',1]^2*`B'[`j',2]+`B'[`l',2]*`B'[`j',1]^3)*`sigmath11'*`sigmath12'+(3*`B'[`l',1]*`B'[`j',1]*`B'[`j',2]^2+3*`B'[`l',2]*`B'[`j',1]^2*`B'[`j',2])*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+3*(`B'[`l',1]*`B'[`j',2]^3+3*`B'[`l',2]*`B'[`j',1]*`B'[`j',2]^2)*`sigmath22'*`sigmath12'+3*`B'[`l',2]*`B'[`j',2]^3*`sigmath22'^2
+ }
+ else if `Q'==1 {
+ local H2i`j'j`l'=`B'[`j',1]*`B'[`l',1]*`sigmath11'
+ local H4i`j'1j`l'3=3*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'^2
+ local H4i`j'2j`l'2=3*`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'^2
+ local H4i`j'3j`l'1=3*`B'[`l',1]*`B'[`j',1]^3*`sigmath11'^2
+ }
+ local H2i`l'j`j'=`H2i`j'j`l''
+ local H4i`l'1j`j'3=`H4i`j'1j`l'3'
+ local H4i`l'2j`j'2=`H4i`j'2j`l'2'
+ local H4i`l'3j`j'1=`H4i`j'3j`l'1'
+ local sigmai`j'j`l'=`H2i`j'j`l''*(`l2``j'''*`l2``l''')+`H4i`j'1j`l'3'/6*`l2``j'''*`l4``l'''+`H4i`j'3j`l'1'/6*`l4``j'''*`l2``l'''+(`H4i`j'2j`l'2'-`H2i`j''*`H2i`l'')/4*`l3``j'''*`l3``l'''
+ }
+ }
+
+ /* DEFINITION DE LA MATRICE COMPOCARRE*/
+ tempname compocarre m
+ local carre=`nbitems'*(`nbitems'-1)/2
+ matrix `compocarre'=J(2,`carre',0)
+
+ local m=0
+ forvalues j=1/`nbitems' {
+ forvalues l=`=`j'+1'/`nbitems' {
+ local m=`m'+1
+ matrix `compocarre'[1,`m']=`j'
+ matrix `compocarre'[2,`m']=`l'
+ }
+ }
+
+ /* CALCUL DE LA MATRICE V22*/
+ matrix `V22'=J(`carre',`carre',0)
+ forvalues k=1/`carre' {
+ local j=`compocarre'[1,`k']
+ local l=`compocarre'[2,`k']
+ matrix `V22'[`k',`k']=(1-2*`mui`j'')*(1-2*`mui`l'')*`sigmai`j'j`l''+`sigmai`j'j`j''*`sigmai`l'j`l''-`sigmai`j'j`l''^2
+ }
+
+ /* CALCUL DES MATRICES V12, V21 ET V*/
+ matrix `V12'=J(`nbitems',`carre',0)
+ forvalues k=1/`carre' {
+ local j=`compocarre'[1,`k']
+ local l=`compocarre'[2,`k']
+ matrix `V12'[`j',`k']=(1-2*`mui`j'')*`sigmai`j'j`l''
+ matrix `V12'[`l',`k']=(1-2*`mui`l'')*`sigmai`j'j`l''
+ }
+ matrix `V21'=`V12' '
+ matrix `V'=(`V11',`V12' \ `V21',`V22')
+
+ /*CALCUL DES MATRICES D11*/
+ matrix `D11'=J(`nbitems',`nbitems',0)
+ matrix `D12'=J(`nbitems',`Q'*(`Q'+1)/2,0)
+
+ forvalues j=1/`nbitems' {
+ matrix `D11'[`j',`j']=-`l2``j'''-`H2i`j''/2*`l4``j'''-`H4i`j''/24*`l6``j'''
+
+ if `Q'==2 {
+ matrix `D12'[`j',1]=`B'[`j',1]^2*`l3``j'''/2+(`B'[`j',1]^4*`sigmath11'+2*`B'[`j',1]^3*`B'[`j',2]*`sigmath12'+`B'[`j',1]^2*`B'[`j',2]^2*`sigmath22')/4*`l5``j'''
+ matrix `D12'[`j',2]=`B'[`j',2]^2*`l3``j'''/2+(`B'[`j',2]^4*`sigmath22'+2*`B'[`j',2]^3*`B'[`j',1]*`sigmath12'+`B'[`j',2]^2*`B'[`j',1]^2*`sigmath11')/4*`l5``j'''
+ matrix `D12'[`j',3]=`B'[`j',1]*`B'[`j',2]*`l3``j'''+(`B'[`j',1]^3*`B'[`j',2]*`sigmath11'+2*`B'[`j',1]^2*`B'[`j',2]^2*`sigmath12'+`B'[`j',1]*`B'[`j',2]^3*`sigmath22')/2*`l5``j'''
+ }
+ else if `Q'==1 {
+ matrix `D12'[`j',1]=`B'[`j',1]^2*`l3``j'''/2+`B'[`j',1]^4*`sigmath11'/4*`l5``j'''
+ }
+ }
+
+ /*CALCUL DES MATRICES D21, D22 et D*/
+ matrix `D21'=J(`carre',`nbitems',0)
+ matrix `D22'=J(`carre',`Q'*(`Q'+1)/2,0)
+
+ forvalues k=1/`carre' {
+ local j=`compocarre'[1,`k']
+ local l=`compocarre'[2,`k']
+ matrix `D21'[`k',`j']=-`H2i`j'j`l''*`l3``j'''*`l2``l'''-`H4i`j'1j`l'3'/6*`l3``j'''*`l4``l'''-`H4i`j'3j`l'1'/6*`l5``j'''*`l2``l'''-(`H4i`j'2j`l'2'-`H2i`j''*`H2i`l'')/4*`l4``j'''*`l3``l'''
+ matrix `D21'[`k',`l']=-`H2i`j'j`l''*`l2``j'''*`l3``l'''-`H4i`j'3j`l'1'/6*`l4``j'''*`l3``l'''-`H4i`j'1j`l'3'/6*`l2``j'''*`l5``l'''-(`H4i`j'2j`l'2'-`H2i`j''*`H2i`l'')/4*`l3``j'''*`l4``l'''
+
+ tempname tmp1 tmp2 tmp3
+ if `Q'==2 {
+ scalar `tmp1'=`B'[`j',1]*`B'[`l',1]*`l2``j'''*`l2``l'''+(2*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'+(3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath12'+(`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*`sigmath22')/2*`l2``j'''*`l4``l'''
+ scalar `tmp2'=(2*`B'[`j',1]^3*`B'[`l',1]*`sigmath11'+(3*`B'[`j',1]^2*`B'[`j',2]*`B'[`l',1]+`B'[`j',1]^3*`B'[`l',2])*`sigmath12'+(`B'[`j',1]*`B'[`j',2]^2*`B'[`l',1]+`B'[`j',1]^2*`B'[`j',2]*`B'[`l',2])*`sigmath22')/2*`l4``j'''*`l2``l'''
+ scalar `tmp3'=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'+(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath12'+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]*`sigmath22')*`l3``j'''*`l3``l'''
+ matrix `D22'[`k',1]=`tmp1'+`tmp2'+`tmp3'
+ scalar `tmp1'=`B'[`j',2]*`B'[`l',2]*`l2``j'''*`l2``l'''+(2*`B'[`j',2]*`B'[`l',2]^3*`sigmath22'+(3*`B'[`j',2]*`B'[`l',2]^2*`B'[`l',1]+`B'[`j',1]*`B'[`l',2]^3)*`sigmath12'+(`B'[`j',2]*`B'[`l',2]*`B'[`l',1]^2+`B'[`j',1]*`B'[`l',2]^2*`B'[`l',1])*`sigmath11')/2*`l2``j'''*`l4``l'''
+ scalar `tmp2'=(2*`B'[`j',2]^3*`B'[`l',2]*`sigmath22'+(3*`B'[`j',2]^2*`B'[`j',1]*`B'[`l',2]+`B'[`j',2]^3*`B'[`l',1])*`sigmath12'+(`B'[`j',2]*`B'[`j',1]^2*`B'[`l',2]+`B'[`j',2]^2*`B'[`j',1]*`B'[`l',1])*`sigmath11')/2*`l4``j'''*`l2``l'''
+ scalar `tmp3'=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath22'+(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath12'+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]*`sigmath11')*`l3``j'''*`l3``l'''
+ matrix `D22'[`k',2]=`tmp1'+`tmp2'+`tmp3'
+ scalar `tmp1'=(`B'[`j',1]*`B'[`l',2]+`B'[`j',2]*`B'[`l',1])*`l2``j'''*`l2``l'''+((3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath11'+4*(`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*`sigmath12'+(`B'[`j',1]*`B'[`l',2]^3+3*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]^2)*`sigmath22')/2*`l2``j'''*`l4``l'''
+ scalar `tmp2'=((3*`B'[`j',1]^2*`B'[`j',2]*`B'[`l',1]+`B'[`j',1]^3*`B'[`l',2])*`sigmath11'+4*(`B'[`j',1]*`B'[`j',2]^2*`B'[`l',1]+`B'[`j',1]^2*`B'[`j',2]*`B'[`l',2])*`sigmath12'+(`B'[`j',2]^3*`B'[`l',1]+3*`B'[`j',1]*`B'[`j',2]^2*`B'[`l',2])*`sigmath22')/2*`l4``j'''*`l2``l'''
+ scalar `tmp3'=((`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2)*`sigmath11'+(`B'[`j',1]^2*`B'[`l',2]^2+2*`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]+`B'[`j',2]^2*`B'[`l',1]^2)*`sigmath12'+(`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2+`B'[`j',2]^2*`B'[`l',1]*`B'[`l',2])*`sigmath22')*`l3``j'''*`l3``l'''
+ matrix `D22'[`k',3]=`tmp1'+`tmp2'+`tmp3'
+ }
+ else if `Q'==1 {
+ scalar `tmp1'=`B'[`j',1]*`B'[`l',1]*`l2``j'''*`l2``l'''+(2*`B'[`j',1]*`B'[`l',1]^3*`sigmath11')/2*`l2``j'''*`l4``l'''
+ scalar `tmp2'=(2*`B'[`j',1]^3*`B'[`l',1]*`sigmath11')/2*`l4``j'''*`l2``l'''
+ scalar `tmp3'=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11')*`l3``j'''*`l3``l'''
+ matrix `D22'[`k',1]=`tmp1'+`tmp2'+`tmp3'
+ }
+ }
+ matrix `D'=(`D11',`D12' \ `D21',`D22')
+
+ /*CALCUL DE LA MATRICE CHSI*/
+
+ tempname chsi
+ matrix `chsi'=J(`nbitems'+`carre',1,0)
+
+ forvalues j=1/`nbitems' {
+ matrix `chsi'[`j',1]=(`si`j''-`N'*`mui`j'')/`N'
+ }
+ forvalues k=1/`carre' {
+ local j=`compocarre'[1,`k']
+ local l=`compocarre'[2,`k']
+ local tmp=`nbitems'+`k'
+ matrix `chsi'[`tmp',1]=(`si`j'j`l''-`si`j''*`mui`l''-`si`l''*`mui`j''+`N'*`mui`j''*`mui`l''-`N'*`sigmai`j'j`l'')/`N'
+ }
+
+ /*CALCUL DE L'ETAPE k*/
+ tempname betaold
+ matrix `betaold'=`beta'
+ matrix `beta'=`betaold'+inv(`D''*inv(`V')*`D')*`D''*inv(`V')*`chsi'
+
+ local l=`nbitems'+1
+ local sigmath11=`beta'[`l',1]
+ local l=`nbitems'+2
+ local sigmath22=`beta'[`l',1]
+ local l=`nbitems'+3
+ local sigmath12=`beta'[`l',1]
+
+ tempname epsilon variatold
+ scalar `variatold'=`variat'[1,1]
+ matrix `epsilon'=`betaold'-`beta'
+ matrix `variat'=(`epsilon''*`epsilon')
+
+ if `variat'[1,1]>`variatold' {
+ matrix `beta'=`betaold'
+ local l=`nbitems'+1
+ local sigm ath11=`beta'[`l',1]
+ if `Q'==2 {
+ local l=`nbitems'+2
+ local sigmath22=`beta'[`l',1]
+ local l=`nbitems'+3
+ local sigmath12=`beta'[`l',1]
+ }
+ local conv=0
+ }
+ else {
+ local macrovariat=`variat'[1,1]
+ }
+}
+
+/*************************CALCUL des STANDARDS ERRORS DES PARAMETRES *********************/
+
+if "`var'"==""{
+ tempname xicarreA xicarreB xicarreC xicarre
+ matrix `xicarreA'=J(`nbitems',`nbitems',0)
+ matrix `xicarreB'=J(`nbitems',`carre',0)
+ matrix `xicarreC'=J(`carre',`carre',0)
+ forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ matrix `xicarreA'[`i',`j']=`si`i'j`j''-`si`i''*`mui`j''-`si`j''*`mui`i''+`N'*`mui`i''*`mui`j''
+ matrix `xicarreA'[`i',`j']=`xicarreA'[`j',`i']
+ }
+ forvalues col=1/`carre' {
+ local j=`compocarre'[1,`col']
+ local k=`compocarre'[2,`col']
+ matrix `xicarreB'[`i',`col']=`si`i'j`j'k`k''-`mui`i''*`si`j'j`k''-`mui`j''*`si`i'j`k''-`mui`k''*`si`i'j`j''+`mui`i''*`mui`j''*`si`k''+`mui`i''*`mui`k''*`si`j''+`mui`j''*`mui`k''*`si`i''-`N'*`mui`i''*`mui`j''*`mui`k''-`sigmai`j'j`k''*`si`i''+`N'*`mui`i''*`sigmai`j'j`k'''
+ }
+ }
+ forvalues row=1/`carre' {
+ forvalues col=`row'/`carre' {
+ local i=`compocarre'[1,`row']
+ local j=`compocarre'[2,`row']
+ local k=`compocarre'[1,`col']
+ local l=`compocarre'[2,`col']
+ matrix `xicarreC'[`row',`col']=`si`i'j`j'k`k'l`l''-`mui`i''*`si`j'j`k'l`l''-`mui`j''*`si`i'j`k'k`l''-`mui`k''*`si`i'j`j'k`l''-`mui`l''*`si`i'j`j'k`k''+`mui`i''*`mui`j''*`si`k'j`l''+`mui`i''*`mui`k''*`si`j'j`l''+`mui`i''*`mui`l''*`si`j'j`k''+`mui`j''*`mui`k''*`si`i'j`l''+`mui`j''*`mui`l''*`si`i'j`k''+`mui`k''*`mui`l''*`si`i'j`j''-`mui`i''*`mui`j''*`mui`k''*`si`l''-`mui`i''*`mui`j''*`mui`l''*`si`k''-`mui`i''*`mui`k''*`mui`l''*`si`j''-`mui`j''*`mui`k''*`mui`l''*`si`i''-`sigmai`i'j`j''*`si`k'j`l''-`sigmai`k'j`l''*`si`i'j`j''+`sigmai`i'j`j''*`mui`k''*`si`l''+`sigmai`i'j`j''*`mui`l''*`si`k''+`sigmai`k'j`l''*`mui`i''*`si`j''+`sigmai`k'j`l''*`mui`j''*`si`i''+`N'*`mui`i''*`mui`j''*`mui`k''*`mui`l''-`N'*`sigmai`i'j`j''*`mui`k''*`mui`l''-`N'*`sigmai`k'j`l''*`mui`i''*`mui`j''+`N'*`sigmai`i'j`j''*`sigmai`k'j`l''
+ matrix `xicarreC'[`col',`row']=`xicarreC'[`row',`col']
+ }
+ }
+ matrix `xicarre'=(`xicarreA',`xicarreB' \ `xicarreB' ',`xicarreC')
+ tempname A1 A2 W
+ matrix `A1'=`D' '*inv(`V')*`D'
+ matrix `A2'=`D' '*inv(`V')*`xicarre'*inv(`V')*`D'
+ matrix `W'=1/`N'^2*inv(`A1')*`A2'*inv(`A1')
+}
+
+/*****************************DISPLAY THE RESULTS***************************************/
+
+
+local compteur=`compteur'-1
+di ""
+di ""
+if `compteur'==0 {
+ noi di in red _col(8) "The algorithm does not converge"
+ return scalar error=1
+ exit
+}
+if `variat'[1,1]<=`critconv'&`compteur'>0 {
+ noi di in green _col(8) "The algorithm converges at the `compteur'th iteration"
+}
+if `compteur'==`nbit'&`variat'[1,1]>`critconv' {
+ noi di in green _col(8) "The algorithm is stopped at the `compteur'th iteration"
+}
+if `conv'==0&`compteur'>0 {
+ noi di in green _col(8) "The algorithm no more converges after the `compteur'th iteration"
+}
+di ""
+if "`var'"=="" {
+ noi di in green _col(30) "Parameters" in green _col(43) "Standard errors"
+ forvalues j=1/`nbitems' {
+ noi di in green _col(20) "``j'': " in yellow _col(30) %10.6f `beta'[`j',1] in yellow _col(50) %8.6f sqrt(`W'[`j',`j'])
+ }
+ di ""
+ noi di in green _col(20) "var1: " in yellow _col(30) %10.6f `beta'[`nbitems'+1,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+1,`nbitems'+1])
+ if `Q'==2 {
+ noi di in green _col(20) "var2: " in yellow _col(30) %10.6f `beta'[`nbitems'+2,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+2,`nbitems'+2])
+ tempname rho
+ scalar `rho'=`beta'[`nbitems'+3,1]/sqrt(`beta'[`nbitems'+1,1]*`beta'[`nbitems'+2,1])
+ noi di in green _col(20) "covar: " in yellow _col(30) %10.6f `beta'[`nbitems'+3,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+3,`nbitems'+3]) " (rho=" %5.4f `rho' ")"
+ }
+}
+else {
+ noi di in green _col(30) "Parameters"
+ forvalues j=1/`nbitems' {
+ noi di in green _col(20) "``j'': " in yellow _col(30) %10.6f `beta'[`j',1]
+ }
+ di ""
+ noi di in green _col(20) "var1: " in yellow _col(30) %10.6f `beta'[`nbitems'+1,1]
+ if `Q'==2 {
+ noi di in green _col(20) "var2: " in yellow _col(30) %10.6f `beta'[`nbitems'+2,1]
+ tempname rho
+ scalar `rho'=`beta'[`nbitems'+3,1]/sqrt(`beta'[`nbitems'+1,1]*`beta'[`nbitems'+2,1])
+ noi di in green _col(20) "covar: " in yellow _col(30) %10.6f `beta'[`nbitems'+3,1]
+ }
+}
+di ""
+if "`ll'"!="" {
+ tempname noeuds poids
+ ghquadm `quad' `noeuds' `poids'
+ tempvar vrais logvrais P
+ qui gen `P'=0
+ qui gen `vrais'=0
+ if `Q'==1 {
+ forvalues u=1/`quad'{
+ tempvar vrais`u'
+ qui gen `vrais`u''=1/sqrt(_pi)
+ forvalues j=1/`nbitems' {
+ qui replace `P'=exp(`B'[`j',1]*sqrt(2*`beta'[`nbitems'+1,1])*`noeuds'[1,`u']-`beta'[`j',1])/(1+exp(`B'[`j',1]*sqrt(2*`beta'[`nbitems'+1,1])*`noeuds'[1,`u']-`beta'[`j',1]))
+ qui replace `P'=1-`P' if ``j''==0
+ qui replace `vrais`u''=`vrais`u''*`P'
+ }
+ qui replace `vrais'=`vrais'+`poids'[1,`u']*`vrais`u''
+ }
+ gen `logvrais'=log(`vrais')
+ qui su `logvrais'
+ local ll=r(N)*r(mean)
+ noi di in green _col(20) "ll: " in yellow _col(30) %12.4f `ll'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+ noi di in green _col(20) "AIC: " in yellow _col(30) %12.4f `AIC'
+ }
+
+ if `Q'==2 {
+ tempname sigma
+ matrix `sigma'=(`beta'[`nbitems'+1,1],`beta'[`nbitems'+3,1] \ `beta'[`nbitems'+3,1],`beta'[`nbitems'+2,1])
+ forvalues u=1/`quad'{
+ forvalues v=1/`quad'{
+ tempvar vraisu`u'v`v'
+ qui gen `vraisu`u'v`v''=1/_pi
+ forvalues j=1/`nbitems' {
+ local A1`u'tilde=sqrt(`beta'[`nbitems'+2,1]/(2*det(`sigma')))*`noeuds'[1,`u']
+ local A2`v'tilde=(`noeuds'[1,`v']-`beta'[`nbitems'+3,1]/sqrt(det(`sigma'))*`noeuds'[1,`u'])/(2*`beta'[`nbitems'+2,1])
+ qui replace `P'=exp(`B'[`j',1]*`A1`u'tilde'+`B'[`j',2]*`A2`v'tilde'-`beta'[`j',1])/(1+exp(`B'[`j',1]*`A1`u'tilde'+`B'[`j',2]*`A2`v'tilde'-`beta'[`j',1]))
+ qui replace `P'=1-`P' if ``j''==0
+ qui replace `vraisu`u'v`v''=`vraisu`u'v`v''*`P'
+ }
+ qui replace `vrais'=`vrais'+`poids'[1,`u']*`poids'[1,`v']*`vraisu`u'v`v''
+ }
+ }
+ qui gen `logvrais'=log(`vrais')
+ qui su `logvrais'
+ local ll=r(N)*r(mean)
+ noi di in green _col(20) "ll: " in yellow _col(27) %12.4f `ll'
+ local AIC=-2*`ll'+2*(`nbitems'+3)
+ noi di in green _col(20) "AIC: " in yellow _col(27) %12.4f `AIC'
+ }
+}
+if "`var'"=="" {
+ return matrix V `W'
+}
+matrix `beta'=`beta''
+return matrix b= `beta'
+
+if "`ll'"!="" {
+ return scalar ll= `ll'
+ return scalar AIC= `AIC'
+}
+
+return scalar J= `nbitems'
+return scalar N= `N'
+return scalar error=0
+
+restore
+end
+
diff --git a/Modules/ado/personal/g/geekel2d.hlp b/Modules/ado/personal/g/geekel2d.hlp
new file mode 100644
index 0000000..925e689
--- /dev/null
+++ b/Modules/ado/personal/g/geekel2d.hlp
@@ -0,0 +1,78 @@
+{smcl}
+{* 2july2005}{...}
+{hline}
+help for {hi:geekel2d}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Estimation of the parameters of undimensional and bidimensional IRT models}
+
+{p 8 14 12}{cmd:geekel2d} {it:varlist} [{cmd:,} {cmdab:coef}({it:matrixname}) {cmdab:nbit}({it:#}) {cmdab:critconv}({it:#}) {cmdab:ll} {cmdab:quad}({it:#}) {cmdab:novar}]
+
+{p 8 14 12}{it:varlist} is a list of two existing dichotomous variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:geekel2d} estimates, by Generalized Estimating
+Equations (GEE), the parameters of the model defined by Kelderman (1994) with
+one or two dimensions and dichotomic items. This model includes the Rasch model
+and the One Parameter Logistic Model (OPLM) for the unidimensional models, the
+Multidimensional Generalized Rasch Model (MGRM) and the Multidimensional
+Completely Sufficient Rasch Model (MMSRM) for the two-dimensional models.
+
+{title:Options}
+
+{p 4 8 2}{cmd:coef} is the name of a matrix which contains the coeficients B. This
+matrix relies the items and the latent traits. Each row represents an item and
+there is as many colmuns than the supposed number of latent traits (one or two).
+The coefficients are choosen, in general, among the first intergers, but
+{cmd:geekel2d} allows using real coefficients. By default, the Rasch model is
+supposed (the matrix {cmd: coef} is a vector of 1).
+
+{p 4 8 2}{cmd:nbit} defines the maximal number of iterations in the estimation
+algorithm. By default, this number is fixed to 30.
+
+{p 4 8 2}{cmd:critconv} is the value of the convergence criterion, calculated
+as the square of the cross-product of the vector containing the difference
+between two successive iterations of the parameters estimations. By default,
+this criterion is fixed to 1e-15.
+
+{p 4 8 2}{cmd:ll} estimates the marginal log-likelihood and the Akaike
+Information Criterion (AIC) by Gauss-Hermite quadratures.
+
+{p 4 8 2}{cmd:quad} defines the number of nodes of quadratures.
+
+{p 4 8 2}{cmd:novar} avoids to compute the standards errors of the estimators (faster).
+
+{title:Remarks}
+
+{p 4 8 2}For detailed informations on the Kelderman model, see Kelderman and
+Rijkes (1994) or Adams and al. (1997).
+
+{p 4 8 2}{cmd:geekel2d} don't allows using of polytomous items.
+
+{p 4 8 2}The {cmd:ghquadm} Stata module is needed (use {cmd:findit ghquadm} to obtain it).
+
+
+{title:Example}
+
+{p 4 8 2}{cmd:. geekel2d item1 item2 item3 item4} /*Rasch model*/
+
+{p 4 8 2}{cmd:. matrix B=(1,0\1,0\0,1\0,1)}
+
+{p 4 8 2}{cmd:. geekel2d item1 item2 item3 item4 , coef(B) nbit(50) critconv(1e-30)}
+
+
+{title:References}
+
+{p 4 8 2}Kelderman H. and Rijkes C. P. M., Loglinear multidimensional IRT models for polytomously scored items. {it:Psychometrika}, 1994, {it:59}, 149-176.
+
+{p 4 8 2}Adams R. J., Wilson M. R. and Wang W., The multidimensional random coefficient multinomial logit model. {it:Applied Psychological Measurement}, 1997, {it:21}, 1-23.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte
+Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France. You can contact the
+author at
+{browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+and visit the websites {browse "http://anaqol.free.fr":AnaQol}
+and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/g/geekel2d4.ado b/Modules/ado/personal/g/geekel2d4.ado
new file mode 100644
index 0000000..22d4adf
--- /dev/null
+++ b/Modules/ado/personal/g/geekel2d4.ado
@@ -0,0 +1,534 @@
+************************************************************************************************************
+* GEEkel2d: GEE for estimation of unidimensional or 2-dimensional Latent Trait models (Kelderman and Rijkes 1994)
+* Version 4 : June 8, 2004
+*
+* Historic:
+* Version 1 (2003-06-23): Jean-Benoit Hardouin
+* Version 2 (2003-08-13): Jean-Benoit Hardouin
+* version 3 (2003-11-06): Jean-Benoit Hardouin
+*
+* Use the ghquadm program (findit ghquadm)
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003, 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 GEEkel2d ,rclass
+version 7.0
+syntax varlist(min=2 numeric) [, coef(string) novar ll nbit(integer 30) critconv(real 1e-15) quad(integer 12)]
+
+preserve
+local nbitems: word count `varlist'
+tokenize `varlist'
+
+qui count
+local N=r(N)
+
+forvalues i=1/`nbitems' {
+qui drop if ``i''==.
+}
+
+qui count
+local Naf=r(N)
+
+di _col(3) in green "Initial step (N=" in yellow `Naf' in green ")"
+di _col(3) in yellow `=`N'-`Naf'' in green " observations are not used for missing values"
+di
+
+qui count
+local N=r(N)
+tempname B Q
+if "`coef'"!="" {
+matrix `B'=`coef'
+}
+else {
+matrix `B'=J(`nbitems',1,1)
+}
+
+scalar `Q'=colsof(`B')
+
+/* CALCUL INITIAUX DES PARAMETRES DELTA ET SIGMA ET DE LA MATRICE BETA*/
+
+local sigmath11=.25
+
+if `Q'==2 {
+local sigmath22=.25
+local sigmath12=0.125
+}
+
+tempname beta
+matrix `beta'=J(`nbitems'+`Q'*(`Q'+1)/2,1,0)
+forvalues j=1/`nbitems' {
+qui count if ``j''==1
+local s``j''=r(N)
+local delta``j''=-log(`s``j'''/(`N'-`s``j'''))
+matrix `beta'[`j',1]=`delta``j'''
+}
+
+
+forvalues j=1/`nbitems' {
+forvalues l=1/`nbitems' {
+quiet count if ``j''==1&``l''==1
+local s``j''``l''=r(N)
+}
+}
+
+if "`var'"==""{
+forvalues i=1/`nbitems' {
+forvalues j=1/`nbitems' {
+forvalues k=1/`nbitems' {
+quiet count if ``i''==1&``j''==1&``k''==1
+local s``i''``j''``k''=r(N)
+}
+}
+}
+
+forvalues i=1/`nbitems' {
+forvalues j=1/`nbitems' {
+forvalues k=1/`nbitems' {
+forvalues l=1/`nbitems' {
+quiet count if ``i''==1&``j''==1&``k''==1&``l''==1
+local s``i''``j''``k''``l''=r(N)
+}
+}
+}
+}
+
+}
+
+local l=`nbitems'+1
+matrix `beta'[`l',1]=`sigmath11'
+
+if `Q'==2 {
+local l=`nbitems'+2
+matrix `beta'[`l',1]=`sigmath22'
+
+local l=`nbitems'+3
+matrix `beta'[`l',1]=`sigmath12'
+}
+
+
+
+tempname variat V11 V12 V21 V22 D11 D12 D21 D22 V D
+matrix `variat'=(1)
+
+local compteur=0
+local conv=1
+
+
+/*********ITERATIONS******************/
+
+
+
+while (`variat'[1,1]>`critconv'&`compteur'<=`nbit'&`conv'==1) {
+
+if `compteur'==0{
+di in green _col(3) "First iteration"
+}
+else {
+di in green _col(3) "iteration:" in yellow _col(14) "`compteur'" in green _col(25) "Convergence index:" in yellow _col(44) %10.7e "`macrovariat'"
+}
+
+local compteur=`compteur'+1
+
+
+forvalues j=1/`nbitems' {
+
+/* CALCUL DES DERIVEES 1 A 6 POUR CHAQUE ITEM*/
+
+local l1``j''=1/(1+exp(`beta'[`j',1]))
+local l2``j''=exp(`beta'[`j',1])/(1+exp(`beta'[`j',1]))^2
+local l3``j''=exp(`beta'[`j',1])*(exp(`beta'[`j',1])-1)/(1+exp(`beta'[`j',1]))^3
+local l4``j''=exp(`beta'[`j',1])*(exp(2*`beta'[`j',1])-4*exp(`beta'[`j',1])+1)/(1+exp(`beta'[`j',1]))^4
+local l5``j''=exp(`beta'[`j',1])*(exp(3*`beta'[`j',1])-11*exp(2*`beta'[`j',1])+11*exp(`beta'[`j',1])-1)/(1+exp(`beta'[`j',1]))^5
+local l6``j''=exp(`beta'[`j',1])*(exp(4*`beta'[`j',1])-26*exp(3*`beta'[`j',1])+66*exp(2*`beta'[`j',1])-26*exp(`beta'[`j',1])+1)/(1+exp(`beta'[`j',1]))^6
+
+if `Q'==2 {
+local H2``j''=`B'[`j',1]^2*`sigmath11'+`B'[`j',1]*`B'[`j',2]*`sigmath12'+`B'[`j',2]^2*`sigmath22'
+local H4``j''=3*`B'[`j',1]^4*`sigmath11'^2+12*`B'[`j',1]^3*`B'[`j',2]*`sigmath11'*`sigmath12'+6*`B'[`j',1]^2*`B'[`j',2]^2*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+12*`B'[`j',1]*`B'[`j',2]^3*`sigmath22'*`sigmath12'+3*`B'[`j',2]^4*`sigmath22'^2
+}
+if `Q'==1 {
+local H2``j''=`B'[`j',1]^2*`sigmath11'
+local H4``j''=3*`B'[`j',1]^4*`sigmath11'^2
+}
+
+
+/* CALCUL DES MOMENTS D'ORDRE 1 ET 2 ET DE LA MATRICE V11*/
+
+local mu``j''=`l1``j'''+`H2``j'''/2*`l3``j'''+`H4``j'''/24*`l5``j'''
+local sigma``j''``j''=`l2``j'''+`H2``j'''/2*(`l3``j'''-2*`l1``j'''*`l3``j''')+`H4``j'''/24*(`l5``j'''-2*(`l3``j''')^2-2*`l1``j'''*`l5``j''')
+}
+
+
+matrix `V11'=J(`nbitems',`nbitems',0)
+
+forvalue j=1/`nbitems' {
+forvalue l=`j'/`nbitems' {
+
+if `j'!=`l' {
+if `Q'==2 {
+local H2``j''``l''=`B'[`j',1]*`B'[`l',1]*`sigmath11'+(`B'[`j',1]*`B'[`l',2]+`B'[`j',2]*`B'[`l',1])*`sigmath12'+`B'[`j',2]*`B'[`l',2]*`sigmath22'
+local H4``j''1``l''3=3*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'^2+3*(3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath11'*`sigmath12'+(3*`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+3*`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+3*(`B'[`j',1]*`B'[`l',2]^3+3*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]^2)*`sigmath22'*`sigmath12'+3*`B'[`j',2]*`B'[`l',2]^3*`sigmath22'^2
+local H4``j''2``l''2=3*`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'^2+6*(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath11'*`sigmath12'+(`B'[`j',1]^2*`B'[`l',2]^2+4*`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]+`B'[`j',2]^2*`B'[`l',1]^2)*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+6*(`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2+`B'[`j',2]^2*`B'[`l',1]*`B'[`l',2])*`sigmath22'*`sigmath12'+3*`B'[`j',2]^2*`B'[`l',2]^2*`sigmath22'^2
+local H4``j''3``l''1=3*`B'[`l',1]*`B'[`j',1]^3*`sigmath11'^2+3*(3*`B'[`l',1]*`B'[`j',1]^2*`B'[`j',2]+`B'[`l',2]*`B'[`j',1]^3)*`sigmath11'*`sigmath12'+(3*`B'[`l',1]*`B'[`j',1]*`B'[`j',2]^2+3*`B'[`l',2]*`B'[`j',1]^2*`B'[`j',2])*(`sigmath11'*`sigmath22'+2*`sigmath12'^2)+3*(`B'[`l',1]*`B'[`j',2]^3+3*`B'[`l',2]*`B'[`j',1]*`B'[`j',2]^2)*`sigmath22'*`sigmath12'+3*`B'[`l',2]*`B'[`j',2]^3*`sigmath22'^2
+}
+if `Q'==1 {
+local H2``j''``l''=`B'[`j',1]*`B'[`l',1]*`sigmath11'
+local H4``j''1``l''3=3*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'^2
+local H4``j''2``l''2=3*`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'^2
+local H4``j''3``l''1=3*`B'[`l',1]*`B'[`j',1]^3*`sigmath11'^2
+}
+
+
+local sigma``j''``l''=`H2``j''``l'''*(`l2``j'''*`l2``l''')+`H4``j''1``l''3'/6*`l2``j'''*`l4``l'''+`H4``j''3``l''1'/6*`l4``j'''*`l2``l'''+(`H4``j''2``l''2'-`H2``j'''*`H2``l''')/4*`l3``j'''*`l3``l'''
+
+
+}
+
+matrix `V11'[`j',`l']=`sigma``j''``l'''
+matrix `V11'[`l',`j']=`sigma``j''``l'''
+}
+}
+
+/* DEFINITION DE LA MATRICE COMPOCARRE*/
+
+tempname compocarre m
+local carre=`nbitems'*(`nbitems'-1)/2
+matrix `compocarre'=J(2,`carre',0)
+
+scalar `m'=0
+forvalue j=1/`nbitems' {
+local lbis=`j'+1
+forvalue l=`lbis'/`nbitems' {
+scalar `m'=`m'+1
+matrix `compocarre'[1,`m']=`j'
+matrix `compocarre'[2,`m']=`l'
+}
+}
+
+/* CALCUL DE LA MATRICE V22*/
+
+matrix `V22'=J(`carre',`carre',0)
+forvalue k=1/`carre' {
+local j=`compocarre'[1,`k']
+local l=`compocarre'[2,`k']
+
+matrix `V22'[`k',`k']=(1-2*`mu``j''')*(1-2*`mu``l''')*`sigma``j''``l'''+`sigma``j''``j'''*`sigma``l''``l'''-`sigma``j''``l'''^2
+}
+
+/* CALCUL DES MATRICES V12, V21 ET V*/
+
+matrix `V12'=J(`nbitems',`carre',0)
+forvalue k=1/`carre' {
+local j=`compocarre'[1,`k']
+local l=`compocarre'[2,`k']
+
+matrix `V12'[`j',`k']=(1-2*`mu``j''')*`sigma``j''``l'''
+matrix `V12'[`l',`k']=(1-2*`mu``l''')*`sigma``j''``l'''
+}
+matrix `V21'=`V12' '
+matrix `V'=(`V11',`V12' \ `V21',`V22')
+
+
+/*CALCUL DES MATRICES D11*/
+
+matrix `D11'=J(`nbitems',`nbitems',0)
+matrix `D12'=J(`nbitems',`Q'*(`Q'+1)/2,0)
+
+forvalue j=1/`nbitems' {
+matrix `D11'[`j',`j']=-`l2``j'''-`H2``j'''/2*`l4``j'''-`H4``j'''/24*`l6``j'''
+
+if `Q'==2 {
+matrix `D12'[`j',1]=`B'[`j',1]^2*`l3``j'''/2+(`B'[`j',1]^4*`sigmath11'+2*`B'[`j',1]^3*`B'[`j',2]*`sigmath12'+`B'[`j',1]^2*`B'[`j',2]^2*`sigmath22')/4*`l5``j'''
+matrix `D12'[`j',2]=`B'[`j',2]^2*`l3``j'''/2+(`B'[`j',2]^4*`sigmath22'+2*`B'[`j',2]^3*`B'[`j',1]*`sigmath12'+`B'[`j',2]^2*`B'[`j',1]^2*`sigmath11')/4*`l5``j'''
+matrix `D12'[`j',3]=`B'[`j',1]*`B'[`j',2]*`l3``j'''+(`B'[`j',1]^3*`B'[`j',2]*`sigmath11'+2*`B'[`j',1]^2*`B'[`j',2]^2*`sigmath12'+`B'[`j',1]*`B'[`j',2]^3*`sigmath22')/2*`l5``j'''
+}
+if `Q'==1 {
+matrix `D12'[`j',1]=`B'[`j',1]^2*`l3``j'''/2+`B'[`j',1]^4*`sigmath11'/4*`l5``j'''
+}
+}
+
+/*CALCUL DES MATRICES D21, D22 et D*/
+
+
+matrix `D21'=J(`carre',`nbitems',0)
+matrix `D22'=J(`carre',`Q'*(`Q'+1)/2,0)
+
+forvalue k=1/`carre' {
+local j=`compocarre'[1,`k']
+local l=`compocarre'[2,`k']
+
+matrix `D21'[`k',`j']=-`H2``j''``l'''*`l3``j'''*`l2``l'''-`H4``j''1``l''3'/6*`l3``j'''*`l4``l'''-`H4``j''3``l''1'/6*`l5``j'''*`l2``l'''-(`H4``j''2``l''2'-`H2``j'''*`H2``l''')/4*`l4``j'''*`l3``l'''
+matrix `D21'[`k',`l']=-`H2``j''``l'''*`l2``j'''*`l3``l'''-`H4``j''3``l''1'/6*`l4``j'''*`l3``l'''-`H4``j''1``l''3'/6*`l2``j'''*`l5``l'''-(`H4``j''2``l''2'-`H2``j'''*`H2``l''')/4*`l3``j'''*`l4``l'''
+
+if `Q'==2 {
+scalar tmp1=`B'[`j',1]*`B'[`l',1]*`l2``j'''*`l2``l'''+(2*`B'[`j',1]*`B'[`l',1]^3*`sigmath11'+(3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath12'+(`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*`sigmath22')/2*`l2``j'''*`l4``l'''
+scalar tmp2=(2*`B'[`j',1]^3*`B'[`l',1]*`sigmath11'+(3*`B'[`j',1]^2*`B'[`j',2]*`B'[`l',1]+`B'[`j',1]^3*`B'[`l',2])*`sigmath12'+(`B'[`j',1]*`B'[`j',2]^2*`B'[`l',1]+`B'[`j',1]^2*`B'[`j',2]*`B'[`l',2])*`sigmath22')/2*`l4``j'''*`l2``l'''
+scalar tmp3=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11'+(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath12'+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]*`sigmath22')*`l3``j'''*`l3``l'''
+
+matrix `D22'[`k',1]=tmp1+tmp2+tmp3
+
+scalar tmp1=`B'[`j',2]*`B'[`l',2]*`l2``j'''*`l2``l'''+(2*`B'[`j',2]*`B'[`l',2]^3*`sigmath22'+(3*`B'[`j',2]*`B'[`l',2]^2*`B'[`l',1]+`B'[`j',1]*`B'[`l',2]^3)*`sigmath12'+(`B'[`j',2]*`B'[`l',2]*`B'[`l',1]^2+`B'[`j',1]*`B'[`l',2]^2*`B'[`l',1])*`sigmath11')/2*`l2``j'''*`l4``l'''
+scalar tmp2=(2*`B'[`j',2]^3*`B'[`l',2]*`sigmath22'+(3*`B'[`j',2]^2*`B'[`j',1]*`B'[`l',2]+`B'[`j',2]^3*`B'[`l',1])*`sigmath12'+(`B'[`j',2]*`B'[`j',1]^2*`B'[`l',2]+`B'[`j',2]^2*`B'[`j',1]*`B'[`l',1])*`sigmath11')/2*`l4``j'''*`l2``l'''
+scalar tmp3=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath22'+(`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]^2)*`sigmath12'+`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]*`sigmath11')*`l3``j'''*`l3``l'''
+
+matrix `D22'[`k',2]=tmp1+tmp2+tmp3
+
+scalar tmp1=(`B'[`j',1]*`B'[`l',2]+`B'[`j',2]*`B'[`l',1])*`l2``j'''*`l2``l'''+((3*`B'[`j',1]*`B'[`l',1]^2*`B'[`l',2]+`B'[`j',2]*`B'[`l',1]^3)*`sigmath11'+4*(`B'[`j',1]*`B'[`l',1]*`B'[`l',2]^2+`B'[`j',2]*`B'[`l',1]^2*`B'[`l',2])*`sigmath12'+(`B'[`j',1]*`B'[`l',2]^3+3*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]^2)*`sigmath22')/2*`l2``j'''*`l4``l'''
+scalar tmp2=((3*`B'[`j',1]^2*`B'[`j',2]*`B'[`l',1]+`B'[`j',1]^3*`B'[`l',2])*`sigmath11'+4*(`B'[`j',1]*`B'[`j',2]^2*`B'[`l',1]+`B'[`j',1]^2*`B'[`j',2]*`B'[`l',2])*`sigmath12'+(`B'[`j',2]^3*`B'[`l',1]+3*`B'[`j',1]*`B'[`j',2]^2*`B'[`l',2])*`sigmath22')/2*`l4``j'''*`l2``l'''
+scalar tmp3=((`B'[`j',1]^2*`B'[`l',1]*`B'[`l',2]+`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2)*`sigmath11'+(`B'[`j',1]^2*`B'[`l',2]^2+2*`B'[`j',1]*`B'[`j',2]*`B'[`l',1]*`B'[`l',2]+`B'[`j',2]^2*`B'[`l',1]^2)*`sigmath12'+(`B'[`j',1]*`B'[`j',2]*`B'[`l',2]^2+`B'[`j',2]^2*`B'[`l',1]*`B'[`l',2])*`sigmath22')*`l3``j'''*`l3``l'''
+
+matrix `D22'[`k',3]=tmp1+tmp2+tmp3
+}
+if `Q'==1 {
+scalar tmp1=`B'[`j',1]*`B'[`l',1]*`l2``j'''*`l2``l'''+(2*`B'[`j',1]*`B'[`l',1]^3*`sigmath11')/2*`l2``j'''*`l4``l'''
+scalar tmp2=(2*`B'[`j',1]^3*`B'[`l',1]*`sigmath11')/2*`l4``j'''*`l2``l'''
+scalar tmp3=(`B'[`j',1]^2*`B'[`l',1]^2*`sigmath11')*`l3``j'''*`l3``l'''
+
+matrix `D22'[`k',1]=tmp1+tmp2+tmp3
+}
+}
+
+matrix `D'=(`D11',`D12' \ `D21',`D22')
+
+/*CALCUL DE LA MATRICE CHSI*/
+
+tempname chsi
+matrix `chsi'=J(`nbitems'+`carre',1,0)
+
+forvalue j=1/`nbitems' {
+matrix `chsi'[`j',1]=(`s``j'''-`N'*`mu``j''')/`N'
+}
+
+
+forvalue k=1/`carre' {
+local j=`compocarre'[1,`k']
+local l=`compocarre'[2,`k']
+local tmp=`nbitems'+`k'
+
+matrix `chsi'[`tmp',1]=(`s``j''``l'''-`s``j'''*`mu``l'''-`s``l'''*`mu``j'''+`N'*`mu``j'''*`mu``l'''-`N'*`sigma``j''``l''')/`N'
+}
+
+/*CALCUL DE L'ETAPE k*/
+tempname betaold
+matrix `betaold'=`beta'
+matrix `beta'=`betaold'+inv(`D''*inv(`V')*`D')*`D''*inv(`V')*`chsi'
+
+local l=`nbitems'+1
+local sigmath11=`beta'[`l',1]
+local l=`nbitems'+2
+local sigmath22=`beta'[`l',1]
+local l=`nbitems'+3
+local sigmath12=`beta'[`l',1]
+
+tempname epsilon variatold
+scalar `variatold'=`variat'[1,1]
+matrix `epsilon'=`betaold'-`beta'
+
+matrix `variat'=(`epsilon''*`epsilon')
+
+if `variat'[1,1]>`variatold' {
+matrix `beta'=`betaold'
+local l=`nbitems'+1
+local sigmath11=`beta'[`l',1]
+local l=`nbitems'+2
+local sigmath22=`beta'[`l',1]
+local l=`nbitems'+3
+local sigmath12=`beta'[`l',1]
+local conv=0
+}
+else {
+local macrovariat=`variat'[1,1]
+}
+
+}
+
+/*************************CALCUL des STANDARDS ERRORS DES PARAMETRES *********************/
+
+if "`var'"==""{
+tempname xicarreA xicarreB xicarreC xicarre
+matrix `xicarreA'=J(`nbitems',`nbitems',0)
+matrix `xicarreB'=J(`nbitems',`carre',0)
+matrix `xicarreC'=J(`carre',`carre',0)
+forvalues i=1/`nbitems' {
+forvalues j=1/`nbitems' {
+matrix `xicarreA'[`i',`j']=`s``i''``j'''-`s``i'''*`mu``j'''-`s``j'''*`mu``i'''+`N'*`mu``i'''*`mu``j'''
+}
+}
+
+forvalues i=1/`nbitems' {
+forvalues col=1/`carre' {
+local j=`compocarre'[1,`col']
+local k=`compocarre'[2,`col']
+matrix `xicarreB'[`i',`col']=`s``i''``j''``k'''-`mu``i'''*`s``j''``k'''-`mu``j'''*`s``i''``k'''-`mu``k'''*`s``i''``j'''+`mu``i'''*`mu``j'''*`s``k'''+`mu``i'''*`mu``k'''*`s``j'''+`mu``j'''*`mu``k'''*`s``i'''-`N'*`mu``i'''*`mu``j'''*`mu``k'''-`sigma``j''``k'''*`s``i'''+`N'*`mu``i'''*`sigma``j''``k'''
+}
+}
+
+forvalues row=1/`carre' {
+forvalues col=1/`carre' {
+local i=`compocarre'[1,`row']
+local j=`compocarre'[2,`row']
+local k=`compocarre'[1,`col']
+local l=`compocarre'[2,`col']
+matrix `xicarreC'[`row',`col']=`s``i''``j''``k''``l'''-`mu``i'''*`s``j''``k''``l'''-`mu``j'''*`s``i''``k''``l'''-`mu``k'''*`s``i''``j''``l'''-`mu``l'''*`s``i''``j''``k'''+`mu``i'''*`mu``j'''*`s``k''``l'''+`mu``i'''*`mu``k'''*`s``j''``l'''+`mu``i'''*`mu``l'''*`s``j''``k'''+`mu``j'''*`mu``k'''*`s``i''``l'''+`mu``j'''*`mu``l'''*`s``i''``k'''+`mu``k'''*`mu``l'''*`s``i''``j'''-`mu``i'''*`mu``j'''*`mu``k'''*`s``l'''-`mu``i'''*`mu``j'''*`mu``l'''*`s``k'''-`mu``i'''*`mu``k'''*`mu``l'''*`s``j'''-`mu``j'''*`mu``k'''*`mu``l'''*`s``i'''-`sigma``i''``j'''*`s``k''``l'''-`sigma``k''``l'''*`s``i''``j'''+`sigma``i''``j'''*`mu``k'''*`s``l'''+`sigma``i''``j'''*`mu``l'''*`s``k'''+`sigma``k''``l'''*`mu``i'''*`s``j'''+`sigma``k''``l'''*`mu``j'''*`s``i'''+`N'*`mu``i'''*`mu``j'''*`mu``k'''*`mu``l'''-`N'*`sigma``i''``j'''*`mu``k'''*`mu``l'''-`N'*`sigma``k''``l'''*`mu``i'''*`mu``j'''+`N'*`sigma``i''``j'''*`sigma``k''``l'''
+}
+}
+
+
+matrix `xicarre'=(`xicarreA',`xicarreB' \ `xicarreB' ',`xicarreC')
+
+tempname A1 A2 W
+matrix `A1'=`D' '*inv(`V')*`D'
+matrix `A2'=`D' '*inv(`V')*`xicarre'*inv(`V')*`D'
+matrix `W'=1/`N'^2*inv(`A1')*`A2'*inv(`A1')
+
+}
+
+/*****************************DISPLAY THE RESULTS***************************************/
+
+
+local compteur=`compteur'-1
+di ""
+di ""
+if `compteur'==0 {
+noi di in red _col(8) "The algorithm can not converge"
+return scalar error=1
+exit
+}
+if `variat'[1,1]<=`critconv'&`compteur'>0 {
+noi di in green _col(8) "The algorithm converge at the `compteur'th iteration"
+}
+if `compteur'==`nbit'&`variat'[1,1]>`critconv' {
+noi di in green _col(8) "The algorithm is stopped at the `compteur'th iteration"
+}
+if `conv'==0&`compteur'>0 {
+noi di in green _col(8) "The algorithm converge no more after the `compteur'th iteration"
+}
+di ""
+if "`var'"=="" {
+noi di in green _col(30) "Parameters" in green _col(43) "Standard errors"
+forvalue j=1/`nbitems' {
+noi di in green _col(20) "``j'': " in yellow _col(30) %10.6f `beta'[`j',1] in yellow _col(50) %8.6f sqrt(`W'[`j',`j'])
+}
+di ""
+noi di in green _col(20) "var1: " in yellow _col(30) %10.6f `beta'[`nbitems'+1,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+1,`nbitems'+1])
+if `Q'==2 {
+noi di in green _col(20) "var2: " in yellow _col(30) %10.6f `beta'[`nbitems'+2,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+2,`nbitems'+2])
+scalar rho=`beta'[`nbitems'+3,1]/sqrt(`beta'[`nbitems'+1,1]*`beta'[`nbitems'+2,1])
+noi di in green _col(20) "covar: " in yellow _col(30) %10.6f `beta'[`nbitems'+3,1] in yellow _col(50) %8.6f sqrt(`W'[`nbitems'+3,`nbitems'+3]) " (rho=" %5.4f rho ")"
+}
+}
+else {
+noi di in green _col(30) "Parameters"
+forvalue j=1/`nbitems' {
+noi di in green _col(20) "``j'': " in yellow _col(30) %10.6f `beta'[`j',1]
+}
+di ""
+noi di in green _col(20) "var1: " in yellow _col(30) %10.6f `beta'[`nbitems'+1,1]
+if `Q'==2 {
+noi di in green _col(20) "var2: " in yellow _col(30) %10.6f `beta'[`nbitems'+2,1]
+scalar rho=`beta'[`nbitems'+3,1]/sqrt(`beta'[`nbitems'+1,1]*`beta'[`nbitems'+2,1])
+noi di in green _col(20) "covar: " in yellow _col(30) %10.6f `beta'[`nbitems'+3,1]
+}
+}
+di ""
+
+
+
+if "`ll'"!="" {
+if `Q'==1 {
+tempname noeuds poids
+ghquadm `quad' `noeuds' `poids'
+tempvar vrais logvrais
+qui gen `vrais'=0
+forvalues u=1/`quad'{
+tempvar vrais`u'
+qui gen `vrais`u''=1/sqrt(_pi)
+forvalues j=1/`nbitems' {
+tempvar Pu`u'j`j'
+qui gen `Pu`u'j`j''=exp(`B'[`j',1]*sqrt(2*`beta'[`nbitems'+1,1])*`noeuds'[1,`u']-`beta'[`j',1])/(1+exp(`B'[`j',1]*sqrt(2*`beta'[`nbitems'+1,1])*`noeuds'[1,`u']-`beta'[`j',1]))
+qui replace `Pu`u'j`j''=1-`Pu`u'j`j'' if ``j''==0
+qui replace `vrais`u''=`vrais`u''*`Pu`u'j`j''
+}
+qui replace `vrais'=`vrais'+`poids'[1,`u']*`vrais`u''
+}
+gen `logvrais'=log(`vrais')
+qui su `logvrais'
+local ll=r(N)*r(mean)
+noi di in green _col(20) "ll: " in yellow _col(30) %12.4f `ll'
+local AIC=-2*`ll'+2*(`nbitems'+1)
+noi di in green _col(20) "AIC: " in yellow _col(30) %12.4f `AIC'
+}
+
+if `Q'==2 {
+
+tempname noeuds poids
+ghquadm `quad' `noeuds' `poids'
+tempvar vrais logvrais
+qui gen `vrais'=0
+matrix sigma=(`beta'[`nbitems'+1,1],`beta'[`nbitems'+3,1] \ `beta'[`nbitems'+3,1],`beta'[`nbitems'+2,1])
+forvalues u=1/`quad'{
+forvalues v=1/`quad'{
+tempvar vraisu`u'v`v'
+qui gen `vraisu`u'v`v''=1/_pi
+forvalues j=1/`nbitems' {
+tempvar Pu`u'v`v'j`j'
+local A1`u'tilde=sqrt(`beta'[`nbitems'+2,1]/(2*det(sigma)))*`noeuds'[1,`u']
+local A2`v'tilde=(`noeuds'[1,`v']-`beta'[`nbitems'+3,1]/sqrt(det(sigma))*`noeuds'[1,`u'])/(2*`beta'[`nbitems'+2,1])
+qui gen `Pu`u'v`v'j`j''=exp(`B'[`j',1]*`A1`u'tilde'+`B'[`j',2]*`A2`v'tilde'-`beta'[`j',1])/(1+exp(`B'[`j',1]*`A1`u'tilde'+`B'[`j',2]*`A2`v'tilde'-`beta'[`j',1]))
+qui replace `Pu`u'v`v'j`j''=1-`Pu`u'v`v'j`j'' if ``j''==0
+qui replace `vraisu`u'v`v''=`vraisu`u'v`v''*`Pu`u'v`v'j`j''
+}
+qui replace `vrais'=`vrais'+`poids'[1,`u']*`poids'[1,`v']*`vraisu`u'v`v''
+}
+}
+qui gen `logvrais'=log(`vrais')
+qui su `logvrais'
+local ll=r(N)*r(mean)
+noi di in green _col(20) "ll: " in yellow _col(27) %12.4f `ll'
+local AIC=-2*`ll'+2*(`nbitems'+3)
+noi di in green _col(20) "AIC: " in yellow _col(27) %12.4f `AIC'
+}
+}
+
+if "`var'"=="" {
+return matrix W= `W'
+}
+return matrix beta= `beta'
+
+if "`ll'"!="" {
+return scalar ll= `ll'
+return scalar AIC= `AIC'
+}
+
+return scalar J= `nbitems'
+return scalar N= `N'
+
+return scalar error=0
+
+restore
+
+
+
+end
+
diff --git a/Modules/ado/personal/g/gengroup.ado b/Modules/ado/personal/g/gengroup.ado
new file mode 100644
index 0000000..c4d8e02
--- /dev/null
+++ b/Modules/ado/personal/g/gengroup.ado
@@ -0,0 +1,158 @@
+*! version 1.3 1 June 2013
+*! Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Stata program : genscore
+* Generate groups of individals based on the values of an ordinal or continuous variable
+*
+* Historic
+* Version 1 (2007-05-27): Jean-Benoit Hardouin
+* Version 1.1 (2007-06-21): Jean-Benoit Hardouin /*Correction of a bug without -if- */
+* Version 1.2 (2009-10-28): Jean-Benoit Hardouin /*-continuous- option*/
+* Version 1.3 (2013-06-01): Jean-Benoit Hardouin /*Correction in presence of missing values*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* EA4275 - SPHERE
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2007, 2009, 2013 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 gengroup ,rclas
+version 7.0
+syntax varlist(numeric min=1 max=1) [if/] [in] [, NEWvariable(namelist min=1 max=1) REPlace MINsize(integer 30) DETails CONTinuous]
+tempvar sort
+qui gen `sort'=_n
+
+if "`if'"!="" {
+ local if2="if `if'"
+ local if3="&(`if')"
+}
+
+marksample touse
+if "`newvariable'"=="" {
+ local newvariable group
+}
+
+capture confirm new variable `newvariable'
+if _rc!=0&"`replace'"=="" {
+ di in red "The variable {hi:`newvariable'} is already defined"
+ exit 198
+}
+else if _rc!=0&"`replace"!="" {
+ qui drop `newvariable'
+}
+
+if "`continuous'"=="" {
+ qui gen `newvariable'=`varlist' `if2' `in'
+
+ qui su `newvariable' `if2' `in'
+ local min=r(min)
+ local max=r(max)
+
+ local groupmin=`min'
+ local groupmax=`min'-1
+ local numgroup=1
+ local recode
+ local list
+
+ while (`groupmin'<`max'+1) {
+ local n=0
+ while (`n'<`minsize') {
+ local groupmax=`groupmax'+1
+ qui count if `newvariable'>=`groupmin'&`newvariable'<=`groupmax'`if3' `in'
+ local n=r(N)
+ if `groupmax'>`max' {
+ local n=`minsize'+1
+ local numgr
+ }
+ }
+ if `groupmax'<`max' {
+ local list `list' `groupmax'
+ }
+ local recode `recode' `groupmin'/`groupmax'=`numgroup'
+ if "`details'"!="" {
+ di in gr "Group " in ye `numgroup' in gr ": Values " in ye `groupmin' in gr " to " in ye `groupmax'
+ }
+ local groupmin=`groupmax'+1
+ local groupmax=`groupmin'-1
+ local numgroup=`numgroup'+1
+ }
+
+ qui recode `newvariable' `recode' `if2' `in'
+ qui count if `newvariable'==`numgroup'-1`if3' `in'
+ local dernier=r(N)
+ if `dernier'<`minsize' {
+ qui recode `newvariable' `=`numgroup'-1'=`=`numgroup'-2' `if2' `in'
+ if "`details'"!="" {
+ di in gr "The group " in ye `=`numgroup'-1' in gr " is recoded in " in ye `=`numgroup'-2'
+ }
+ local list2
+ forvalues i=1/`=`numgroup'-3' {
+ local w:word `i' of `list'
+ local list2 `list2' `w'
+ }
+ local list `list2'
+ }
+}
+else {
+ local list
+ qui sort `varlist'
+ qui tempvar sort2
+ qui gen `sort2'=_n
+ qui gen `newvariable'=0 `if2' `in'
+ qui replace `newvariable'=. if `varlist'==.
+ qui count if `varlist'!=.`if3' `in'
+ local nbind=r(N)
+ local tmpgp=floor(`nbind'/`minsize')
+ local minsize=floor(`nbind'/`tmpgp')
+ local nbused=0
+ tempvar used
+ qui gen `used'=0 `if2' `in'
+ local num=1
+ while (`=`nbused'+`minsize''<`nbind'+1) {
+ qui su `varlist' if `sort2'==`=`nbused'+`minsize''`if3' `in'
+ local mean=r(mean)
+ local list `list' `mean'
+ local mean=round(`mean',0.0000001)+0.0000001
+ if "`details'"!="" {
+ di in gr "The values inferior to " in ye `mean' in gr " are recoded in " in ye `num'
+ }
+ qui replace `newvariable'=`num' if `varlist'<=`mean'&`used'==0
+ qui replace `used'=1 if `newvariable'!=0&`newvariable'!=.
+ qui count if `used'==1
+ local nbused=`r(N)'
+ local num=`num'+1
+ }
+ qui replace `newvariable'=`num'-1 if `newvariable'==0
+ if "`details'"!="" {
+ qui su `varlist'
+ local max=r(max)
+ if `max'>`mean' {
+ di in gr "Individuals between " in ye `mean' in gr "and " in ye `max' " are recoded in " in ye `=`num'-1'
+ }
+ }
+ qui sort `sort'
+}
+return local list `list'
+end
diff --git a/Modules/ado/personal/g/gengroup.hlp b/Modules/ado/personal/g/gengroup.hlp
new file mode 100644
index 0000000..6df3377
--- /dev/null
+++ b/Modules/ado/personal/g/gengroup.hlp
@@ -0,0 +1,51 @@
+{smcl}
+{* 6May2013}{...}
+{hline}
+help for {hi:gengroup}{right:Jean-benoit Hardouin}
+{hline}
+
+{title:Module to generate group of individuals based on a ordinal or continuous variable}
+
+{p 8 14 2}{cmd:gengroup} {it:varname} [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [{cmd:,} {cmdab:new:variable}({it:newvarname}) {cmdab:rep:lace} {cmdab:min:size}(#) {cmdab:det:ails} {cmdab:cont:inuous}]
+
+{title:Description}
+
+{p 4 8 2}{cmd:gengroup} creates groups of individuals by using the values of an ordinal or continuous variable.
+The module creates groups by recoding several adjacent values of the variable, until obtaining groups with more than individuals than the number defined in the {cmd:minsize} option.
+
+
+{title:Options}
+
+{p 4 8 2}{cmd:newvariable} defines the name of the new variable ({it:group} by default).
+
+{p 4 8 2}{cmd:replace} replaces the variable defined in the {cmd:newvariable} option if it already exists.
+
+{p 4 8 2}{cmd:minsize} defines the minimal number of individuals in each group (30 by default).
+
+{p 4 8 2}{cmd:details} diplays the composition of each group.
+
+{p 4 8 2}{cmd:continuous} allows handling a continuous variable.
+
+{title:Examples}
+
+{p 4 8 2}{inp:. gengroup score}
+
+{p 4 8 2}{inp:. gengroup score, newvariable(grouptocreate) replace minsize(80)}
+
+{p 4 8 2}{inp:. gengroup score, details}
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help egen}, {help generate} and {help genscore} if installed.{p_end}
+
diff --git a/Modules/ado/personal/g/gengutt.ado b/Modules/ado/personal/g/gengutt.ado
new file mode 100644
index 0000000..476f5d5
--- /dev/null
+++ b/Modules/ado/personal/g/gengutt.ado
@@ -0,0 +1,133 @@
+*! Version 1.1 24 March 2015
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : gengutt
+* Generation of Guttman's error per individuals
+* Release 1.1 : March 24, 2015 /*no required -order- option*/
+*
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Release 1 : March 20, 2015 /*initial version with only -order- option*/
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2015 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 gengutt , rclass
+syntax varlist(min=2 numeric) [if] , Gen(string) [ Replace Order(string) PAIRWise] /*[,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]*/
+preserve
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+local nbs=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ local modamax`i'=r(max)
+ local nbs=`nbs'+`modamax`i''
+ local testmodamax`i'=0
+ local ordermax`i'=0
+}
+if "`order'"=="" {
+ tempname mattmp
+ matrix `mattmp'=J(3,`nbs',0)
+ local col=1
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`modamax`i'' {
+ qui count if ``i''>=`s'
+ matrix `mattmp'[3,`col']=r(N)
+ matrix `mattmp'[1,`col']=`i'
+ matrix `mattmp'[2,`col']=`s'
+ local ++col
+ }
+ }
+ local list
+ forvalues j=1/`nbs' {
+ local max=0
+ local col=0
+ local item=0
+ forvalues i=1/`nbs' {
+ if `mattmp'[3,`i']>`max' {
+ local max=`mattmp'[3,`i']
+ local col=`i'
+ local item=`mattmp'[1,`i']
+ }
+ }
+ local list `list' `item'
+ matrix `mattmp'[3,`col']=0
+ }
+ local order `list'
+}
+local nbsteps: word count `order'
+tempname matorder
+matrix `matorder'=J(3,`nbsteps',0)
+local defordre=1
+forvalues i=1/`nbsteps' {
+ local tmp: word `i' of `order'
+ local ++testmodamax`tmp'
+ matrix `matorder'[1,`i']=`tmp'
+ local ordermax`tmp'=`ordermax`tmp''+1
+ matrix `matorder'[2,`i']=`ordermax`tmp''
+ local i`tmp'_m`ordermax`tmp''=`defordre'
+ local s`defordre' i`tmp'_m`ordermax`tmp''
+ tempname `s`defordre''
+ qui gen ``s`defordre'''=``tmp''>=`ordermax`tmp''
+ local ++defordre
+}
+local error=0
+forvalues i=1/`nbitems' {
+ if `modamax`i''>`testmodamax`i'' {
+ di in red "The item `i' presents more answer categories than defined in the -order- option "
+ local error=1
+ }
+}
+if `error'!=0 {
+ error 198
+}
+if "`replace'"!="" {
+ qui capture drop `gen'
+}
+qui gen `gen'=0
+forvalues i=1/`nbitems' {
+ if "`replace'"!="" {
+ qui capture drop `gen'_``i''
+ }
+ qui gen `gen'_``i''=0
+}
+forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ qui replace `gen'=`gen'+1 if ``s`i'''<``s`j'''&``s`i'''!=.&``s`j'''!=.
+ local iti=`matorder'[1,`i']
+ local itj=`matorder'[1,`j']
+ qui replace `gen'_``iti''=`gen'_``iti''+1 if ``s`i'''<``s`j'''&``s`i'''!=.&``s`j'''!=.
+ qui replace `gen'_``itj''=`gen'_``itj''+1 if ``s`i'''<``s`j'''&``s`i'''!=.&``s`j'''!=.
+ }
+}
+if "`replace'"!="" {
+ capture drop `gen'_gp
+}
+egen `gen'_gp=concat(``s1''-``s`nbsteps''')
+
+capture restore, not
+end
+
diff --git a/Modules/ado/personal/g/genscore.ado b/Modules/ado/personal/g/genscore.ado
new file mode 100644
index 0000000..e3164e4
--- /dev/null
+++ b/Modules/ado/personal/g/genscore.ado
@@ -0,0 +1,86 @@
+*! version 1.4 27december2005
+*! Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Stata program : genscore
+* Generate scores from a list of variables
+* Version 1.4 : December 27, 2005 /*corrects a bug with the mean option*/
+*
+* Historic
+* Version 1.2 (2005-10-01): Jean-Benoit Hardouin
+* Version 1.3 (2005-12-09): Jean-Benoit Hardouin /*centered and standardized options*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005 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 genscore
+version 7.0
+syntax varlist(min=1) [if] [in] [fweight] [, SCore(namelist min=1 max=1) CENTered STAndardized MEan MIssing(string) REPlace]
+
+marksample touse
+if "`score'"=="" {
+ local score score
+}
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+if "`missing'"=="" {
+ local missing .
+}
+capture confirm new variable `score'
+quietly {
+ if _rc!=0&"`replace"=="" {
+ di in red "The variable {hi:`score'} already defined"
+ exit 198
+ }
+ else if _rc!=0&"`replace"!="" {
+ drop `score'
+ }
+ forvalues i=1/`nbitems' {
+ tempname var`i'
+ local sd=1
+ local moy=0
+ if "`standardized'"!=""|"`centered'"!="" {
+ su ``i'' [`weight'`exp']
+ local moy=r(mean)
+ local sd=r(sd)
+ if "`standardized'"=="" {
+ local sd=1
+ }
+ }
+ gen `var`i''=(``i''-`moy')/`sd'
+ }
+ gen `score'=0 if `touse'
+ forvalues i=1/`nbitems' {
+ replace `score'=`score'+`var`i'' if `touse'
+ replace `score'=. if `touse'&``i''==`missing'&``i''>=.
+ }
+ if "`mean'"!="" {
+ replace `score'=`score'/`nbitems' if `touse'
+ }
+}
+
+end
+
diff --git a/Modules/ado/personal/g/genscore.hlp b/Modules/ado/personal/g/genscore.hlp
new file mode 100644
index 0000000..182da15
--- /dev/null
+++ b/Modules/ado/personal/g/genscore.hlp
@@ -0,0 +1,54 @@
+{smcl}
+{* 9december2005}{...}
+{hline}
+help for {hi:genscore}{right:Jean-benoit Hardouin}
+{hline}
+
+{title:Module to generate a score}
+
+{p 8 14 2}{cmd:genscore} {it:varlist} [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [{it:weights}] [{cmd:,} {cmdab:sc:ore}({it:newvarname}) {cmdab:me:an} {cmdab:cent:ered} {cmdab:sta:ndardized} {cmdab:mi:ssing}(string) {cmdab:rep:lace}]
+
+{title:Description}
+
+{p 4 8 2}{cmd:genscore} allows creating a new variable containing the score
+computed as the sum (or the mean) of the responses to the variables defined in
+{it:varlist}. Variables of {it:varlist} can be centered or standardized. The new
+variable will contain a missing value for each individual with at least one
+missing values among the variables of {it:varlist}.
+
+{p 4 8 2}Only {cmd:fweights} are allowed, and the weights have an influence only with
+the {cmd:centered} or {cmd:standardized} options.
+
+{title:Options}
+
+{p 4 8 2}{cmd:score} defines the name of the new variable ({it:score} by default).
+
+{p 4 8 2}{cmd:mean} allows obtaining a mean score (the sum of the responses is divided by the number of variables).
+
+{p 4 8 2}{cmd:centered} computes the scores with centered variables.
+
+{p 4 8 2}{cmd:standardized} computes the scores with standardized variables.
+
+{p 4 8 2}{cmd:missing} defines a specific modality of the variables which can be considered as a missing value.
+
+{p 4 8 2}{cmd:replace} allows replacing the variable defined in the {cmd:score} option if it already exists.
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. genscore turn trunk mpg [fweight=w],standardized mean}
+
+{p 4 8 2}{cmd:. genscore item1-item20, score(totscore) missing(9)}
+
+{p 4 8 2}{cmd:. genscore var*, score(scorevar) replace}
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte
+Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France. You can contact the author at
+{browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+and visit the websites {browse "http://anaqol.free.fr":AnaQol} and
+{browse "http://freeirt.free.fr":FreeIRT}
+
+{title:Also see}
+
+{p 4 8 2}Online: help for {help egen}, {help generate} and {help mvdecode}{p_end}
diff --git a/Modules/ado/personal/g/guttmax.ado b/Modules/ado/personal/g/guttmax.ado
new file mode 100644
index 0000000..ed75ab6
--- /dev/null
+++ b/Modules/ado/personal/g/guttmax.ado
@@ -0,0 +1,181 @@
+*! Version 1 19 November 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : guttmax
+* Research of the maximal number of Guttman Errors for a specific score
+*
+* Historic :
+* Version 1 (November 19, 2008) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2008 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 guttmax , rclass
+version 10
+syntax anything [,Score(real -1) Response(string)]
+
+if `score'!=-1&"`response'"!="" {
+ di in red "You cannot defined in the same time the score and the response options";
+ error 198
+}
+
+
+local step:word count `anything'
+local nbitems=0
+forvalues i=1/`step' {
+ local step`i':word `i' of `anything'
+ if `step`i''>`nbitems' {
+ local nbitems=`step`i''
+ }
+}
+di in green "Number of steps: " in ye `step'
+di in green "Number of items: " in ye `nbitems'
+tempname mate
+matrix `mate'=J(1,`step',0)
+
+
+if `score'!=-1 {
+ if `score'>`step' {
+ di in red "You cannot defined a score greater to the maximal possible score";
+ error 198
+ }
+ di in green "Score: " in ye `score'
+ local maxstep=0
+ forvalues i=1/`nbitems' {
+ local nstep`i'=0
+ forvalues j=1/`step' {
+ if `step`j''==`i' {
+ local ++nstep`i'
+ if `nstep`i''>`maxstep' {
+ local maxstep=`nstep`i''
+ }
+ }
+ }
+ }
+
+ tempname calcul
+ matrix `calcul'=J(`nbitems',`maxstep',0)
+ *matrix list `calcul'
+ forvalues i=1/`nbitems' {
+ *di "item `i'"
+ local n=1
+ forvalues j=1/`step' {
+ if `step`j''==`i' {
+ forvalues s=`n'/`nstep`i'' {
+ matrix `calcul'[`i',`s']=`calcul'[`i',`s']+`j'
+ matrix list `calcul'
+ }
+ local ++n
+ }
+ }
+ forvalues j=2/`nstep`i'' {
+ matrix `calcul'[`i',`j']=`calcul'[`i',`j']/`j'
+ di "j=`j'"
+ matrix list `calcul'
+ }
+ }
+ *matrix list `calcul'
+
+ while (`score'>0) {
+ local max=0
+ forvalues i=1/`nbitems' {
+ local s=min(`score',`nstep`i'')
+ *di "forvalues j=1/`s' {"
+ forvalues j=1/`s' {
+ if `calcul'[`i',`j']>`max' {
+ local maxi=`i'
+ local maxj=`j'
+ local max=`calcul'[`i',`j']
+ }
+ }
+ }
+ *di "maxi=`maxi' maxj=`maxj'"
+ local d=0
+ forvalues l=1/`step' {
+ if `step`l''==`maxi'&`mate'[1,`l']==0&`d'<=`maxj' {
+ matrix `mate'[1,`l']=1
+ local ++d
+ }
+ }
+ forvalues l=1/`maxj' {
+ matrix `calcul'[`maxi',`l']=0
+ }
+ local score=`score'-`maxj'
+ *matrix list `calcul'
+ }
+}
+else { /*if reponse*/
+ local nbrep: word count `response'
+ if `nbrep'!=`nbitems' {
+ di in red "You cannot defined a number of responses different of the number of items";
+ error 198
+ }
+
+ tempname cpt
+ qui matrix `cpt'=J(`nbitems',1,0)
+ forvalues i=1/`nbitems' {
+ local rep`i':word `i' of `response'
+ qui matrix `cpt'[`i',1]=`rep`i''
+ }
+ forvalues i=1/`step' {
+ if `cpt'[`step`i'',1]>0 {
+ qui matrix `mate'[1,`i']=1
+ qui matrix `cpt'[`step`i'',1]=`cpt'[`step`i'',1]-1
+ }
+ else {
+ qui matrix `mate'[1,`i']=0
+ }
+ }
+}
+local emax=0
+
+forvalue i=1/`step' {
+ forvalues j=`=`i'+1'/`step' {
+ if `mate'[1,`i']==0&`mate'[1,`j']==1 {
+ local ++emax
+ }
+ }
+}
+
+
+if `score'!=-1 {
+ di in green "Responses profile generating the most important number of Guttman error"
+ matrix list `mate' ,noheader nonames
+ di in green "Max number of Guttman errors : " in ye `emax'
+}
+else {
+ di in green "Responses profile"
+ matrix list `mate' ,noheader nonames
+ di in green "Number of Guttman errors : " in ye `emax'
+}
+return scalar maxegutt =`emax'
+end
diff --git a/Modules/ado/personal/g/guttmax1.ado b/Modules/ado/personal/g/guttmax1.ado
new file mode 100644
index 0000000..5f8a3a1
--- /dev/null
+++ b/Modules/ado/personal/g/guttmax1.ado
@@ -0,0 +1,136 @@
+*! Version 1 19 November 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : guttmax
+* Research of the maximal number of Guttman Errors for a specific score
+*
+* Historic :
+* Version 1 (November 19, 2008) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2008 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 guttmax1 , rclass
+version 10
+syntax anything [,Score(int 0)]
+
+
+local step:word count `anything'
+local nbitems=0
+forvalues i=1/`step' {
+ local step`i':word `i' of `anything'
+ if `step`i''>`nbitems' {
+ local nbitems=`step`i''
+ }
+}
+di in green "Number of steps: " in ye `step'
+di in green "Number of items: " in ye `nbitems'
+di in green "Score: " in ye `score'
+
+tempname mate
+matrix `mate'=J(1,`step',0)
+
+local maxstep=0
+forvalues i=1/`nbitems' {
+ local nstep`i'=0
+ forvalues j=1/`step' {
+ if `step`j''==`i' {
+ local ++nstep`i'
+ if `nstep`i''>`maxstep' {
+ local maxstep=`nstep`i''
+ }
+ }
+ }
+}
+
+tempname calcul
+matrix `calcul'=J(`nbitems',`maxstep',0)
+*matrix list `calcul'
+forvalues i=1/`nbitems' {
+*di "item `i'"
+ local n=1
+ forvalues j=1/`step' {
+ if `step`j''==`i' {
+ forvalues s=`n'/`nstep`i'' {
+ matrix `calcul'[`i',`s']=`calcul'[`i',`s']+`j'
+ }
+ local ++n
+ }
+ }
+ forvalues j=2/`nstep`i'' {
+ matrix `calcul'[`i',`j']=`calcul'[`i',`j']/`j'
+ }
+}
+*matrix list `calcul'
+
+while (`score'>0) {
+ local max=0
+ forvalues i=1/`nbitems' {
+ local s=min(`score',`nstep`i'')
+ *di "forvalues j=1/`s' {"
+ forvalues j=1/`s' {
+ if `calcul'[`i',`j']>`max' {
+ local maxi=`i'
+ local maxj=`j'
+ local max=`calcul'[`i',`j']
+ }
+ }
+ }
+ *di "maxi=`maxi' maxj=`maxj'"
+ local d=0
+ forvalues l=1/`step' {
+ if `step`l''==`maxi'&`mate'[1,`l']==0&`d'<=`maxj' {
+ matrix `mate'[1,`l']=1
+ local ++d
+ }
+ }
+ forvalues l=1/`maxj' {
+ matrix `calcul'[`maxi',`l']=0
+ }
+ local score=`score'-`maxj'
+ *matrix list `calcul'
+}
+local emax=0
+forvalue i=1/`step' {
+ forvalues j=`=`i'+1'/`step' {
+ if `mate'[1,`i']==0&`mate'[1,`j']==1 {
+ local ++emax
+ }
+ }
+}
+
+
+di in green "Responses profile generating the most important number of Guttman error"
+matrix list `mate' ,noheader nonames
+di in green "Max number of Guttman errors : " in ye `emax'
+return scalar maxegutt =`emax'
+end
diff --git a/Modules/ado/personal/grec/r.grec b/Modules/ado/personal/grec/r.grec
new file mode 100644
index 0000000..6adc2c8
--- /dev/null
+++ b/Modules/ado/personal/grec/r.grec
@@ -0,0 +1,25 @@
+StataFileTM:00001:01100:GREC: :
+00008:00008:00001:
+*! classname: twowaygraph_g
+*! family: twoway
+*! date: 8 Jul 2023
+*! time: 23:18:16
+*! graph_scheme: stcolor
+*! naturallywhite: 1
+*! end
+
+// File created by Graph Editor Recorder.
+// Edit only if you know what you are doing.
+
+.plotregion1.AddTextBox added_text editor -39.54864687610738 -1.346531835179192
+.plotregion1.added_text_new = 1
+.plotregion1.added_text_rec = 2
+.plotregion1.added_text[2].style.editstyle angle(default) size( sztype(relative) val(3.4722) allow_pct(1)) color(black) horizontal(left) vertical(middle) margin( gleft( sztype(relative) val(0) allow_pct(1)) gright( sztype(relative) val(0) allow_pct(1)) gtop( sztype(relative) val(0) allow_pct(1)) gbottom( sztype(relative) val(0) allow_pct(1))) linegap( sztype(relative) val(0) allow_pct(1)) drawbox(no) boxmargin( gleft( sztype(relative) val(0) allow_pct(1)) gright( sztype(relative) val(0) allow_pct(1)) gtop( sztype(relative) val(0) allow_pct(1)) gbottom( sztype(relative) val(0) allow_pct(1))) fillcolor(bluishgray) linestyle( width( sztype(relative) val(.2) allow_pct(1)) color(black) pattern(solid) align(inside)) box_alignment(east) editcopy
+.plotregion1.added_text[2].text = {}
+.plotregion1.added_text[2].text.Arrpush 1
+// editor text[2] edits
+
+// editor text[2] edits
+
+
+//
diff --git a/Modules/ado/personal/h/hcaccprox.ado b/Modules/ado/personal/h/hcaccprox.ado
new file mode 100644
index 0000000..698610b
--- /dev/null
+++ b/Modules/ado/personal/h/hcaccprox.ado
@@ -0,0 +1,501 @@
+************************************************************************************************************
+* hcaccprox: Hierachical Clusters Analysis/CCPROX
+* Version 1: May 12, 2004
+* Add-on: Partition version 2 (2004-04-10)
+*
+* Use the Detect Stata program (http://freeirt.free.fr)
+*
+* Historic :
+* Version 1 [2004-01-18], Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : 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 hcaccprox , rclass
+version 8.0
+syntax varlist(min=2 numeric) [,PROX(string) METHod(string) PARTition(numlist) MEASures DETails DETect(integer 0)]
+
+local nbpart:word count `partition'
+tokenize `partition'
+forvalues k=1/`nbpart' {
+ local part`k'=``k''
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+tempname proximity whereitems
+
+matrix define `proximity'=J(`nbitems',`nbitems',0)
+matrix define `whereitems'=J(`=`nbitems'-1',`nbitems',0)
+
+if `detect'>`nbitems' {
+ di _col(3) in green "The number of partitions analyzed by the DETECT criterion must be inferior to the number of possible partitions"
+ di _col(3) in green "This number of possible partitions is `=`nbitems'-1', so your detect option is put to this number"
+ local detect=`nbitems'-1
+ di
+}
+
+if "`prox'"!="a"&"`prox'"!="ad"&"`prox'"!="cor"&"`prox'"!="ccov"&"`prox'"!="ccor"&"`prox'"!="mh" {
+ if "`prox'"=="" {
+ local prox="ccov"
+ }
+ else {
+ di in red "You must define an existing measure of proximity (a, ad, cor, ccov, ccor, mh)."
+ di in red "Please correct your prox option."
+ exit
+ }
+}
+
+if "`method'"!="UPGMA"&"`method'"!="single"&"`method'"!="complete" {
+ if "`method'"=="" {
+ local method="UPGMA"
+ }
+ else {
+ di in red "Tou must define an existing method to define the proximity between two clusters of items:"
+ di in red _col(10) "- UPGMA: Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- single: single linkage"
+ di in red _col(10) "- complete: complete linkage "
+ di in red "Please correct your method option"
+ exit
+ }
+}
+
+forvalues i=1/`nbitems' {
+ matrix `whereitems'[1,`i']=`i'
+ if "`details'"!="" {
+ di in green _col(3) "The item " _col(13) in yellow "``i''" in green " correspond to the node " in yellow "`i'"
+ }
+}
+
+tempvar score
+egen `score'=rmean(`varlist')
+qui replace `score'=`score'*`nbitems'
+forvalues k=0/`nbitems' {
+ qui count if `score'==`k'
+ local nk`k'=r(N)
+}
+
+qui count
+local N=r(N)
+
+if "`prox'"=="ccov"|"`prox'"=="mh" {
+ local proxmin=0
+}
+
+/*************************Measure of proximities*********************************/
+
+forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ /***********************************Proximity A**************************/
+ if "`prox'"=="a" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/(`N'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity AD*************************/
+ if "`prox'"=="ad" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-(`tmp11'+`tmp00')/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /**********************************Proximity COR*************************/
+ if "`prox'"=="cor" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+ qui count if ``i''==1&``j''==0
+ local tmp10=r(N)
+ qui count if ``i''==0&``j''==1
+ local tmp01=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-(`tmp11'*`tmp00'-`tmp10'*`tmp01')/(sqrt((`tmp11'+`tmp10')*(`tmp11'+`tmp01')*(`tmp00'+`tmp10')*(`tmp00'+`tmp01')))))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity CCOV**********************/
+ if "`prox'"=="ccov" {
+ local dij=0
+ forvalues k=1/`=`nbitems'-1' {
+ if `nk`k''!=0 {
+ qui corr ``i'' ``j'',cov
+ local covi`i'j`j'k`k'=r(cov_12)
+ local dij=`dij'+`covi`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-`dij'/`N'
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'<`dij'/`N' {
+ local proxmin=`dij'/`N'
+ }
+ }
+
+ /***********************************Proximity CCOR**********************/
+
+ if "`prox'"=="ccor" {
+ local dij=0
+ forvalues k=1/`=`nbitems'-1' {
+ if `nk`k''!=0 {
+ qui corr ``i'' ``j''
+ local cori`i'j`j'k`k'=r(rho)
+ local dij=`dij'+`cori`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-`dij'/`N'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+
+ /***********************************Proximity MH************************/
+
+ if "`prox'"=="mh" {
+ local numij=0
+ local denom=0
+ forvalues k=1/`=`nbitems'-1' {
+ if `nk`k''!=0 {
+ qui count if ``i''==1&``j''==1
+ local A=r(N)
+ qui count if ``i''==0&``j''==1
+ local B=r(N)
+ qui count if ``i''==1&``j''==0
+ local C=r(N)
+ qui count if ``i''==0&``j''==0
+ local D=r(N)
+
+ if `B'!=0&`C'!=0 {
+ local numij=`numij'+`A'*`D'/`nk`k''
+ local denomij=`denomij'+`B'*`C'/`nk`k''
+ }
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-log(`numij'/`denomij')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'`currentprox'[`i',`j'] {
+ local distmin=`currentprox'[`i',`j']
+ local cl1=`i'
+ local cl2=`j'
+ }
+ }
+ }
+
+ local linescl1=`conclinesnodes'[1,`cl1']
+ local nbitemscl1=`nodes'[1,`linescl1']
+ matrix `nodes'[2,`linescl1']=0
+ local linescl2=`conclinesnodes'[1,`cl2']
+ local nbitemscl2=`nodes'[1,`linescl2']
+ matrix `nodes'[2,`linescl2']=0
+ matrix `nodes'[1,`=`nbitems'+`k'']=`nbitemscl1'+`nbitemscl2'
+ matrix `nodes'[2,`=`nbitems'+`k'']=1
+ matrix `nodes'[3,`=`nbitems'+`k'']=`linescl1'
+ matrix `nodes'[4,`=`nbitems'+`k'']=`linescl2'
+ if "`details'"!="" {
+ di in green _col(3) "The nodes" _col(13) in yellow "`linescl1'" _col(17) in green "and" _col(21) in yellow "`linescl2'" _col(25) in green "are been aggregated to form the node " in yellow "`=`nbitems'+`k''"
+ }
+
+ forvalues i=5/`=`nbitemscl1'+4' {
+ local item=`nodes'[`i',`linescl1']
+ matrix `nodes'[`i',`=`nbitems'+`k'']=`item'
+ matrix `whereitems'[`k',`item']=`=`nbitems'+`k''
+ }
+ forvalues i=5/`=`nbitemscl2'+4' {
+ local item=`nodes'[`i',`linescl2']
+ matrix `nodes'[`=`i'+`nbitemscl1'',`=`nbitems'+`k'']=`item'
+ matrix `whereitems'[`k',`item']=`=`nbitems'+`k''
+ }
+
+ local tmp=1
+ forvalues i=1/`=`nbitems'+`k'' {
+ if `nodes'[2,`i']==1 {
+ matrix `mempart'[`tmp',`k']=`i'
+ local tmp=`tmp'+1
+ }
+ }
+
+
+
+ if `detect'>=`=`nbitems'-`k'' {
+ local partdetect
+ local compteur=1
+ local scaledetect
+ forvalues i=1/`=`nbitems'-`k'' {
+ local scaledetect`i'
+ }
+ forvalues i=1/`=`nbitems'+`k'' {
+ if `nodes'[2,`i']==1{
+ local tmp=`nodes'[1,`i']
+ local partdetect `partdetect' `tmp'
+ local tmp2=4+`tmp'
+ forvalues j=5/`tmp2' {
+ local tmp3=`nodes'[`j',`i']
+ local scaledetect`compteur' `scaledetect`compteur'' ``tmp3''
+ }
+ local scaledetect `scaledetect' `scaledetect`compteur''
+ local compteur=`compteur'+1
+ }
+ }
+ qui detect `scaledetect' , partition(`partdetect')
+ local detect`=`nbclusters'-1'=r(DETECT)
+ local R`=`nbclusters'-1'=r(R)
+ local Iss`=`nbclusters'-1'=r(Iss)
+ }
+
+
+ matrix drop `currentprox'
+ matrix define `currentprox'=J(`=`nbclusters'-1',`=`nbclusters'-1',0)
+ matrix drop `conclinesnodes'
+ matrix define `conclinesnodes'=J(1,`=`nbclusters'-1',0)
+
+ local tmp=1
+ forvalues i=1/`=`nbitems'+`k'' {
+ if `nodes'[2,`i']==1 {
+ matrix `conclinesnodes'[1,`tmp']=`i'
+ local tmp=`tmp'+1
+ }
+ }
+ forvalues i=1/`=`nbclusters'-1' {
+ forvalues j=`=`i'+1'/`=`nbclusters'-1' {
+ if "`method'"=="UPGMA" {
+ local moy=0
+ local linescl1=`conclinesnodes'[1,`i']
+ local nbitemscl1=`nodes'[1,`linescl1']
+ local linescl2=`conclinesnodes'[1,`j']
+ local nbitemscl2=`nodes'[1,`linescl2']
+ forvalues l=5/`=`nbitemscl1'+4' {
+ forvalues m=5/`=`nbitemscl2'+4' {
+ local item1=`nodes'[`l',`linescl1']
+ local item2=`nodes'[`m',`linescl2']
+ local tmp=`proximity'[`item1',`item2']
+ local moy=`moy'+`tmp'
+ }
+ }
+ matrix `currentprox'[`i',`j']=`moy'/(`nbitemscl1'*`nbitemscl2')
+ matrix `currentprox'[`j',`i']=`moy'/(`nbitemscl1'*`nbitemscl2')
+ }
+ if "`method'"=="single" {
+ local moy=0
+ local linescl1=`conclinesnodes'[1,`i']
+ local nbitemscl1=`nodes'[1,`linescl1']
+ local linescl2=`conclinesnodes'[1,`j']
+ local nbitemscl2=`nodes'[1,`linescl2']
+ forvalues l=5/`=`nbitemscl1'+4' {
+ forvalues m=5/`=`nbitemscl2'+4' {
+ local item1=`nodes'[`l',`linescl1']
+ local item2=`nodes'[`m',`linescl2']
+ if `l'==5&`m'==5 {
+ local distmin=`proximity'[`item1',`item2']
+ }
+ else {
+ if `distmin'>`proximity'[`item1',`item2'] {
+ local distmin=`proximity'[`item1',`item2']
+ }
+ }
+ }
+ }
+ matrix `currentprox'[`i',`j']=`distmin'
+ matrix `currentprox'[`j',`i']=`distmin'
+ }
+ if "`method'"=="complete" {
+ local moy=0
+ local linescl1=`conclinesnodes'[1,`i']
+ local nbitemscl1=`nodes'[1,`linescl1']
+ local linescl2=`conclinesnodes'[1,`j']
+ local nbitemscl2=`nodes'[1,`linescl2']
+ local distmax=0
+ forvalues l=5/`=`nbitemscl1'+4' {
+ forvalues m=5/`=`nbitemscl2'+4' {
+ local item1=`nodes'[`l',`linescl1']
+ local item2=`nodes'[`m',`linescl2']
+ if `distmax'<`proximity'[`item1',`item2'] {
+ local distmax=`proximity'[`item1',`item2']
+ }
+ }
+ }
+ matrix `currentprox'[`i',`j']=`distmax'
+ matrix `currentprox'[`j',`i']=`distmax'
+ }
+ }
+ }
+}
+
+if `detect'!=0 {
+ tempname indexes
+ matrix define `indexes'=J(`detect',4,0)
+ matrix colnames `indexes'=Clusters DETECT Iss R
+ di ""
+ di in green _col(7) "Indexes to test the `detect' latest partitions of the items"
+ di ""
+ di in green _col(29) "DETECT" _col(43) "Iss" _col(56) "R"
+ di _col(5) in green "Only one cluster:" _col(27) in yellow %8.5f `detect1' _col(38) %8.5f `Iss1' _col(49) %8.5f `R1'
+ matrix `indexes'[1,1]=1
+ matrix `indexes'[1,2]=`detect1'
+ matrix `indexes'[1,3]=`Iss1'
+ matrix `indexes'[1,4]=`R1'
+ forvalues k=2/`detect' {
+ matrix `indexes'[`k',1]=`k'
+ matrix `indexes'[`k',2]=`detect`k''
+ matrix `indexes'[`k',3]=`Iss`k''
+ matrix `indexes'[`k',4]=`R`k''
+ di _col(5) in green "`k' clusters:" _col(27) in yellow %8.5f `detect`k'' _col(38) %8.5f `Iss`k'' _col(49) %8.5f `R`k''
+ }
+ return matrix indexes=`indexes'
+}
+
+
+forvalues k=1/`nbpart' {
+ di ""
+ local rowmempart=`nbitems'-`part`k''
+ di in green _col(8) "Number of clusters : `part`k''"
+ tempname affect`part`k''
+ matrix define `affect`part`k'''=J(1,`nbitems',0)
+ forvalues i=1/`part`k'' {
+ di
+ di in green _col(12) "Cluster `i':"
+ local rownodes=`mempart'[`i',`rowmempart']
+ local itemsinthecluster=`nodes'[1,`rownodes']
+ forvalues j=5/`=4+`itemsinthecluster'' {
+ local tmp=`nodes'[`j',`rownodes']
+ matrix `affect`part`k'''[1,`tmp']=`i'
+ di in yellow _col(13)"``tmp''"
+ }
+ }
+ matrix colnames `affect`part`k'''=`varlist'
+ return matrix affect`part`k''=`affect`part`k'''
+}
+
+return matrix mempart `mempart'
+return matrix nodes `nodes'
+return local nbitems=`nbitems'
+return local varlist `varlist'
+end
+
+/*********************************************************
+*Partition
+*Version 2 (May 10, 2004)
+*
+*Historic
+*Version 1 (January 18, 2004)
+***********************************************************/
+
+program define partition
+version 8.0
+syntax anything(name=partition)
+
+local nbitems=r(nbitems)
+tempname mempart nodes
+matrix `mempart'=r(mempart)
+matrix `nodes'=r(nodes)
+local varlist "`r(varlist)'"
+
+local nbpart:word count `partition'
+tokenize `partition'
+
+forvalues k=1/`nbpart' {
+ local part`k'=``k''
+}
+tokenize `varlist'
+
+forvalues k=1/`nbpart' {
+ di ""
+ local rowmempart=`nbitems'-`part`k''
+ di in green _col(8) "Number of clusters : `part`k''"
+ forvalues i=1/`part`k'' {
+ di
+ di in green _col(12) "Cluster `i':"
+ local rownodes=`mempart'[`i',`rowmempart']
+ local itemsinthecluster=`nodes'[1,`rownodes']
+ forvalues j=5/`=4+`itemsinthecluster'' {
+ local tmp=`nodes'[`j',`rownodes']
+ di in yellow _col(13)"``tmp''"
+ }
+ }
+}
+end
+
diff --git a/Modules/ado/personal/h/hcaccprox.hlp b/Modules/ado/personal/h/hcaccprox.hlp
new file mode 100644
index 0000000..2daca3b
--- /dev/null
+++ b/Modules/ado/personal/h/hcaccprox.hlp
@@ -0,0 +1,90 @@
+{smcl}
+{* 12may2004}{...}
+{hline}
+help for {hi:hcaccprox}
+{hline}
+
+{title:Hierarchical Clusters Analysis with conditional proximity measures}
+
+{p 8 14 2}{cmd:hcaccprox} {it:varlist}
+[{cmd:,} {cmdab:prox:(}{it:keyword}{cmd:)} {cmdab:meth:od(}{it:keyword}{cmd:)} {cmdab:part:ition(}{it:numlist}{cmd:)}
+ {cmdab:meas:ures} {cmdab:det:ails} {cmdab:det:ect:(}{it:#}{cmd:)} ]
+
+{p 8 14 2}{cmd:partition} {it:numlist}
+
+{title:Description}
+
+{p 4 8 2}
+{cmd:hcaccprox} realize a Hierarchical Clusters Analysis on dichotomoux items
+based on specific measures of proximity as conditional proximity measures. The program
+permit to obtain indexes to test the obtained partition (the {help detect} program is
+necessary in this case).
+
+{p 4 8 2}
+{cmd:partition} permit, after a {cmd:hcaccprox} step to obtain
+the composition of some specific partitions of the items.
+
+{title:Options}
+
+{p 4 8 2}{cmd:prox:(}{it:keyword}{cmd:)} define the method to compute the proximity between the items.
+Six measures are possible. The three first ones are unconditional measures named {it:a}, {it:ad} and {it:cor}.
+The three last ones are conditional measures named {it:ccov}, {it:ccor} and {it:mh}. See Roussos, Stout and Marden (1998)
+for details of these six measures. By default, the {it:ccov} option is used.
+
+{p 4 8 2}{cmd:method} define the method to aggregate two clusters, {it:single} for a single linkage, {it:complete} for a complete
+linkage, and {it:UPGMA} for the Unweighted Pair-Group Method of Average. By default, the {it:UPGMA} option is used.
+
+{p 4 8 2}{cmd:partition(}{it:numlist}{cmd:)} lists the partitions to detail by the program. List like {it:(2 4 6)} or {it:(2(2)6)}
+are authorized.
+
+{p 4 8 2}{cmd:measures} display the used proximity measures between the items.
+
+{p 4 8 2}{cmd:details} display the results of the algorithm of aggregation.
+
+{p 4 8 2}{cmd:detect(}{it:#}{cmd:)} specifies for all the partitions with a number of clusters inferior or equal to {it:#}
+to compute the DETECT, Iss and R indexes.
+
+{p 4 8 2}{it:numlist}, for the {cmd:partition} program, define the partitions with the number of clusters indicated in the {it:numlist}
+to detail.
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. hcaccprox q1-q10}
+
+{p 4 8 2}{cmd:. partition 3 5 6}
+
+{p 4 8 2}{cmd:. hcaccprox item1-item9 dotest1-dotest6, detect(6) measures}
+
+{p 4 8 2}{cmd:. hcaccprox c1 c2 c3 c4 c5 c6 c7, prox(a) method(single)}
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:. r(varlist)} is a macro who contain {it:varlist}
+
+{p 4 8 2}{cmd:. r(nbitems)} is a macro who contain the number of items
+
+{p 4 8 2}{cmd:. r(nodes)} is a matrix who contain all the informations about all the possible clusters of items. Each column represent a node (the first ones represent each item of {it:varlist}, and the following columns represent each
+aggregation of clusters), the first line represent the number of items in each cluster, the third and the fourth lines represent the two cluster who are aggregated to form the new cluster, and the following lines represent the list of
+items composing each cluster
+
+{p 4 8 2}{cmd:. r(mempart)} list the number of cluster composing each possible partition : the last column is the partition in only one cluster, the preceeding column represent the partition in two cluster, and so on
+
+{p 4 8 2}{cmd:. r(affect#)} is obtained with the {it:partition} option. In this vector, the number of the cluster (of the partition in # clusters) is associated to each item
+
+{p 4 8 2}{cmd:. r(indexes)} is obtained with the {it:detect} option. This matrix contain the DETECT, Iss and R indexes associated to each partition with a number of clusters inferior to the number defined in the {it:detect} option
+
+
+{title:Reference}
+
+{p 4 8 2}{cmd:Roussos L. A, Stout W. F. and Marden J. I.}, {it:Using new proximity measures with hierarchical cluster analysis to detect multidimensionality}. Journal of Educational Measurement, {cmd:35}(1), pp 1-30, 1998.
+
+{p 4 8 2}{cmd:Zhang J. and Stout W. F.}, {it:The theorical DETECT index of dimensionality and its application to approximate simple structure}. Psychometrika, {cmd:64}(2), pp 213-249, 1999.
+
+{title:Also see}
+
+{p 4 13 2} help for {help detect}
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@neuf.fr":jean-benoit.hardouin@neuf.fr} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/h/hcavar.ado b/Modules/ado/personal/h/hcavar.ado
new file mode 100644
index 0000000..888ffe8
--- /dev/null
+++ b/Modules/ado/personal/h/hcavar.ado
@@ -0,0 +1,509 @@
+*! Version 3.6 19 July 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* hcavar: Hierachical Clusters Analysis (HCA) of variables
+* Version 3.5 [2014-05-26], Jean-Benoit Hardouin /* dirsave and filesave options */
+*
+* Use the Detect Stata program (ssc install detect)
+*
+* Historic :
+* Under the name of -hcaccprox-
+* Version 1 [2004-01-18], Jean-Benoit Hardouin
+* Version 2 [2004-05-12], Jean-Benoit Hardouin
+* Version 3 [2005-12-31], Jean-Benoit Hardouin
+* Version 3.1 [2006-01-15], Jean-Benoit Hardouin /* correction if there is only one individual with a given score*/
+* Version 3.2 [2010-04-15], Jean-Benoit Hardouin /* Possibility to use Polytomous Items with CCOR, CCOV and MH*/
+* Version 3.3 [2014-05-07], Jean-Benoit Hardouin, Bastien Perrot /* HTML option, if option*/
+* Version 3.4 [2014-05-26], Jean-Benoit Hardouin, Bastien Perrot /* DETECT option available for polytomous items */
+* Version 3.5 [2019-07-18], Jean-Benoit Hardouin /* dirsave and filesave options */
+* Version 3.6 [2019-07-19], Jean-Benoit Hardouin /* loevH proximity */
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2004-2006, 2010, 2019 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 hcavar, rclass
+version 9
+syntax varlist(min=2 numeric) [if] [in] [,PROX(string) METHod(string) PARTition(numlist) MEASures DETect MATrix(string) noDENDROgram HTML(string) DIRSave(string) FILESave]
+
+tempfile hcaccproxfile
+qui save `hcaccproxfile',replace
+preserve
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`html'"!="" {
+ //set scheme sj
+ //local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+local type=0
+forvalues i=1/`nbitems' {
+ qui drop if ``i''==.
+ qui inspect ``i''
+ if r(N_unique)>`type'&r(N_unique)!=. {
+ local type=r(N_unique)
+ }
+ else if r(N_unique)>`type'&r(N_unique)==. {
+ local type "100"
+ }
+}
+if `type'==100 {
+ local type ">99"
+}
+
+tempname proximity whereitems
+
+local prox=lower("`prox'")
+local method=lower("`method'")
+matrix define `proximity'=J(`nbitems',`nbitems',0)
+matrix define `whereitems'=J(`=`nbitems'-1',`nbitems',0)
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`matrix'"!="" {
+ local desprox="Defined by the user"
+}
+if "`prox'"=="" {
+ local prox="pearson"
+}
+else if "`prox'"=="a" {
+ local prox="jaccard"
+}
+else if "`prox'"=="ad" {
+ local prox="matching"
+}
+else if "`prox'"=="corr" {
+ local prox="pearson"
+}
+if "`type'">"2"&"`prox'"!="pearson"&"`prox'"!="ccov"&"`prox'"!="ccor"&"`prox'"!="mh"&"`prox'"!="loevh" {
+ di in red "Only the {hi:pearson}, {hi:ccov}, {hi:ccor}, {hi:mh} and {hi:loevh} measures of proximity are available with ordinal or numerous variables"
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+
+if "`partition'"==""&"`detect'"!="" {
+ di in ye "option partition() required"
+ error 198
+}
+local existmeas=0
+foreach i in jaccard matching pearson russel dice ccor mh ccov loevh {
+ if "`prox'"=="`i'" {
+ local existmeas=1
+ }
+}
+if `existmeas'==0 {
+ di in red "You must define an existing measure of proximity (jaccard(a), matching(ad), pearson(cor), russel, dice, ccov, ccor, mh, loevh)."
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`prox'"=="ccov"|"`prox'"=="mh" {
+ local proxmin=0
+}
+
+if "`prox'"=="matching" {
+ local desprox="Matching"
+}
+else if "`prox'"=="jaccard" {
+ local desprox="Jaccard"
+}
+else if "`prox'"=="russel" {
+ local desprox="Russel"
+}
+else if "`prox'"=="dice" {
+ local desprox="Dice"
+}
+else if "`prox'"=="pearson" {
+ local desprox="Pearson"
+}
+else if "`prox'"=="ccov" {
+ local desprox="Conditional covariances"
+}
+else if "`prox'"=="ccor" {
+ local desprox="Conditional correlations"
+}
+else if "`prox'"=="mh" {
+ local desprox="Mantel Hanzel"
+}
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`method'"=="upgma"|"`method'"=="" {
+ local method="average"
+}
+if "`method'"=="wpgma"|"`method'"=="" {
+ local method="waverage"
+}
+local vermethod=0
+foreach i in average waverage single centroid median complete wards {
+ if "`method'"=="`i'" {
+ local vermethod=1
+ }
+ }
+
+if `vermethod'==0 {
+ di in red "You must define an existing method to define the proximity between two clusters of items:"
+ di in red _col(10) "- single: single linkage"
+ di in red _col(10) "- complete: complete linkage "
+ di in red _col(10) "- average(UPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- waverage(WPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- wards: Ward's linkage"
+ di in red "Please correct your method option"
+ exit
+}
+if "`method'"=="single"|"`method'"=="singlelinkage" {
+ local method single
+ local desmethod="Single linkage"
+}
+else if "`method'"=="complete"|"`method'"=="completelinkage" {
+ local desmethod="Complete linkage"
+}
+else if "`method'"=="median"|"`method'"=="medianlinkage" {
+ local desmethod="Median linkage (no dendrogram)"
+}
+else if "`method'"=="centroid"|"`method'"=="centroidlinkage" {
+ local desmethod="Centroid linkage (no dendrogram)"
+}
+else if "`method'"=="average"|"`method'"=="averagelinkage" {
+ local desmethod="Unweighted Pair-Group Method of Average"
+}
+else if "`method'"=="waverage"|"`method'"=="waveragelinkage" {
+ local desmethod="Weighted Pair-Group Method of Average"
+}
+else if "`method'"=="wards"|"`method'"=="wardslinkage" {
+ local desmethod="Ward's linkage"
+}
+
+forvalues i=1/`nbitems' {
+ matrix `whereitems'[1,`i']=`i'
+}
+
+tempvar score
+genscore `varlist',score(`score')
+qui su `score'
+local maxscore=r(max)
+forvalues k=0/`maxscore' {
+ qui count if `score'==`k'
+ local nk`k'=r(N)
+}
+
+qui count
+local N=r(N)
+
+
+di in green "{hline 80}"
+di in green "Number of individuals with none missing values: " in ye `N'
+di in green "Maximal number of modalities for a variable: " in ye "`type'"
+di in green "Proximity measures: " in ye "`desprox'"
+di in green "Method to aggregate clusters: " in ye "`desmethod'"
+di in green "{hline 80}"
+di
+di
+
+
+/*************************Measure of proximities*********************************/
+if "`matrix'"=="" {
+ if "`prox'"=="loevh" {
+ qui loevh `varlist', pairw pair
+ matrix `proximity'=r(loevHjk)
+ }
+
+ forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ /***********************************Proximity AD*************************/
+ if "`prox'"=="matching" { /*ad*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-(`tmp11'+`tmp00')/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="jaccard" { /*a*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/(`N'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity Russel**************************/
+ else if "`prox'"=="russel" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="dice" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-2*`tmp11'/(`N'+`tmp11'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /**********************************Proximity COR*************************/
+ else if "`prox'"=="pearson" { /*corr*/
+ qui corr ``i'' ``j''
+ matrix `proximity'[`i',`j']=sqrt(2*(1-r(rho)))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity CCOV**********************/
+ else if "`prox'"=="ccov" {
+ local dij=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k',cov
+ local covi`i'j`j'k`k'=r(cov_12)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local covi`i'j`j'k`k'=0
+ }
+ else {
+ local covi`i'j`j'k`k'=0
+ }
+ local dij=`dij'+`covi`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-`dij'/`Ntemp'
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'<`dij'/`Ntemp' {
+ local proxmin=`dij'/`Ntemp'
+ }
+ }
+
+ /***********************************Proximity CCOR**********************/
+
+ else if "`prox'"=="ccor" {
+ local dij=0
+ local nnull=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k'
+ local cori`i'j`j'k`k'=r(rho)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local cori`i'j`j'k`k'=0
+ }
+ else {
+ local cori`i'j`j'k`k'=0
+ }
+ if `cori`i'j`j'k`k''!=. {
+ local dij=`dij'+`cori`i'j`j'k`k''*`nk`k''
+ }
+ else if `cori`i'j`j'k`k''==. {
+ local nnull=`nnull'+`nk`k''
+ }
+ }
+ }
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-`dij'/(`Ntemp'-`nnull')))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+
+ /***********************************Proximity MH************************/
+
+ else if "`prox'"=="mh" {
+ local numij=0
+ local denom=0
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ qui count if ``i''==1&``j''==1&`score'==`k'
+ local A=r(N)
+ qui count if ``i''==0&``j''==1&`score'==`k'
+ local B=r(N)
+ qui count if ``i''==1&``j''==0&`score'==`k'
+ local C=r(N)
+ qui count if ``i''==0&``j''==0&`score'==`k'
+ local D=r(N)
+ local numij=`numij'+`A'*`D'/`nk`k''
+ local denomij=`denomij'+`B'*`C'/`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-log(`numij'/`denomij')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//dendrogram,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ qui cluster dendro ,labels(name) hor ylabel(,angle(0)) title("Hierarchical Cluster Analysis on variables") subtitle("`desmethod'") xtitle("`desprox' proximities") `saving'
+ }
+}
+
+if "`partition'"!="" {
+ foreach i of numlist `partition' {
+ qui cluster gen cluster`i'=group(`i')
+ }
+ tempname clusters
+ mkmat cluster* ,mat(`clusters')
+ matrix rownames `clusters'=`varlist'
+ local compteur=0
+ foreach i of numlist `partition' {
+ local ++compteur
+ di
+ di in green "{hline 30}"
+ di in green "Partition in `i' cluster(s)"
+ di in green "{hline 30}"
+ di
+ forvalues j=1/`i' {
+ local cluster`i'_`j'
+ local nbi`i'_`j'=0
+ forvalues k=1/`nbitems' {
+ if `clusters'[`k',`compteur']==`j' {
+ local cluster`i'_`j' `cluster`i'_`j'' ``k''
+ local ++nbi`i'_`j'
+ }
+ }
+ di in green "Cluster `j': " in ye "`cluster`i'_`j''"
+ }
+ }
+ return matrix clusters=`clusters'
+}
+
+/**********************DETECT OPTION **************************************************/
+
+use `hcaccproxfile',clear
+if "`detect'"!=""&"`partition'"!="" {
+ foreach i of numlist `partition' {
+ local liste
+ local part
+ forvalues j=1/`i' {
+ local liste "`liste' `cluster`i'_`j''"
+ local part "`part' `nbi`i'_`j''"
+ }
+ qui detect `liste',part(`part')
+ local detect`i'=r(DETECT)
+ local Iss`i'=r(Iss)
+ local R`i'=r(R)
+ }
+ tempname indexes
+ matrix define `indexes'=J(`compteur',4,0)
+ matrix colnames `indexes'=Clusters DETECT Iss R
+ di ""
+ di in green "{hline 50}"
+ di in green "Indexes to compare the partitions of the items"
+ di in green "{hline 50}"
+ di ""
+ di in green _col(29) "DETECT" _col(43) "Iss" _col(56) "R"
+ local compteur=0
+ foreach k of numlist `partition' {
+ local ++compteur
+ matrix `indexes'[`compteur',1]=`k'
+ matrix `indexes'[`compteur',2]=`detect`k''
+ matrix `indexes'[`compteur',3]=`Iss`k''
+ matrix `indexes'[`compteur',4]=`R`k''
+ di _col(5) in green "`k' cluster(s):" _col(27) in yellow %8.5f `detect`k'' _col(38) %8.5f `Iss`k'' _col(49) %8.5f `R`k''
+ }
+ return matrix indexes=`indexes'
+}
+return local nbvar=`nbitems'
+return matrix measures=`proximity'
+restore, not
+*use `hcaccproxfile',clear
+
+end
diff --git a/Modules/ado/personal/h/hcavar.hlp b/Modules/ado/personal/h/hcavar.hlp
new file mode 100644
index 0000000..dec6ad1
--- /dev/null
+++ b/Modules/ado/personal/h/hcavar.hlp
@@ -0,0 +1,100 @@
+{smcl}
+{* 6december2012}{...}
+{hline}
+help for {hi:hcavar}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Hierarchical Clusters Analysis of variables}
+
+{p 8 14 2}{cmd:hcavar} {it:varlist}
+[{cmd:,} {cmdab:prox}{it:(keyword)} {cmdab:mat:rix}{it:(matrix)} {cmdab:meth:od}{it:(keyword)}
+{cmdab:part:ition}{it:(numlist)} {cmdab:meas:ures} {cmdab:det:ect} {cmdab:nodendro:gram}]
+
+{title:Description}
+
+{p 4 8 2}
+{cmd:hcavar} is the new name of the old {cmd:hcaccprox} module.
+
+{p 4 8 2}
+{cmd:hcavar} realizes a Hierarchical Clusters Analysis on variables.
+The variables can be numerous, ordinal or binary. The distances (dissimilarity
+measures for binary variables) between two variables are computed as the squared
+root of 2 times one minus the Pearson correlation. For binary variables, it is
+possible to use other similarity coefficients as Matching, Jaccard, Russel or Dice
+(See {help measure option} for more details). The distance matrix is computed as
+the squared root of one minus the value of these coefficients.
+In the field of Item Response Theory, it is possible to define conditional measures
+to the score as defined by Roussos, Stout and Marden (1998): conditional correlations,
+conditional covariance, or Mantel-Haenszel measures of similarity. In the same field,
+it is possible to compute, for a set of obtained partition of the items, the DETECT,
+Iss and R indexes defined by Zhang and Stout (1999).
+
+{title:Options}
+
+{p 4 8 2}{cmd:prox} defines the proximity measures to use : {it:jaccard}
+(alias {it:a}), {it: russel}, {it:dice}, {it:matching} (alias {it:ad}), {it:pearson}
+(alias {it:corr}), conditional covariance ({it:ccov}), conditional correlation
+({it:ccor}), or Mantel Haenszel ({it:mh}). By default, this option is put to
+{it:pearson}. {it:pearson} is the only one option available with ordinal or numerous
+variables.
+
+{p 4 8 2}{cmd:matrix} allows using a matrix as distance matrix.
+
+{p 4 8 2}{cmd:method} defines the method to aggregate two clusters. See {help cluster}
+for more details about these methods. The complete name of the method
+must be indicated (with or without "linkage"), none abbreviation is allowed.
+{it:waveragelinkage} is used by default.
+
+{p 4 8 2}{cmd:partition} lists the partitions of variables to detail by
+the program.
+
+{p 4 8 2}{cmd:measures} displays the used proximity measures matrix between
+the variables.
+
+{p 4 8 2}{cmd:detect} computes the DETECT, Iss and R indexes
+for the partitions indicated in the {cmd:partitions} option.
+
+{p 4 8 2}{cmdnodendrogram} enables the displaying of th dendrogram.
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. hcavar var1-var10} /*displays only the dendrogram*/
+
+{p 4 8 2}{cmd:. hcavar var*, partition(1/6) measures method(single)} /*Single linkage, details of 6 partitions*/
+
+{p 4 8 2}{cmd:. hcavar itemA1-itemA7 itemB1-itemB7, prox(ccor) method(single) detect part(1/4)} /*details of 4 partitions, conditional correlations*/
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:. r(nbvar)} contains the number of variables
+
+{p 4 8 2}{cmd:. r(measures)} is the distances measures matrix between the variables
+
+{p 4 8 2}{cmd:. r(clusters)} is a matrix obtained with the {cmd:partition} option
+containing the composition of the partitions defined with this option.
+
+{p 4 8 2}{cmd:. r(indexes)} is obtained with the {cmd:detect} option.
+This matrix contain the DETECT, Iss and R indexes associated to each partition
+defined with the {cmd:partition} option.
+
+
+{title:Reference}
+
+{p 4 8 2}{cmd:Roussos L. A, Stout W. F. and Marden J. I.}, {it:Using new proximity measures with hierarchical cluster analysis to detect multidimensionality}. Journal of Educational Measurement, {cmd:35}(1), pp 1-30, 1998.
+
+{p 4 8 2}{cmd:Zhang J. and Stout W. F.}, {it:The theorical DETECT index of dimensionality and its application to approximate simple structure}. Psychometrika, {cmd:64}(2), pp 213-249, 1999.
+
+{title:Also see}
+
+{p 4 13 2} help for {help cluster}, help for {help detect} (if installed)
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 SPHERE "Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
diff --git a/Modules/ado/personal/h/hcavar3.2.ado b/Modules/ado/personal/h/hcavar3.2.ado
new file mode 100644
index 0000000..2c7078d
--- /dev/null
+++ b/Modules/ado/personal/h/hcavar3.2.ado
@@ -0,0 +1,464 @@
+*! Version 3.2 15 April 2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* hcavar: Hierachical Clusters Analysis (HCA) of variables
+* Version 3.2: April 15, 2010 /* Possibility to use Polytomous Items with CCOR, CCOV and MH*/
+*
+* Use the Detect Stata program (ssc install detect)
+*
+* Historic :
+* Under the name of -hcaccprox-
+* Version 1 [2004-01-18], Jean-Benoit Hardouin
+* Version 2 [2004-05-12], Jean-Benoit Hardouin
+* Version 3 [2005-12-31], Jean-Benoit Hardouin
+* Version 3.1 [2006-01-15], Jean-Benoit Hardouin /* correction if there is only one individual with a given score*/
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2004-2006, 2010 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 hcavar , rclass
+version 9
+syntax varlist(min=2 numeric) [,PROX(string) METHod(string) PARTition(numlist) MEASures DETect MATrix(string) noDENDROgram]
+
+tempfile hcaccproxfile
+qui save `hcaccproxfile',replace
+preserve
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+local type=0
+forvalues i=1/`nbitems' {
+ qui drop if ``i''==.
+ qui inspect ``i''
+ if r(N_unique)>`type'&r(N_unique)!=. {
+ local type=r(N_unique)
+ }
+ else if r(N_unique)>`type'&r(N_unique)==. {
+ local type "100"
+ }
+}
+if `type'==100 {
+ local type ">99"
+}
+
+tempname proximity whereitems
+
+local prox=lower("`prox'")
+local method=lower("`method'")
+matrix define `proximity'=J(`nbitems',`nbitems',0)
+matrix define `whereitems'=J(`=`nbitems'-1',`nbitems',0)
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`matrix'"!="" {
+ local desprox="Defined by the user"
+}
+if "`prox'"=="" {
+ local prox="pearson"
+}
+else if "`prox'"=="a" {
+ local prox="jaccard"
+}
+else if "`prox'"=="ad" {
+ local prox="matching"
+}
+else if "`prox'"=="corr" {
+ local prox="pearson"
+}
+if "`type'">"2"&"`prox'"!="pearson"&"`prox'"!="ccov"&"`prox'"!="ccor"&"`prox'"!="mh" {
+ di in red "Only the {hi:pearson}, {hi:ccov} and {hi:ccor} measures of proximity are available with ordinal or numerous variables"
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`type'">"2"&"`detect'"!="" {
+ di in ye "The {hi:detect} option is available only with binary variables. This option is disabled."
+ local detect
+ di
+}
+local existmeas=0
+foreach i in jaccard matching pearson russel dice ccor mh ccov {
+ if "`prox'"=="`i'" {
+ local existmeas=1
+ }
+}
+if `existmeas'==0 {
+ di in red "You must define an existing measure of proximity (jaccard(a), matching(ad), pearson(cor), russel, dice, ccov, ccor, mh)."
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`prox'"=="ccov"|"`prox'"=="mh" {
+ local proxmin=0
+}
+
+if "`prox'"=="matching" {
+ local desprox="Matching"
+}
+else if "`prox'"=="jaccard" {
+ local desprox="Jaccard"
+}
+else if "`prox'"=="russel" {
+ local desprox="Russel"
+}
+else if "`prox'"=="dice" {
+ local desprox="Dice"
+}
+else if "`prox'"=="pearson" {
+ local desprox="Pearson"
+}
+else if "`prox'"=="ccov" {
+ local desprox="Conditional covariances"
+}
+else if "`prox'"=="ccor" {
+ local desprox="Conditional correlations"
+}
+else if "`prox'"=="mh" {
+ local desprox="Mantel Hanzel"
+}
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`method'"=="upgma"|"`method'"=="" {
+ local method="average"
+}
+if "`method'"=="wpgma"|"`method'"=="" {
+ local method="waverage"
+}
+local vermethod=0
+foreach i in average waverage single centroid median complete wards {
+ if "`method'"=="`i'" {
+ local vermethod=1
+ }
+ }
+
+if `vermethod'==0 {
+ di in red "You must define an existing method to define the proximity between two clusters of items:"
+ di in red _col(10) "- single: single linkage"
+ di in red _col(10) "- complete: complete linkage "
+ di in red _col(10) "- average(UPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- waverage(WPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- wards: Ward's linkage"
+ di in red "Please correct your method option"
+ exit
+}
+if "`method'"=="single"|"`method'"=="singlelinkage" {
+ local method single
+ local desmethod="Single linkage"
+}
+else if "`method'"=="complete"|"`method'"=="completelinkage" {
+ local desmethod="Complete linkage"
+}
+else if "`method'"=="median"|"`method'"=="medianlinkage" {
+ local desmethod="Median linkage (no dendrogram)"
+}
+else if "`method'"=="centroid"|"`method'"=="centroidlinkage" {
+ local desmethod="Centroid linkage (no dendrogram)"
+}
+else if "`method'"=="average"|"`method'"=="averagelinkage" {
+ local desmethod="Unweighted Pair-Group Method of Average"
+}
+else if "`method'"=="waverage"|"`method'"=="waveragelinkage" {
+ local desmethod="Weighted Pair-Group Method of Average"
+}
+else if "`method'"=="wards"|"`method'"=="wardslinkage" {
+ local desmethod="Ward's linkage"
+}
+
+forvalues i=1/`nbitems' {
+ matrix `whereitems'[1,`i']=`i'
+}
+
+tempvar score
+genscore `varlist',score(`score')
+qui su `score'
+local maxscore=r(max)
+forvalues k=0/`maxscore' {
+ qui count if `score'==`k'
+ local nk`k'=r(N)
+}
+
+qui count
+local N=r(N)
+
+
+di in green "{hline 80}"
+di in green "Number of individuals with none missing values: " in ye `N'
+di in green "Maximal number of modalities for a variable: " in ye "`type'"
+di in green "Proximity measures: " in ye "`desprox'"
+di in green "Method to aggregate clusters: " in ye "`desmethod'"
+di in green "{hline 80}"
+di
+di
+
+/*************************Measure of proximities*********************************/
+if "`matrix'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ /***********************************Proximity AD*************************/
+ if "`prox'"=="matching" { /*ad*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-(`tmp11'+`tmp00')/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="jaccard" { /*a*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/(`N'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity Russel**************************/
+ else if "`prox'"=="russel" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="dice" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-2*`tmp11'/(`N'+`tmp11'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /**********************************Proximity COR*************************/
+ else if "`prox'"=="pearson" { /*corr*/
+ qui corr ``i'' ``j''
+ matrix `proximity'[`i',`j']=sqrt(2*(1-r(rho)))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity CCOV**********************/
+ else if "`prox'"=="ccov" {
+ local dij=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k',cov
+ local covi`i'j`j'k`k'=r(cov_12)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local covi`i'j`j'k`k'=0
+ }
+ else {
+ local covi`i'j`j'k`k'=0
+ }
+ local dij=`dij'+`covi`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-`dij'/`Ntemp'
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'<`dij'/`Ntemp' {
+ local proxmin=`dij'/`Ntemp'
+ }
+ }
+
+ /***********************************Proximity CCOR**********************/
+
+ else if "`prox'"=="ccor" {
+ local dij=0
+ local nnull=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k'
+ local cori`i'j`j'k`k'=r(rho)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local cori`i'j`j'k`k'=0
+ }
+ else {
+ local cori`i'j`j'k`k'=0
+ }
+ if `cori`i'j`j'k`k''!=. {
+ local dij=`dij'+`cori`i'j`j'k`k''*`nk`k''
+ }
+ else if `cori`i'j`j'k`k''==. {
+ local nnull=`nnull'+`nk`k''
+ }
+ }
+ }
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-`dij'/(`Ntemp'-`nnull')))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+
+ /***********************************Proximity MH************************/
+
+ else if "`prox'"=="mh" {
+ local numij=0
+ local denom=0
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ qui count if ``i''==1&``j''==1&`score'==`k'
+ local A=r(N)
+ qui count if ``i''==0&``j''==1&`score'==`k'
+ local B=r(N)
+ qui count if ``i''==1&``j''==0&`score'==`k'
+ local C=r(N)
+ qui count if ``i''==0&``j''==0&`score'==`k'
+ local D=r(N)
+ local numij=`numij'+`A'*`D'/`nk`k''
+ local denomij=`denomij'+`B'*`C'/`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-log(`numij'/`denomij')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'"
+ di ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+local type=0
+forvalues i=1/`nbitems' {
+ qui drop if ``i''==.
+ qui inspect ``i''
+ if r(N_unique)>`type'&r(N_unique)!=. {
+ local type=r(N_unique)
+ }
+ else if r(N_unique)>`type'&r(N_unique)==. {
+ local type "100"
+ }
+}
+if `type'==100 {
+ local type ">99"
+}
+
+tempname proximity whereitems
+
+local prox=lower("`prox'")
+local method=lower("`method'")
+matrix define `proximity'=J(`nbitems',`nbitems',0)
+matrix define `whereitems'=J(`=`nbitems'-1',`nbitems',0)
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`matrix'"!="" {
+ local desprox="Defined by the user"
+}
+if "`prox'"=="" {
+ local prox="pearson"
+}
+else if "`prox'"=="a" {
+ local prox="jaccard"
+}
+else if "`prox'"=="ad" {
+ local prox="matching"
+}
+else if "`prox'"=="corr" {
+ local prox="pearson"
+}
+if "`type'">"2"&"`prox'"!="pearson"&"`prox'"!="ccov"&"`prox'"!="ccor"&"`prox'"!="mh" {
+ di in red "Only the {hi:pearson}, {hi:ccov} and {hi:ccor} measures of proximity are available with ordinal or numerous variables"
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`type'">"2"&"`detect'"!="" {
+ di in ye "The {hi:detect} option is available only with binary variables. This option is disabled."
+ local detect
+ di
+}
+local existmeas=0
+foreach i in jaccard matching pearson russel dice ccor mh ccov {
+ if "`prox'"=="`i'" {
+ local existmeas=1
+ }
+}
+if `existmeas'==0 {
+ di in red "You must define an existing measure of proximity (jaccard(a), matching(ad), pearson(cor), russel, dice, ccov, ccor, mh)."
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`prox'"=="ccov"|"`prox'"=="mh" {
+ local proxmin=0
+}
+
+if "`prox'"=="matching" {
+ local desprox="Matching"
+}
+else if "`prox'"=="jaccard" {
+ local desprox="Jaccard"
+}
+else if "`prox'"=="russel" {
+ local desprox="Russel"
+}
+else if "`prox'"=="dice" {
+ local desprox="Dice"
+}
+else if "`prox'"=="pearson" {
+ local desprox="Pearson"
+}
+else if "`prox'"=="ccov" {
+ local desprox="Conditional covariances"
+}
+else if "`prox'"=="ccor" {
+ local desprox="Conditional correlations"
+}
+else if "`prox'"=="mh" {
+ local desprox="Mantel Hanzel"
+}
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`method'"=="upgma"|"`method'"=="" {
+ local method="average"
+}
+if "`method'"=="wpgma"|"`method'"=="" {
+ local method="waverage"
+}
+local vermethod=0
+foreach i in average waverage single centroid median complete wards {
+ if "`method'"=="`i'" {
+ local vermethod=1
+ }
+ }
+
+if `vermethod'==0 {
+ di in red "You must define an existing method to define the proximity between two clusters of items:"
+ di in red _col(10) "- single: single linkage"
+ di in red _col(10) "- complete: complete linkage "
+ di in red _col(10) "- average(UPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- waverage(WPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- wards: Ward's linkage"
+ di in red "Please correct your method option"
+ exit
+}
+if "`method'"=="single"|"`method'"=="singlelinkage" {
+ local method single
+ local desmethod="Single linkage"
+}
+else if "`method'"=="complete"|"`method'"=="completelinkage" {
+ local desmethod="Complete linkage"
+}
+else if "`method'"=="median"|"`method'"=="medianlinkage" {
+ local desmethod="Median linkage (no dendrogram)"
+}
+else if "`method'"=="centroid"|"`method'"=="centroidlinkage" {
+ local desmethod="Centroid linkage (no dendrogram)"
+}
+else if "`method'"=="average"|"`method'"=="averagelinkage" {
+ local desmethod="Unweighted Pair-Group Method of Average"
+}
+else if "`method'"=="waverage"|"`method'"=="waveragelinkage" {
+ local desmethod="Weighted Pair-Group Method of Average"
+}
+else if "`method'"=="wards"|"`method'"=="wardslinkage" {
+ local desmethod="Ward's linkage"
+}
+
+forvalues i=1/`nbitems' {
+ matrix `whereitems'[1,`i']=`i'
+}
+
+tempvar score
+genscore `varlist',score(`score')
+qui su `score'
+local maxscore=r(max)
+forvalues k=0/`maxscore' {
+ qui count if `score'==`k'
+ local nk`k'=r(N)
+}
+
+qui count
+local N=r(N)
+
+
+di in green "{hline 80}"
+di in green "Number of individuals with none missing values: " in ye `N'
+di in green "Maximal number of modalities for a variable: " in ye "`type'"
+di in green "Proximity measures: " in ye "`desprox'"
+di in green "Method to aggregate clusters: " in ye "`desmethod'"
+di in green "{hline 80}"
+di
+di
+
+/*************************Measure of proximities*********************************/
+if "`matrix'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ /***********************************Proximity AD*************************/
+ if "`prox'"=="matching" { /*ad*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-(`tmp11'+`tmp00')/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="jaccard" { /*a*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/(`N'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity Russel**************************/
+ else if "`prox'"=="russel" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="dice" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-2*`tmp11'/(`N'+`tmp11'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /**********************************Proximity COR*************************/
+ else if "`prox'"=="pearson" { /*corr*/
+ qui corr ``i'' ``j''
+ matrix `proximity'[`i',`j']=sqrt(2*(1-r(rho)))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity CCOV**********************/
+ else if "`prox'"=="ccov" {
+ local dij=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k',cov
+ local covi`i'j`j'k`k'=r(cov_12)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local covi`i'j`j'k`k'=0
+ }
+ else {
+ local covi`i'j`j'k`k'=0
+ }
+ local dij=`dij'+`covi`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-`dij'/`Ntemp'
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'<`dij'/`Ntemp' {
+ local proxmin=`dij'/`Ntemp'
+ }
+ }
+
+ /***********************************Proximity CCOR**********************/
+
+ else if "`prox'"=="ccor" {
+ local dij=0
+ local nnull=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k'
+ local cori`i'j`j'k`k'=r(rho)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local cori`i'j`j'k`k'=0
+ }
+ else {
+ local cori`i'j`j'k`k'=0
+ }
+ if `cori`i'j`j'k`k''!=. {
+ local dij=`dij'+`cori`i'j`j'k`k''*`nk`k''
+ }
+ else if `cori`i'j`j'k`k''==. {
+ local nnull=`nnull'+`nk`k''
+ }
+ }
+ }
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-`dij'/(`Ntemp'-`nnull')))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+
+ /***********************************Proximity MH************************/
+
+ else if "`prox'"=="mh" {
+ local numij=0
+ local denom=0
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ qui count if ``i''==1&``j''==1&`score'==`k'
+ local A=r(N)
+ qui count if ``i''==0&``j''==1&`score'==`k'
+ local B=r(N)
+ qui count if ``i''==1&``j''==0&`score'==`k'
+ local C=r(N)
+ qui count if ``i''==0&``j''==0&`score'==`k'
+ local D=r(N)
+ local numij=`numij'+`A'*`D'/`nk`k''
+ local denomij=`denomij'+`B'*`C'/`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-log(`numij'/`denomij')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'"
+ di ""
+ }
+ else {
+ qui cluster dendro ,labels(name) hor ylabel(,angle(0)) title("Hierarchical Cluster Analysis on variables") subtitle("`desmethod'") xtitle("`desprox' proximities")
+ }
+}
+
+if "`partition'"!="" {
+ foreach i of numlist `partition' {
+ qui cluster gen cluster`i'=group(`i')
+ }
+ tempname clusters
+ mkmat cluster* ,mat(`clusters')
+ matrix rownames `clusters'=`varlist'
+ local compteur=0
+ foreach i of numlist `partition' {
+ local ++compteur
+ di
+ di in green "{hline 30}"
+ di in green "Partition in `i' cluster(s)"
+ di in green "{hline 30}"
+ di
+ forvalues j=1/`i' {
+ local cluster`i'_`j'
+ local nbi`i'_`j'=0
+ forvalues k=1/`nbitems' {
+ if `clusters'[`k',`compteur']==`j' {
+ local cluster`i'_`j' `cluster`i'_`j'' ``k''
+ local ++nbi`i'_`j'
+ }
+ }
+ di in green "Cluster `j': " in ye "`cluster`i'_`j''"
+ }
+ }
+ return matrix clusters=`clusters'
+}
+
+/**********************DETECT OPTION **************************************************/
+
+use `hcaccproxfile',clear
+if "`detect'"!="" {
+ foreach i of numlist `partition' {
+ local liste
+ local part
+ forvalues j=1/`i' {
+ local liste "`liste' `cluster`i'_`j''"
+ local part "`part' `nbi`i'_`j''"
+ }
+ qui detect `liste',part(`part')
+ local detect`i'=r(DETECT)
+ local Iss`i'=r(Iss)
+ local R`i'=r(R)
+ }
+ tempname indexes
+ matrix define `indexes'=J(`compteur',4,0)
+ matrix colnames `indexes'=Clusters DETECT Iss R
+ di ""
+ di in green "{hline 50}"
+ di in green "Indexes to compare the partitions of the items"
+ di in green "{hline 50}"
+ di ""
+ di in green _col(29) "DETECT" _col(43) "Iss" _col(56) "R"
+ local compteur=0
+ foreach k of numlist `partition' {
+ local ++compteur
+ matrix `indexes'[`compteur',1]=`k'
+ matrix `indexes'[`compteur',2]=`detect`k''
+ matrix `indexes'[`compteur',3]=`Iss`k''
+ matrix `indexes'[`compteur',4]=`R`k''
+ di _col(5) in green "`k' cluster(s):" _col(27) in yellow %8.5f `detect`k'' _col(38) %8.5f `Iss`k'' _col(49) %8.5f `R`k''
+ }
+ return matrix indexes=`indexes'
+}
+return local nbvar=`nbitems'
+return matrix measures=`proximity'
+restore, not
+*use `hcaccproxfile',clear
+
+end
diff --git a/Modules/ado/personal/h/hcavar3.4.ado b/Modules/ado/personal/h/hcavar3.4.ado
new file mode 100644
index 0000000..8067c4c
--- /dev/null
+++ b/Modules/ado/personal/h/hcavar3.4.ado
@@ -0,0 +1,489 @@
+*! Version 3.4 26 May 2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* hcavar: Hierachical Clusters Analysis (HCA) of variables
+* Version 3.4: May 26, 2014 /* DETECT option available for polytomous items */
+*
+* Use the Detect Stata program (ssc install detect)
+*
+* Historic :
+* Under the name of -hcaccprox-
+* Version 1 [2004-01-18], Jean-Benoit Hardouin
+* Version 2 [2004-05-12], Jean-Benoit Hardouin
+* Version 3 [2005-12-31], Jean-Benoit Hardouin
+* Version 3.1 [2006-01-15], Jean-Benoit Hardouin /* correction if there is only one individual with a given score*/
+* Version 3.2 [2010-04-15], Jean-Benoit Hardouin /* Possibility to use Polytomous Items with CCOR, CCOV and MH*/
+* Version 3.3 [2014-05-07], Jean-Benoit Hardouin, Bastien Perrot /* HTML option, if option*/
+* Version 3.4 [2014-05-26], Jean-Benoit Hardouin, Bastien Perrot /* DETECT option available for polytomous items */
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2004-2006, 2010 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 hcavar34, rclass
+version 9
+syntax varlist(min=2 numeric) [if] [in] [,PROX(string) METHod(string) PARTition(numlist) MEASures DETect MATrix(string) noDENDROgram HTML(string)]
+
+tempfile hcaccproxfile
+qui save `hcaccproxfile',replace
+preserve
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`html'"!="" {
+ //set scheme sj
+ //local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+local type=0
+forvalues i=1/`nbitems' {
+ qui drop if ``i''==.
+ qui inspect ``i''
+ if r(N_unique)>`type'&r(N_unique)!=. {
+ local type=r(N_unique)
+ }
+ else if r(N_unique)>`type'&r(N_unique)==. {
+ local type "100"
+ }
+}
+if `type'==100 {
+ local type ">99"
+}
+
+tempname proximity whereitems
+
+local prox=lower("`prox'")
+local method=lower("`method'")
+matrix define `proximity'=J(`nbitems',`nbitems',0)
+matrix define `whereitems'=J(`=`nbitems'-1',`nbitems',0)
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`matrix'"!="" {
+ local desprox="Defined by the user"
+}
+if "`prox'"=="" {
+ local prox="pearson"
+}
+else if "`prox'"=="a" {
+ local prox="jaccard"
+}
+else if "`prox'"=="ad" {
+ local prox="matching"
+}
+else if "`prox'"=="corr" {
+ local prox="pearson"
+}
+if "`type'">"2"&"`prox'"!="pearson"&"`prox'"!="ccov"&"`prox'"!="ccor"&"`prox'"!="mh" {
+ di in red "Only the {hi:pearson}, {hi:ccov} and {hi:ccor} measures of proximity are available with ordinal or numerous variables"
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+
+if "`partition'"==""&"`detect'"!="" {
+ di in ye "option partition() required"
+ error 198
+}
+local existmeas=0
+foreach i in jaccard matching pearson russel dice ccor mh ccov {
+ if "`prox'"=="`i'" {
+ local existmeas=1
+ }
+}
+if `existmeas'==0 {
+ di in red "You must define an existing measure of proximity (jaccard(a), matching(ad), pearson(cor), russel, dice, ccov, ccor, mh)."
+ di in red "Please correct your {hi:prox} option."
+ exit
+}
+if "`prox'"=="ccov"|"`prox'"=="mh" {
+ local proxmin=0
+}
+
+if "`prox'"=="matching" {
+ local desprox="Matching"
+}
+else if "`prox'"=="jaccard" {
+ local desprox="Jaccard"
+}
+else if "`prox'"=="russel" {
+ local desprox="Russel"
+}
+else if "`prox'"=="dice" {
+ local desprox="Dice"
+}
+else if "`prox'"=="pearson" {
+ local desprox="Pearson"
+}
+else if "`prox'"=="ccov" {
+ local desprox="Conditional covariances"
+}
+else if "`prox'"=="ccor" {
+ local desprox="Conditional correlations"
+}
+else if "`prox'"=="mh" {
+ local desprox="Mantel Hanzel"
+}
+
+/**************************PROXIMITIES MEASURES DESCRIPTION************************/
+
+if "`method'"=="upgma"|"`method'"=="" {
+ local method="average"
+}
+if "`method'"=="wpgma"|"`method'"=="" {
+ local method="waverage"
+}
+local vermethod=0
+foreach i in average waverage single centroid median complete wards {
+ if "`method'"=="`i'" {
+ local vermethod=1
+ }
+ }
+
+if `vermethod'==0 {
+ di in red "You must define an existing method to define the proximity between two clusters of items:"
+ di in red _col(10) "- single: single linkage"
+ di in red _col(10) "- complete: complete linkage "
+ di in red _col(10) "- average(UPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- waverage(WPGMA): Unweighted Pair-Group Method of Average"
+ di in red _col(10) "- wards: Ward's linkage"
+ di in red "Please correct your method option"
+ exit
+}
+if "`method'"=="single"|"`method'"=="singlelinkage" {
+ local method single
+ local desmethod="Single linkage"
+}
+else if "`method'"=="complete"|"`method'"=="completelinkage" {
+ local desmethod="Complete linkage"
+}
+else if "`method'"=="median"|"`method'"=="medianlinkage" {
+ local desmethod="Median linkage (no dendrogram)"
+}
+else if "`method'"=="centroid"|"`method'"=="centroidlinkage" {
+ local desmethod="Centroid linkage (no dendrogram)"
+}
+else if "`method'"=="average"|"`method'"=="averagelinkage" {
+ local desmethod="Unweighted Pair-Group Method of Average"
+}
+else if "`method'"=="waverage"|"`method'"=="waveragelinkage" {
+ local desmethod="Weighted Pair-Group Method of Average"
+}
+else if "`method'"=="wards"|"`method'"=="wardslinkage" {
+ local desmethod="Ward's linkage"
+}
+
+forvalues i=1/`nbitems' {
+ matrix `whereitems'[1,`i']=`i'
+}
+
+tempvar score
+genscore `varlist',score(`score')
+qui su `score'
+local maxscore=r(max)
+forvalues k=0/`maxscore' {
+ qui count if `score'==`k'
+ local nk`k'=r(N)
+}
+
+qui count
+local N=r(N)
+
+
+di in green "{hline 80}"
+di in green "Number of individuals with none missing values: " in ye `N'
+di in green "Maximal number of modalities for a variable: " in ye "`type'"
+di in green "Proximity measures: " in ye "`desprox'"
+di in green "Method to aggregate clusters: " in ye "`desmethod'"
+di in green "{hline 80}"
+di
+di
+
+/*************************Measure of proximities*********************************/
+if "`matrix'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ /***********************************Proximity AD*************************/
+ if "`prox'"=="matching" { /*ad*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-(`tmp11'+`tmp00')/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="jaccard" { /*a*/
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/(`N'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity Russel**************************/
+ else if "`prox'"=="russel" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-`tmp11'/`N')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity A**************************/
+ else if "`prox'"=="dice" {
+ qui count if ``i''==1&``j''==1
+ local tmp11=r(N)
+ qui count if ``i''==0&``j''==0
+ local tmp00=r(N)
+
+ matrix `proximity'[`i',`j']=sqrt(1-2*`tmp11'/(`N'+`tmp11'-`tmp00'))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /**********************************Proximity COR*************************/
+ else if "`prox'"=="pearson" { /*corr*/
+ qui corr ``i'' ``j''
+ matrix `proximity'[`i',`j']=sqrt(2*(1-r(rho)))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+ /***********************************Proximity CCOV**********************/
+ else if "`prox'"=="ccov" {
+ local dij=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k',cov
+ local covi`i'j`j'k`k'=r(cov_12)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local covi`i'j`j'k`k'=0
+ }
+ else {
+ local covi`i'j`j'k`k'=0
+ }
+ local dij=`dij'+`covi`i'j`j'k`k''*`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-`dij'/`Ntemp'
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'<`dij'/`Ntemp' {
+ local proxmin=`dij'/`Ntemp'
+ }
+ }
+
+ /***********************************Proximity CCOR**********************/
+
+ else if "`prox'"=="ccor" {
+ local dij=0
+ local nnull=0
+ local Ntemp=`N'
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ if `nk`k''>1 {
+ qui corr ``i'' ``j'' if `score'==`k'
+ local cori`i'j`j'k`k'=r(rho)
+ }
+ else if `nk`k''==1 {
+ local Ntemp=`Ntemp'-1
+ local cori`i'j`j'k`k'=0
+ }
+ else {
+ local cori`i'j`j'k`k'=0
+ }
+ if `cori`i'j`j'k`k''!=. {
+ local dij=`dij'+`cori`i'j`j'k`k''*`nk`k''
+ }
+ else if `cori`i'j`j'k`k''==. {
+ local nnull=`nnull'+`nk`k''
+ }
+ }
+ }
+
+ matrix `proximity'[`i',`j']=sqrt(2*(1-`dij'/(`Ntemp'-`nnull')))
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ }
+
+
+ /***********************************Proximity MH************************/
+
+ else if "`prox'"=="mh" {
+ local numij=0
+ local denom=0
+ forvalues k=1/`=`maxscore'-1' {
+ if `nk`k''!=0 {
+ qui count if ``i''==1&``j''==1&`score'==`k'
+ local A=r(N)
+ qui count if ``i''==0&``j''==1&`score'==`k'
+ local B=r(N)
+ qui count if ``i''==1&``j''==0&`score'==`k'
+ local C=r(N)
+ qui count if ``i''==0&``j''==0&`score'==`k'
+ local D=r(N)
+ local numij=`numij'+`A'*`D'/`nk`k''
+ local denomij=`denomij'+`B'*`C'/`nk`k''
+ }
+ }
+
+ matrix `proximity'[`i',`j']=-log(`numij'/`denomij')
+ matrix `proximity'[`j',`i']=`proximity'[`i',`j']
+ if `proxmin'"
+ di ""
+ }
+ else {
+ qui cluster dendro ,labels(name) hor ylabel(,angle(0)) title("Hierarchical Cluster Analysis on variables") subtitle("`desmethod'") xtitle("`desprox' proximities")
+ }
+}
+
+if "`partition'"!="" {
+ foreach i of numlist `partition' {
+ qui cluster gen cluster`i'=group(`i')
+ }
+ tempname clusters
+ mkmat cluster* ,mat(`clusters')
+ matrix rownames `clusters'=`varlist'
+ local compteur=0
+ foreach i of numlist `partition' {
+ local ++compteur
+ di
+ di in green "{hline 30}"
+ di in green "Partition in `i' cluster(s)"
+ di in green "{hline 30}"
+ di
+ forvalues j=1/`i' {
+ local cluster`i'_`j'
+ local nbi`i'_`j'=0
+ forvalues k=1/`nbitems' {
+ if `clusters'[`k',`compteur']==`j' {
+ local cluster`i'_`j' `cluster`i'_`j'' ``k''
+ local ++nbi`i'_`j'
+ }
+ }
+ di in green "Cluster `j': " in ye "`cluster`i'_`j''"
+ }
+ }
+ return matrix clusters=`clusters'
+}
+
+/**********************DETECT OPTION **************************************************/
+
+use `hcaccproxfile',clear
+if "`detect'"!="" {
+ foreach i of numlist `partition' {
+ local liste
+ local part
+ forvalues j=1/`i' {
+ local liste "`liste' `cluster`i'_`j''"
+ local part "`part' `nbi`i'_`j''"
+ }
+ qui detect `liste',part(`part')
+ local detect`i'=r(DETECT)
+ local Iss`i'=r(Iss)
+ local R`i'=r(R)
+ }
+ tempname indexes
+ matrix define `indexes'=J(`compteur',4,0)
+ matrix colnames `indexes'=Clusters DETECT Iss R
+ di ""
+ di in green "{hline 50}"
+ di in green "Indexes to compare the partitions of the items"
+ di in green "{hline 50}"
+ di ""
+ di in green _col(29) "DETECT" _col(43) "Iss" _col(56) "R"
+ local compteur=0
+ foreach k of numlist `partition' {
+ local ++compteur
+ matrix `indexes'[`compteur',1]=`k'
+ matrix `indexes'[`compteur',2]=`detect`k''
+ matrix `indexes'[`compteur',3]=`Iss`k''
+ matrix `indexes'[`compteur',4]=`R`k''
+ di _col(5) in green "`k' cluster(s):" _col(27) in yellow %8.5f `detect`k'' _col(38) %8.5f `Iss`k'' _col(49) %8.5f `R`k''
+ }
+ return matrix indexes=`indexes'
+}
+return local nbvar=`nbitems'
+return matrix measures=`proximity'
+restore, not
+*use `hcaccproxfile',clear
+
+end
diff --git a/Modules/ado/personal/i/imputeitems - Copie.ado b/Modules/ado/personal/i/imputeitems - Copie.ado
new file mode 100644
index 0000000..4760f0f
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems - Copie.ado
@@ -0,0 +1,193 @@
+*! version 2.4 3 May 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+* Version 2.4 : May 3, 2013 (Jean-Benoit Hardouin) /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2006-2008,2013 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 imputeitems
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int -1) noround]
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==-1 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if `r(min)'!=0&(`r(max)'!=1&"`method'"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i'' `ifif'
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputeitems v2.4.ado b/Modules/ado/personal/i/imputeitems v2.4.ado
new file mode 100644
index 0000000..4760f0f
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems v2.4.ado
@@ -0,0 +1,193 @@
+*! version 2.4 3 May 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+* Version 2.4 : May 3, 2013 (Jean-Benoit Hardouin) /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2006-2008,2013 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 imputeitems
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int -1) noround]
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==-1 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if `r(min)'!=0&(`r(max)'!=1&"`method'"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i'' `ifif'
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputeitems.ado b/Modules/ado/personal/i/imputeitems.ado
new file mode 100644
index 0000000..a90a9d3
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems.ado
@@ -0,0 +1,193 @@
+*! version 2.5 17 December 2021
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+* Version 2.4 : May 3, 2013 (Jean-Benoit Hardouin) /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2006-2008,2013 2021 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 imputeitems
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int -1) noround]
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==-1 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if "`r(min)'"!="0"&("`r(max)'"!="1"&"`method'"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i'' `ifif'
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputeitems.hlp b/Modules/ado/personal/i/imputeitems.hlp
new file mode 100644
index 0000000..a75c9aa
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems.hlp
@@ -0,0 +1,70 @@
+{smcl}
+{* 6May2013}{...}
+{hline}
+help for {hi:imputeitems}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Imputation of missing item responses}
+
+{p 8 14 2}{cmd:imputeitems} {it:varlist} [{it:if}] [,{cmdab:pref:ix}({it:string}) {cmdab:meth:od}({it:string}) {cmdab:rand:om} {cmdab:max}({it:#})]
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:imputeitems} imputes missing item responses by different ways : Item Mean Substitution (IMS), Person Mean Substitution (PMS), Corrected Item Mean Substiutution (CIM), Interitem Correlation Substitution (ICS), logistic model (LOG) and Worst Case (WORST). A random process can be added to several methods.
+
+{title:Options}
+
+{p 4 8 2}{cmd:prefix} defines the prefix to use to name the imputted variables (this prefix is followed by the name of the initial variable). By default, this prefix is "imp".
+
+{p 4 8 2}{cmd:method} defines the method to impute missing data :
+
+{p 8 8 2}{it:pms} computes the proportion of positive response of each individual on non missing items, and impute a deterministic result (if p<.5 then 0, else 1),
+
+{p 8 8 2}{it:ims} computes the proportion of positive response to each items, and impute a deterministic result (if p<.5 then 0, else 1),
+
+{p 8 8 2}{it:cim} computes the proportion of positive response to each items, corrected by the ability of the individual and impute a deterministic result (if p<.5 then 0, else 1),
+
+{p 8 8 2}{it:ics} searchs for each item the more correlated item and replaces a missing data by the data of this more correlated item (if the other response is missing too, there is no imputation),
+
+{p 8 8 2}{it:log} explains the responses of each item by a logistic model where the independent variables are the responses to the others items. Only significant variables are rettained (5%). These methods impute a deterministic result (if p<.5 then 0, else 1) [{it:log}] to missing responses (if the response to an independant variable is missing, there is no imputation),
+
+{p 8 8 2}{it:worst} replaces the missing data by a 0.
+
+{p 4 8 2}{cmd:random} adds a random effect to the imputation process (available only with {it:pms}, {it:ims}, {it:cim} or {it:log}). In these cases, the imputed value is randomly drawed from a binomial distribution using the parameter p.
+
+{p 4 8 2}{cmd:noround} avoids to round the imputed values to the nearest integer.
+
+{p 4 8 2}{cmd:max} allows imputing missing values only for individuals with a maximal number of missing values defined with this option.
+
+{p 4 8 2}By default, {it:pms} method is working.
+
+{p 4 8 2}Old names of methods ({it:bip}, {bii}, {it:bic} and {it:bil} continues to run. They actually correspond to the add of the {cmd:random} option to the {it:pms}, {it:ims}, {it:cim} and {it:log} methods.
+
+
+{title:Example}
+
+ {cmd:. imputeitems itemA*} /*PMS method, IMP prefix*/
+
+ {cmd:. imputeitems itemA*, prefix(cim) method(cim)}
+
+ {cmd:. imputeitems itemA*, method(log) random}
+
+
+{title:Reference}
+
+{p 4 8 2}{cmd:Huisman M.} (2000), Imputation of missing item responses: some simple techniques. {it: Quality & Quantity}, {cmd:34}, 331-351.
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
+
diff --git a/Modules/ado/personal/i/imputeitems.txt b/Modules/ado/personal/i/imputeitems.txt
new file mode 100644
index 0000000..15d21a7
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems.txt
@@ -0,0 +1,190 @@
+*! version 2.3 19 February 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2006-2008,2013 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 imputeitems
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int 0) noround]
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==0 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if `r(min)'!=0&(`r(max)'!=1&"`method"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i'' `ifif'
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputeitems2.ado b/Modules/ado/personal/i/imputeitems2.ado
new file mode 100644
index 0000000..042e8f8
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems2.ado
@@ -0,0 +1,201 @@
+*! version 2.3 19 February 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2006-2008,2013 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 imputeitems2
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int 0) noround replace]
+
+
+
+if "`noround'" != "" di "noround"
+if "`round'" != "" di "round"
+
+
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==0 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if `r(min)'!=0&(`r(max)'!=1&"`method'"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ tempvar `prefix'``i''
+
+ *di "`prefix'``i''"
+ qui gen ``prefix'``i'''=`imp`i'' `ifif'
+ replace ``i'' = ``prefix'``i'''
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace ``prefix'``i'''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputeitems_1.ado b/Modules/ado/personal/i/imputeitems_1.ado
new file mode 100644
index 0000000..4760f0f
--- /dev/null
+++ b/Modules/ado/personal/i/imputeitems_1.ado
@@ -0,0 +1,193 @@
+*! version 2.4 3 May 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputeitems: Imputation of missing data of binary items
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the BIL method*/
+* Version 1.2 : March 9, 2007 (Jean-Benoit Hardouin) /*IF*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*new names of the methods, MAX option*/
+* Version 2.1 : December 3, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+* Version 2.2 : January 28, 2013 (Jean-Benoit Hardouin) /*noround option*/
+* Version 2.3 : February 19, 2013 (Jean-Benoit Hardouin) /*polytomous items with PMS method*/
+* Version 2.4 : May 3, 2013 (Jean-Benoit Hardouin) /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2006-2008,2013 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 imputeitems
+version 9
+syntax varlist(min=2 numeric) [if/] [, PREFix(string) METHod(string) RANDom max(int -1) noround]
+
+if "`if'"=="" {
+ local if=1
+ local ifif
+}
+else {
+ local ifif if `if'
+}
+
+*di "IF : `if' `ifif'"
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==-1 {
+ local max=`nbitems'
+}
+
+if "`method'"=="" {
+ local method pms
+}
+forvalues i=1/`nbitems' {
+ qui su ``i'' `ifif'
+ if `r(min)'!=0&(`r(max)'!=1&"`method'"!="pms") {
+ di in red "The {hi:imputeqol} command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+}
+
+if "`method'"!="pms"&"`method'"!="ims"&"`method'"!="cim"&"`method'"!="ics"&"`method'"!="bip"&"`method'"!="bil"&"`method'"!="bic"&"`method'"!="bii"&"`method'"!="log"&"`method'"!="worst" {
+ di in red "The method option is unknow (choose among pms, ims, cim, ics, log and worst)"
+ error
+}
+forvalues i=1/`nbitems'{
+ qui su ``i'' `ifif'
+ local mean`i'=r(mean)
+}
+
+if "`method'"=="pms"&"`random'"!="" {
+ local method bip
+}
+else if "`method'"=="ims"&"`random'"!="" {
+ local method bii
+}
+else if "`method'"=="log"&"`random'"!="" {
+ local method bil
+}
+else if "`method'"=="cim"&"`random'"!="" {
+ local method bic
+}
+else if ("`method'"=="ics"|"`method'"=="worst")&"`random'"!="" {
+ di in green "The random process is not available with the {hi:ics} or {hi:worst} methods. The {hi:random} option is ignored."
+ local random
+}
+
+
+forvalues i=1/`nbitems' {
+ tempvar imp`i' tmp`i'
+ if "`method'"=="pms"|"`method'"=="bip"|"`method'"=="cim"|"`method'"=="bic" {
+ qui egen `imp`i''=rowtotal(`varlist') `ifif'
+ qui egen `tmp`i''=rownonmiss(`varlist') `ifif'
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`method'"=="pms"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bip" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ else if "`method'"=="cim"|"`method'"=="bic"{
+ qui replace `imp`i''=`imp`i''*`tmp`i''*`mean`i'' `ifif'
+ qui replace `tmp`i''=0 `ifif'
+ forvalues j=1/`nbitems' {
+ qui replace `tmp`i''=`tmp`i''+`mean`j'' if ``j''!=.&`if'
+ }
+ qui replace `imp`i''=`imp`i''/`tmp`i'' `ifif'
+ qui replace `imp`i''=1 if `imp`i''>1&`imp`i''!=.&`if'
+ qui replace `imp`i''=0 if `imp`i''<0&`imp`i''!=.&`if'
+ if "`method'"=="cim"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bic" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ }
+ else if "`method'"=="ims"|"`method'"=="bii" {
+ qui gen `imp`i''=`mean`i'' `ifif'
+ if "`method'"=="ims"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') `ifif'
+ }
+ else if "`method'"=="bii" {
+ qui replace `imp`i''=uniform()<`imp`i'' `ifif'
+ }
+ }
+ else if "`method'"=="ics" {
+ local item=0
+ local corrmax=-2
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ qui corr ``i'' ``j'' `ifif'
+ if r(rho)>`corrmax'&r(rho)!=. {
+ local item `j'
+ local corrmax=r(rho)
+ }
+ }
+ }
+ di "A missing value for the item ``i'' is replaced by the value of the item `item'"
+ qui gen `imp`i''=``i'' `ifif'
+ qui replace `imp`i''=``item'' if ``i''==.&`if'
+ }
+ else if "`method'"=="log"|"`method'"=="bil" {
+ local liste`i'
+ forvalues j=1/`nbitems' {
+ if `i'!=`j' {
+ local liste`i' `liste`i'' ``j''
+ }
+ }
+ qui sw ,pr(0.05): logit ``i'' `liste`i'' `ifif'
+ *local select :colnames e(b)
+ local select=substr("`:colnames e(b)'",1,length("`:colnames e(b)'")-5)
+ qui logit ``i'' `select' `ifif'
+ qui predict `imp`i'' `ifif'
+ if "`method'"=="log"&"`round'"=="" {
+ qui replace `imp`i''=round(`imp`i'') if `imp`i''!=.&`if'
+ }
+ else if "`method'"=="bil" {
+ qui replace `imp`i''=uniform()<`imp`i'' if `imp`i''!=.&`if'
+ }
+ }
+ else if "`method'"=="worst" {
+ qui gen `imp`i''=0 `ifif'
+ }
+}
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.&`if'
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i'' `ifif'
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputemok.ado b/Modules/ado/personal/i/imputemok.ado
new file mode 100644
index 0000000..93d5ece
--- /dev/null
+++ b/Modules/ado/personal/i/imputemok.ado
@@ -0,0 +1,135 @@
+*! version 2.1 24 November 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* impmok: Imputation of missing data by a Mokken model
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*MAX option*/
+* Version 2.1 : November 24, 2008 (Jean-Benoit Hardouin) /*correction of a bug with the MAX option*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2006, 2008 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 imputemok , rclass
+version 9
+syntax varlist(min=2 numeric) [, PREFix(string) max(int 0)]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+if `max'==0 {
+ local max=`nbitems'
+}
+
+
+
+tempname p
+matrix `p'=J(3,`nbitems',0)
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ if `r(min)'!=0&`r(max)'!=1 {
+ di in red "The -impmok- command runs only with dichotomous items"
+ error
+ }
+ local p`i'=r(mean)
+ matrix `p'[1,`i']=`i'
+}
+
+forvalues place=1/`nbitems' {
+ local pmax=0
+ local itemax=0
+ forvalues i=1/`nbitems' {
+ local t=`p'[1,`i']
+ if `p`i''>`pmax'&`t'!=0 {
+ local pmax=`p`i''
+ local itemax=`i'
+ }
+ }
+ matrix `p'[1,`itemax']=0
+ matrix `p'[2,`place']=`itemax'
+ matrix `p'[3,`place']=`pmax'
+}
+local liste
+forvalues i=1/`nbitems' {
+ local t=`p'[2,`i']
+ local liste "`liste' ``t''"
+ tempname imp`i'
+ qui gen `imp`i''`i'=``i''
+}
+forvalues j=`=`nbitems'-1'(-1)1 {
+ local i=`p'[2,`j']
+ local suiv=`p'[2,`=`j'+1']
+ qui replace `imp`i''`i'=1 if `imp`suiv''`suiv'==1&`imp`i''`i'==.
+}
+forvalues j=2/`nbitems'{
+ local i=`p'[2,`j']
+ local prec=`p'[2,`=`j'-1']
+ qui replace `imp`i''`i'=0 if `imp`prec''`prec'==0&`imp`i''`i'==.
+}
+forvalues j=1/`nbitems' {
+ local i=`p'[2,`j']
+ local suiv=`p'[2,`=`j'+1']
+ local prec=`p'[2,`=`j'-1']
+ tempname prec0`i' prec1`i'
+ qui gen `prec0`i''=0
+ qui gen `prec1`i''=0
+ if `j'!=1 {
+ qui replace `prec0`i''=`prec0`prec''+1 if `imp`prec''`prec'==0
+ qui replace `prec0`i''=`prec0`prec'' if `imp`prec''`prec'!=0
+ qui replace `prec1`i''=`prec1`prec''+1 if `imp`prec''`prec'==1
+ qui replace `prec1`i''=`prec1`prec'' if `imp`prec''`prec'!=1
+ qui replace `imp`i''`i'=0 if `prec0`i''!=0&`prec0`i''>=`prec1`i''&`imp`i''`i'==.
+ }
+}
+forvalues j=`nbitems'(-1)1 {
+ local i=`p'[2,`j']
+ local suiv=`p'[2,`=`j'+1']
+ local prec=`p'[2,`=`j'-1']
+ tempname suiv0`i' suiv1`i'
+ qui gen `suiv0`i''=0
+ qui gen `suiv1`i''=0
+ if `j'!=`nbitems' {
+ qui replace `suiv0`i''=`suiv0`suiv''+1 if `imp`suiv''`suiv'==0
+ qui replace `suiv0`i''=`suiv0`suiv'' if `imp`suiv''`suiv'!=0
+ qui replace `suiv1`i''=`suiv1`suiv''+1 if `imp`suiv''`suiv'==1
+ qui replace `suiv1`i''=`suiv1`suiv'' if `imp`suiv''`suiv'!=1
+ qui replace `imp`i''`i'=1 if `suiv0`i''<=`suiv1`i''&`suiv1`i''!=0&`imp`i''`i'==.
+ }
+}
+forvalues j=1/`nbitems' {
+ local i=`p'[2,`j']
+ qui replace `imp`i''`i'=uniform()<=`p`i'' if `imp`i''`i'==.
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i''`i'
+}
+
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputemok.hlp b/Modules/ado/personal/i/imputemok.hlp
new file mode 100644
index 0000000..a4f96d9
--- /dev/null
+++ b/Modules/ado/personal/i/imputemok.hlp
@@ -0,0 +1,58 @@
+{smcl}
+{* 30June2008}{...}
+{hline}
+help for {hi:imputemok}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Imputation of missing item responses with the Mokken scaling}
+
+{p 8 14 2}{cmd:imputemok} {it:varlist} [,{cmdab:pref:ix}({it:string}) {cmdab:max}({it:#})]
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:imputemok} imputes missing item responses with the Mokken scaling as defined in Huisman and Molenaar (2001). This module runs only with dichotomous items.
+
+{p 4 4 2}The following algorithm is used:
+
+{p 8 4 2}First, the items are ordered according to the percentage of positive responses (in a decreasing order).
+
+{p 8 4 2}For each individual, if a positive response follows a missing response, it is imputed to 1.
+
+{p 8 4 2}Else if a negative response precedes a missing response, it is imputed to 0.
+
+{p 8 4 2}Else we count the number of positive and negative responses preceding a missing response and if the number of negative response is larger or equal than the number of positive responses, the missing value is imputed to 0.
+
+{p 8 4 2}Else we count the number of positive and negative responses following a missing response and if the number of positive response is larger or equal than the number of negative responses, the missing value is imputed to 1.
+
+{p 8 4 2}Else, the missing value is imputed by drawing a random number based on the observed proportion of positive responses to the item.
+
+{title:Options}
+
+{p 4 8 2}{cmd:prefix} defines the prefix to use to name the imputted variables (this prefix is followed by the name of the initial variable). By default, this prefix is "imp".
+
+{p 4 8 2}{cmd:max} allows imputing missing values only for individuals with a maximal number of missing values defined with this option.
+
+{title:Example}
+
+ {cmd:. imputemok itemA*}
+
+ {cmd:. imputemok itemA*,prefix(new)}
+
+
+{title:Reference}
+
+{p 4 8 2}{cmd:Huisman M. and Molenaar I. W.}, {it:Imputation of missing scale data with item response models}. In A. Boomsma, M.A.J. van Duijn, & T.A.B. Snijders (Eds.), {it: Essays on item response theory} (pp. 221-244).
+New York: Springer-Verlag, 2001.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
diff --git a/Modules/ado/personal/i/imputerasch.ado b/Modules/ado/personal/i/imputerasch.ado
new file mode 100644
index 0000000..704e30a
--- /dev/null
+++ b/Modules/ado/personal/i/imputerasch.ado
@@ -0,0 +1,146 @@
+*! version 2 30 June 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* imputerasch: Imputation of missing data by a Rasch model
+*
+* Version 1 : November 25, 2006 (Jean-Benoit Hardouin) /*Dichotomous data*/
+* Version 1.1 : January 26, 2007 (Jean-Benoit Hardouin) /*Correction of a bug with the Binomial option*/
+* Version 2 : June 30, 2008 (Jean-Benoit Hardouin) /*norandom option, max option*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2006-2008 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 imputerasch
+version 9
+syntax varlist(min=2 numeric) [, PREFix(string) noBINomial noRANDom SAVEProba(string) NBITeration(integer 1) DETails MAX(int 0) ]
+preserve
+qui ds
+local order=r(varlist)
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if `max'==0 {
+ local max=`nbitems'
+}
+
+if "`random'"!="" {
+ local binomial nobinomial
+}
+
+if "`binomial'"==""&`nbiteration'!=1 {
+ local binomial nobinomial
+ di in green "You must use the {hi:norandom} option when you use iterative process. This option is assumed."
+}
+
+if `nbiteration'!=1 {
+ di in ye "Iteration : 1"
+}
+
+tempvar lt0 lt1 score id item lt name
+qui gen `id'=_n
+qui egen `score'=rowtotal(`varlist')
+forvalues i=1/`nbitems' {
+ qui rename ``i'' `name'`i'
+}
+
+qui reshape long `name' ,i(`id') j(`item')
+forvalues i=1/`nbitems' {
+ qui gen ``i''=`item'==`i'
+}
+qui gllamm `name' `varlist' ,family(bin) nocons link(logit) i(`id') it(1)
+qui gllapred `lt' ,u
+qui bysort `id':egen `lt'=min(`lt'm1)
+drop `lt's1 `lt'm1
+tempname diff
+matrix `diff'=e(b)
+drop `varlist'
+qui reshape wide `name' ,i(`id') j(`item')
+forvalues i=1/`nbitems' {
+ qui rename `name'`i' ``i''
+ tempvar imp`i'
+ local diff`i'=`diff'[1,`i']
+ qui gen `imp`i''=exp(`lt'-`diff`i'')/(1+exp(`lt'-`diff`i''))
+ if "`saveproba'"!="" {
+ qui gen `saveproba'``i''=`imp`i''
+ }
+ if "`binomial'"!="" {
+ qui replace `imp`i''=round(`imp`i'')
+ }
+ else {
+ qui replace `imp`i''=uniform()<`imp`i''
+ }
+}
+
+
+restore,not
+forvalues i=1/`nbitems' {
+ qui replace `imp`i''=``i'' if ``i''!=.
+ if "`prefix'"=="" {
+ local prefix imp
+ }
+ qui gen `prefix'``i''=`imp`i''
+}
+
+if "`details'"!="" {
+ forvalues i=1/`nbitems' {
+ qui count if ``i''==.
+ local nbmiss`i'=r(N)
+ di in ye "``i'':" in gr " Number of missing data: " in ye "`nbmiss`i''"
+ }
+}
+if `nbiteration'>1 {
+ local flag=0
+ local it=2
+ tempname p new
+ while `flag'!=1&`it'<=`nbiteration' {
+ di in ye "Iteration : `it'"
+ imputerasch `prefix'`1'-`prefix'``nbitems'', savep(`p') prefix(`new') nobin
+ local flag=1
+ forvalues i=1/`nbitems' {
+ qui replace `new'`prefix'``i''=round(`p'`prefix'``i'') if ``i''==.
+ qui corr `prefix'``i'' `new'`prefix'``i''
+ local rho=round(r(rho)*1000000)
+ qui count if `prefix'``i''==`new'`prefix'``i''&``i''==.
+ qui count if ``i''==.
+ local nbmiss`i'=r(N)
+ local coher=r(N)
+ local txcoher=`coher'/`nbmiss`i''*100
+ di in ye "``i'':" in gr " Coherence rate between iterations `it' and `=`it'-1': " in ye %6.2f `txcoher' in gr "%"
+ if int(`txcoher')!=100 {
+ local flag=0
+ }
+ qui replace `prefix'``i''=`new'`prefix'``i''
+ }
+ drop `p'`prefix'`1'-`p'`prefix'``nbitems'' `new'`prefix'`1'-`new'`prefix'``nbitems''
+ local ++it
+ }
+}
+
+tempvar miss
+qui egen `miss'=rowmiss(`varlist')
+forvalues i=1/`nbitems' {
+ qui replace `prefix'``i''=. if ``i''==.&`miss'>`max'
+}
+
+end
diff --git a/Modules/ado/personal/i/imputerasch.hlp b/Modules/ado/personal/i/imputerasch.hlp
new file mode 100644
index 0000000..8e38e21
--- /dev/null
+++ b/Modules/ado/personal/i/imputerasch.hlp
@@ -0,0 +1,63 @@
+{smcl}
+{* 30june2008}{...}
+{hline}
+help for {hi:imputerasch}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Imputation of missing binary variables by a Rasch model}
+
+{p 8 14 2}{cmd:imputerasch} {it:varlist} [{cmd:,} {cmdab:pref:ix}({it:string}) {cmdab:noran:dom} {cmdab:savep:roba}({it:string}) {cmdab:nbit:eration}({it:#}) {cmdab:det:ails} {cmdab:max}({it:#})]
+
+{p 8 14 2}{it:varlist} is a list of two or more existing dichotomous variables.
+
+{title:Description}
+
+{p 4 8 2}{cmd:imputerasch} imputes missing binary data by a Rasch model.
+The parameters of the Rasch model are estimated on complete data, then the missing data are imputed from the estimated probability
+for each individual to response to each item.
+By default, the imputed value is a result of a random draw within a Bernouilli random variable with this probability used like
+parameter, but it is possible to affect more deterministically the value of the missing data (0 if p<0.5 and 1 if p>=.5) with
+the {cmd:norandom} option.
+ An iterative procedure can be run in a second time by estimating parameters of the Rasch model on existing and imputing data,
+ and by eventually correcting missing data at each step (see the {cmd:nbiteration} option).
+ This procedure is stopped as soon the allowed maximal number of iterations is attained, or as soon the imputed values are stable.
+
+{title:Options}
+
+{p 4 8 2}{cmd:prefix}. The former variables (with missing data) are keeped. New variables are created by imputing new values to missing data.
+The name of these new variables are the names of the former variables preeceded by the prefix defined in this option. By default, this prefix is "imp".
+
+{p 4 8 2}{cmd:norandom} avoids to randomly draw the value of imputation (by default). A deterministic process is used : if the expected probability is <0.5, imputed value is 0, else imputed value is 1
+(the old name of this option, {cmd:nobinomial}, continues to run).
+
+{p 4 8 2}{cmd:saveproba} allows saving the expected probability in variables whose the names begin by the string defined in this option.
+
+{p 4 8 2}{cmd:nbiteration} realizes an iterative procedure which is stopped as soon as the maximal number of iterations is attained, or as soon as the imputed data are stable.
+
+{p 4 8 2}{cmd:details} gives details on the imputation.
+
+{p 4 8 2}{cmd:max} allows imputing missing values only for individuals with a maximal number of missing values defined with this option.
+
+
+
+{title:Example}
+
+ {inp:. imputerasch item*}
+
+ {inp:. imputerasch item*, norandom saveproba(p) prefix(dataimputed) max(4)}
+
+ {inp:. imputerasch item1-item5, nbiteration(5) details}
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
+
diff --git a/Modules/ado/personal/i/irtpoly.ado b/Modules/ado/personal/i/irtpoly.ado
new file mode 100644
index 0000000..ce56d30
--- /dev/null
+++ b/Modules/ado/personal/i/irtpoly.ado
@@ -0,0 +1,414 @@
+program define irtpoly,eclass
+version 11.0
+syntax varlist(min=3 numeric) [if] [in] [,test Graph group(string) latent(string) REPlace Fixed(string) FIXEDVar(real -1) rsm rasch Last SASOUTput long Covariables(varlist) Covariablemean(varname) noCentered Project(string)]
+preserve
+
+
+capture mkdir "c:/data/irtpoly//`project'/"
+if !_rc {
+ di in green "The directory c:/data/irtpoly//`project' has been created"
+}
+
+local dir="c:/data/irtpoly//`project'/"
+local savegroup=1
+if "`group'"=="" {
+ tempname group
+ local savegroup=0
+}
+local savelatent=1
+if "`latent'"=="" {
+ tempname latent
+ local savelatent=0
+}
+tempvar order
+gen `order'=_n
+tempfile pcmsasfile
+qui save `pcmsasfile'
+qui count `if' `in'
+local nbind=r(N)
+tokenize `varlist'
+local nbitems:word count `varlist'
+local max=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ local max`i'=r(max)
+ if `max`i''>`max' {
+ local max=`max`i''
+ }
+}
+tempname freq
+contract `varlist' `covariables' `covariablemean', freq(`freq')
+qui sort `varlist'
+qui outsheet `varlist' `covariables' `covariablemean' `freq' using "`dir'irtpoly_data.txt",replace
+
+drop _all
+if "`fixed'"!="" {
+ capture confirm matrix `fixed'
+ if _rc {
+ di as error "The {hi:`fixed'} matrix does not exist"
+ error 198
+ }
+ tempname matfix
+ matrix `matfix'=`fixed''
+ qui svmat `matfix'
+ qui rename `matfix'1 estimate
+ qui gen parameter=""
+ order parameter estimate
+ local l=1
+ forvalues j=1/`nbitems' {
+ forvalues m=1/`max`j'' {
+ if "`rasch'"=="" {
+ qui replace parameter="beta``j''_`m'" in `l'
+ }
+ else {
+ qui replace parameter="beta``j''" in `l'
+ }
+ local ++l
+ }
+ }
+ qui outsheet using "`dir'/irtpoly_fixedparameters.txt",replace
+
+}
+drop _all
+qui set obs 1000
+qui generate str txt="%include 'C:\ado\macros SAS\anaqolv48.sas';" in 1
+qui replace txt="%include 'C:\Documents and Settings\Jean-Benoit Hardouin\Mes documents\Boulot JB\Enseignement\ENSAI\2009-2010\macros\gammasymv1.sas';" in 2
+qui replace txt="PROC IMPORT OUT=WORK.data DATAFILE='`dir'irtpoly_data.txt' DBMS=TAB REPLACE;GETNAMES=YES;DATAROW=2; RUN;" in 3
+if "`fixed'"!="" {
+ qui replace txt="PROC IMPORT OUT=WORK.fixed DATAFILE='`dir'irtpoly_fixedparameters.txt' DBMS=TAB REPLACE;GETNAMES=YES;DATAROW=2; RUN;" in 4
+}
+local txt="%anaqol(DATASET=data,ITEMS=`varlist',DETAILS=yes,WEIGHT=`freq',MODEL="
+if "`rsm'"==""&"`rasch'"=="" {
+ local txt `txt'pcm
+}
+else if "`rasch'"!="" {
+ local txt `txt'rasch, TEST=no
+}
+else {
+ local txt `txt'rsm
+}
+if "`fixed'"!="" {
+ local txt `txt',FIXED=fixed
+}
+if `fixedvar'>0 {
+ local txt `txt',FIXEDVAR=`fixedvar'
+}
+if "`fixed'"!=""&"`fixedvar'"!="" {
+ local centered nocentered
+}
+if "`centered'"!="" {
+ local txt `txt',CENTERED=yes
+}
+if "`covariables'"!="" {
+ local txt `txt',COVARIABLES=`covariables'
+}
+if "`covariablemean'"!="" {
+ local txt `txt',COVARIABLEMEAN=`covariablemean'
+}
+local txt `txt');
+qui replace txt="`txt'" in 10
+qui replace txt="PROC EXPORT DATA= WORK.Out_parameters OUTFILE='`dir'irtpoly_parameters.txt' DBMS=TAB REPLACE;RUN;" in 11
+qui replace txt="PROC EXPORT DATA= WORK.Out_latent OUTFILE='`dir'irtpoly_latent.txt' DBMS=TAB REPLACE;RUN;" in 12
+qui replace txt="PROC EXPORT DATA= WORK.Out_rep OUTFILE='`dir'irtpoly_rep.txt' DBMS=TAB REPLACE;RUN;" in 13
+qui replace txt="PROC EXPORT DATA= WORK.Out_fit OUTFILE='`dir'irtpoly_fit.txt' DBMS=TAB REPLACE;RUN;" in 14
+
+qui outsheet txt using "`dir'irtpoly_pgmsas.txt", replace nonames noquote
+
+if "`last'"=="" {
+ /*local date=c(current_date)
+ local jour=substr("`date'",1,2)
+ local mois=substr("`date'",4,3)
+ local an=substr("`date'",8,4)
+ if "`mois'"=="Jan" {local moisd 01}
+ if "`mois'"=="Feb" {local moisd 02}
+ if "`mois'"=="Mar" {local moisd 03}
+ if "`mois'"=="Apr" {local moisd 04}
+ if "`mois'"=="May" {local moisd 05}
+ if "`mois'"=="Jun" {local moisd 06}
+ if "`mois'"=="Jul" {local moisd 07}
+ if "`mois'"=="Aug" {local moisd 08}
+ if "`mois'"=="Sep" {local moisd 09}
+ if "`mois'"=="Oct" {local moisd 10}
+ if "`mois'"=="Nov" {local moisd 11}
+ if "`mois'"=="Dec" {local moisd 12}
+ di "`jour' `mois' `an' `moisd'"
+ shell "date" "01/01/2009"
+ */
+ if "`long'"!=""{
+ local cmd winexec
+ }
+ else {
+ local cmd shell
+ }
+ `cmd' "C:\Program Files\SAS\SAS 9.2\SASFoundation\9.2\sas.exe" "`dir'irtpoly_pgmsas.txt" -print "`dir'irtpoly_pgmsas.lst" -nolog
+ *shell "cmd.exe" "date `jour'/`moid'/`an'"
+ if "`long'"!="" {
+ exit
+ }
+
+}
+if "`sasoutput'"!="" {
+ view "`dir'irtpoly_pgmsas.lst"
+}
+*set trace on
+
+*set trace on
+drop _all
+qui insheet using "`dir'irtpoly_fit.txt"
+qui su value if descr=="-2 Log Likelihood"
+local m2ll=r(mean)
+local ll=-`m2ll'/2
+qui su value if descr=="AIC (smaller is better)"
+local aic=r(mean)
+qui su value if descr=="BIC (smaller is better)"
+local bic=r(mean)
+
+drop _all
+qui insheet using "`dir'irtpoly_parameters.txt"
+tempname parameters separameters
+qui su estimate if parameter=="var"
+local variance=r(mean)
+qui su standarderror if parameter=="var"
+local sevariance=r(mean)
+*set trace on
+local nbcov:word count `covariables'
+forvalues i=1/`nbcov' {
+ local cov`i':word `i' of `covariables'
+ qui su estimate if parameter=="beta`cov`i''"
+ local betacov`i'=r(mean)
+ qui su standarderror if parameter=="beta`cov`i''"
+ local secov`i'=r(mean)
+}
+*set trace off
+*su
+di in gr "Number of individuals: " in ye `nbind'
+di in gr "Number of items: " in ye `nbitems'
+di in gr "log-likelihood: " in ye %10.4f `ll'
+di in gr "AIC: " in ye %10.4f `aic'
+di in gr "BIC: " in ye %10.4f `bic'
+di
+di
+if "`rsm'"=="" {
+ matrix `parameters'=J(`nbitems',`max',0)
+ matrix `separameters'=J(`nbitems',`max',0)
+ local l=1
+
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`max`i'' {
+ if "`fixed'"=="" {
+ qui su estimate if parameter=="beta``i''_`j'"
+ matrix `parameters'[`i',`j']=r(mean)
+ qui su standarderror if parameter=="beta``i''_`j'"
+ matrix `separameters'[`i',`j']=r(mean)
+ }
+ else {
+ matrix `parameters'[`i',`j']=`fixed'[1,`l']
+ }
+ local ++l
+ }
+ }
+ di in gr "{hline 52}"
+ di in gr "Items" _col(18) "Modality" _col(30) "Estimate" _col(39) "Standard error"
+ di in gr "{hline 52}"
+ forvalues j=1/`nbitems' {
+ di in gr "``j''" _c
+ forvalues m=1/`max`i'' {
+ di _col(25) in gr `m' _col(30) %8.4f in ye `parameters'[`j',`m'] _col(45) %8.4f in ye `separameters'[`j',`m']
+ }
+ }
+}
+else {
+ matrix `parameters'=J(`=`nbitems'+`max'-1',1,0)
+ matrix `separameters'=J(`=`nbitems'+`max'-1',1,0)
+ local l=1
+ if "`fixed'"=="" {
+ forvalues i=1/`nbitems' {
+ qui su estimate if parameter=="beta``i''"
+ matrix `parameters'[`i',1]=r(mean)
+ qui su standarderror if parameter=="beta``i''"
+ matrix `separameters'[`i',1]=r(mean)
+ local ++l
+ }
+ forvalues l=`=`nbitems'+1'/`=`nbitems'+`max'-1' {
+ local m=`l'-`nbitems'+1
+ qui su estimate if parameter=="t`m'"
+ matrix `parameters'[`l',1]=r(mean)
+ local tau`m'=r(mean)
+ qui su standarderror if parameter=="t`m'"
+ matrix `separameters'[`l',1]=r(mean)
+ }
+ }
+ else {
+ matrix `parameters'=`fixed'
+ }
+ di in gr "{hline 52}"
+ di in gr "Items" _col(30) "Estimate" _col(39) "Standard error"
+ di in gr "{hline 52}"
+ forvalues j=1/`nbitems' {
+ di in gr "``j''" _col(30) %8.4f in ye `parameters'[`j',1] _col(45) %8.4f in ye `separameters'[`j',1]
+ }
+ forvalues l=`=`nbitems'+1'/`=`nbitems'+`max'-1' {
+ di in gr "tau`=`l'-`nbitems''" _col(30) %8.4f in ye `parameters'[`l',1] _col(45) %8.4f in ye `separameters'[`l',1]
+ }
+}
+di in gr "{hline 52}"
+di in gr "Variance" _col(30) %8.4f in ye `variance' _col(45) %8.4f in ye `sevariance'
+di in gr "{hline 52}"
+forvalues i=1/`nbcov' {
+ di in gr "`cov`i''" _col(30) %8.4f in ye `betacov`i'' _col(45) %8.4f in ye `secov`i''
+}
+if "`covariables'"!="" {
+ di in gr "{hline 52}"
+}
+*matrix list `parameters'
+*fdsjklgvsjf
+
+*set trace on
+
+drop _all
+qui insheet using "`dir'irtpoly_rep.txt"
+qui sort anaqol_id
+qui sort `varlist' `covariables' `covariablemean'
+qui tempfile pcmsas
+qui rename theta `latent'
+qui rename stderrpred se`latent'
+qui save `pcmsas',replace
+qui use `pcmsasfile', clear
+qui sort `varlist'
+qui gen anaqol_id=_n
+qui sort anaqol_id
+qui sort `varlist' `covariables' `covariablemean'
+
+/***********************************************
+qui merge 1:1 anaqol_id using "`pcmsas'",nogen
+***********************************************/
+qui merge m:1 `varlist' `covariables' `covariablemean' using "`pcmsas'",nogen
+
+*tempvar group
+*set trace on
+forvalues i=1/`nbcov' {
+ qui replace `latent'=`latent'+`betacov`i''*`cov`i''
+}
+*qui save `latent' using c:\latent.dta
+qui gengroup `latent', det replace continuous newvariable(`group')
+qui su `group'
+local nbgroup=r(max)
+forvalues g=1/`nbgroup' {
+ qui count if `group'==`g'
+ local group`g'=r(N)
+}
+forvalues i=1/`nbitems' {
+ *set trace on
+ tempname freq`i'
+ qui tab `group' ``i'',matcell(`freq`i'') row nofreq m
+ *matrix list `freq`i''
+ forvalues g=1/`nbgroup' {
+ qui count if `group'==`g'&``i''!=.
+ local freq`g'_`i'=r(N)
+ forvalues j=0/`max`i'' {
+ matrix `freq`i''[`g',`=`j'+1']=`freq`i''[`g',`=`j'+1']/`freq`g'_`i''
+ }
+ }
+ local D`i'=0
+ forvalues j=0/`max`i'' {
+ local D`i'_`j' exp(`j'*`latent'
+ forvalues l=1/`j' {
+ if "`rsm'"=="" {
+ local D`i'_`j' `D`i'_`j''-`parameters'[`i',`l']
+ }
+ else {
+ local D`i'_`j' `D`i'_`j''-`parameters'[`i',1]
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues m=2/`j' {
+ local D`i'_`j' `D`i'_`j''-`tau`m''
+ }
+ }
+ local D`i'_`j' `D`i'_`j'')
+ local D`i' `D`i''+`D`i'_`j''
+ }
+ }
+ tempvar theta2
+ qui gen `theta2'=0
+ forvalues g=1/`nbgroup' {
+ qui su `latent' if `group'==`g'
+ local thetag`g'=r(mean)
+ qui replace `theta2'=`thetag`g'' if `group'==`g'
+}
+local colors="blue red green gray pink purple"
+
+*local chi2=0
+forvalues i=1/`nbitems' {
+ local line`i'
+ local scatter`i'
+ tempvar propE``i'' propO``i''
+ qui gen `propE``i'''=0
+ qui gen `propO``i'''=0
+ forvalues j=0/`max`i'' {
+ local color:word `=`j'+1' of `colors'
+ tempvar propE``i''_`j' propO``i''_`j'
+ *matrix list `parameters'
+ *di "qui gen `propE``i''_`j''=`D`i'_`j''/(`D`i'')"
+ qui gen `propE``i''_`j''=`D`i'_`j''/(`D`i'')
+ *su `propE``i''_`j''
+ label variable `propE``i''_`j'' "Expected values / modality `j'"
+ local line`i' `line`i'' (line `propE``i''_`j'' `latent', lcolor(`color') lwidth(thick))
+ qui gen `propO``i''_`j''=0
+ forvalues g=1/`nbgroup' {
+ local tmp=`freq`i''[`g',`=`j'+1']
+ qui replace `propO``i''_`j''=`tmp' if `group'==`g'
+ }
+ label variable `propO``i''_`j'' "Observed values / modality `j'"
+ qui replace `propO``i'''=`propO``i'''+`j'*`propO``i''_`j''
+ qui replace `propE``i'''=`propE``i'''+`j'*`propE``i''_`j''
+ local scatter`i' `scatter`i'' (scatter `propO``i''_`j'' `theta2', mcolor(`color'))
+ }
+ qui sort `latent'
+ if "`graph'"!="" {
+ twoway `line`i'' `scatter`i'',name(``i'', replace)
+ }
+ label variable `propE``i''' "Expected values"
+ label variable `propO``i''' "Observed values"
+ if "`graph'"!="" {
+ twoway (line `propE``i''' `latent', lcolor(green) lwidth(thick)) (scatter `propO``i''' `theta2',mcolor(green)),name(``i''2, replace)
+ }
+*set trace on
+if "`test'"!="" {
+local chi2=0
+forvalues g=1/`nbgroup' {
+ qui ttest `propE``i'''=`propO``i''' if `group'==`g'
+ local t`g'=r(t)
+ qui count if `group'==`g'
+ local nb`g'=r(N)
+ di "local chi2=`chi2'+/*`nb`g''**/(`t`g'')^2"
+ local chi2=`chi2'+/*`nb`g''**/(`t`g'')^2
+}
+di "Chi-square statistics: " %8.4f `chi2'
+local pchi2=chi2(`=`nbgroup'-1',`chi2')
+di "p-values: " %8.4f `pchi2'
+}
+}
+*set trace on
+tempfile saveu
+qui keep `order' `latent' se`latent' `group'
+if `savegroup'==0 {
+ drop `group'
+}
+if `savelatent'==0 {
+ drop `latent'
+ drop se`latent'
+}
+sort `order'
+qui save `saveu' ,replace
+
+restore
+qui gen `order'=_n
+qui sort `order'
+if "`replace'"!="" {
+ capture drop `group'
+ capture drop `latent'
+ capture drop se`latent'
+}
+qui merge 1:1 `order' using `saveu',nogen
+end
diff --git a/Modules/ado/personal/i/isvar.ado b/Modules/ado/personal/i/isvar.ado
new file mode 100644
index 0000000..bf43346
--- /dev/null
+++ b/Modules/ado/personal/i/isvar.ado
@@ -0,0 +1,27 @@
+*! NJC 1.0.0 19 Sept 2005
+program isvar, rclass
+ version 8
+ syntax anything
+
+ foreach v of local anything {
+ capture unab V : `v'
+ if _rc == 0 local varlist `varlist' `V'
+ else local badlist `badlist' `v'
+ }
+
+ di
+
+ if "`varlist'" != "" {
+ local n : word count `varlist'
+ local what = plural(`n', "variable")
+ di as txt "{p}`what': `varlist'{p_end}"
+ return local varlist "`varlist'"
+ }
+
+ if "`badlist'" != "" {
+ local n : word count `badlist'
+ local what = plural(`n', "not variable")
+ di as txt "{p}`what': `badlist'{p_end}"
+ return local badlist "`badlist'"
+ }
+end
diff --git a/Modules/ado/personal/k/kapci.ado b/Modules/ado/personal/k/kapci.ado
new file mode 100644
index 0000000..baf1a18
--- /dev/null
+++ b/Modules/ado/personal/k/kapci.ado
@@ -0,0 +1,495 @@
+* version 1.0.5 23set2004 MER version 8.0
+capture program drop kapci
+program define kapci, rclass byable(recall)
+ version 8.0
+
+
+ if "`1'" == "" {
+ di _n in gr " Syntax is:" _n
+ di in wh " kapci " in gr "[varlist] [if] [in] , [ " _c
+ di in wh "est" in gr "im(" in wh "an bc p n bsall" in gr ") "
+ di in wh _col(22) "w" in gr "gt" _c
+ di in gr "(" in wh "w w2 any_wgt" in gr ") " _c
+ di in wh "r" in gr "eps(" in wh "#" in gr ") " _c
+ di in wh "si" in gr "ze(" in wh "#" in gr ") "
+ di in wh _col(22) "se" in gr "ed(" in wh "#" in gr ") " _c
+ di in wh "ev" in gr "ery(" in wh "#" in gr ") " _c
+ di in wh "le" in gr "vel(" in wh "#" in gr ") " _c
+ di in wh "t" in gr "ab " in wh "w" in gr "ide"
+ di in wh _col(22) "sa" in gr "ving(" in wh "filename" in gr ") " _c
+ di in wh "replace nom" in gr "sg ]"
+ exit
+ }
+
+
+* Setup
+
+ version 8
+ syntax varlist [if] [in] [ , Reps(numlist) SIze(numlist) SEed(numlist) ///
+ EVery(numlist) Wgt(str) ESTim(str) Level(integer $S_level) ///
+ SAving(str) REPLACE Tab WIDE NOMsg ]
+
+
+ if "`options'" ~= "" {
+ local options = ", `options'"
+ }
+ tokenize "`varlist'"
+ marksample touse
+
+ preserve
+
+ if "`if'"!="" {
+ keep `if'
+ }
+ if ("`in'"!="") {
+ keep `in'
+ }
+
+
+* Level value, etc.
+
+ global zsc = invnorm(1-(1-`level'/100)/2)
+ global N = _N
+
+
+* Checking if estim=an is compatible with data
+
+ qui inspect `1'
+ local numlev `r(N_unique)'
+ local nummeas : word count `varlist'
+ if `numlev' < 3 & `nummeas' < 3 {
+ local bs 0
+ }
+ else local bs 1
+
+ if "`estim'" == "an" & `bs' == 1 {
+ di in gr " "
+ di in gr "Note: Option " in wh "estim(an) " in gr "is only suitable for 2x2 data."
+ di in wh " bs " in gr " will be used."
+ }
+
+* Defaults
+
+ if ("`estim'" == "") & (`bs' == 0) {
+ local estim "an"
+ }
+ if ("`estim'" == "") & (`bs' == 1) {
+ local estim "bc"
+ }
+
+
+*************************************
+* Displaying table if it is requested
+*************************************
+
+ if "`wide'" ~= "" {
+ local wide_str ", wrap"
+ }
+ if "`wide'" == "" {
+ local wide_str ""
+ }
+
+ if ("`tab'" ~= "") & (`nummeas' < 3) {
+ tab `varlist' if `touse' `wide_str'
+ }
+ if ("`tab'" ~= "") & (`nummeas' >= 3) {
+ tab2 `varlist'if `touse' `wide_str'
+ }
+
+
+****************************************************
+* Calculating analytical CI for kappa when estim=an
+****************************************************
+
+if (`bs' == 0) & ("`estim'" == "an") { /* Start of no bs situation */
+
+
+* First ... extracting effective sample size used (noting byable!)
+
+ qui summ `varlist' if `touse'
+ local N = `r(N)'
+
+
+* Call kappa and get midpoints
+
+ qui kap `varlist' if `touse' `options'
+
+
+* Saving scalars from kap as locals for return list
+
+ local prop_e = r(prop_e)
+ local prop_o = r(prop_o)
+
+
+* Working macro ...
+
+ local k = r(kappa)
+
+
+* Extract table data
+
+ tempname tab2x2 a b c d agrN
+ qui tab2 `varlist' , matcell(`tab2x2')
+
+ scalar `a'=`tab2x2'[1,1]
+ scalar `b'=`tab2x2'[1,2]
+ scalar `c'=`tab2x2'[2,1]
+ scalar `d'=`tab2x2'[2,2]
+ scalar `agrN'=`a'+`b'+`c'+`d'
+
+
+* Locals - marginals
+
+ local p1 = (`a'+`b')/`agrN'
+ local p2 = (`a'+`c')/`agrN'
+
+
+* Quantity Q based on Fleiss, (1981), equations 13.15 - 13.18
+
+
+ local Q = ( ( ( (-1 + `k' ) * ( (-2*`k' *`p1' ) + /*
+*/ ((`k' ^2)*`p1' ) + (4*`k' *(`p1'^2)) - /*
+*/ (2*(`k'^2)*(`p1'^2)) - (2*`k' *`p2' ) + /*
+*/ ((`k'^2)*`p2' ) - (4*`p1' *`p2' ) + /*
+*/ (8*`k' *`p1' *`p2' ) - (6*(`k'^2)*`p1' *`p2' ) + /*
+*/ (4*(`p1'^2)*`p2' ) - (12*`k' *(`p1'^2)*`p2' ) + /*
+*/ (8*(`k'^2)*(`p1'^2)*`p2' ) + (4*`k' *(`p2'^2)) - /*
+*/ (2*(`k'^2)*(`p2'^2)) + (4*`p1' *(`p2'^2)) - /*
+*/ (12*`k' *`p1' *(`p2'^2)) + /*
+*/ (8*(`k'^2)*`p1' *(`p2'^2)) - /*
+*/ (4*(`p1'^2)*(`p2'^2)) + /*
+*/ (12*`k' *(`p1'^2)*(`p2'^2)) - /*
+*/ (8*(`k'^2)*(`p1'^2)*(`p2'^2))) /*
+*/ ) / ( (`p1' + `p2' - (2*`p1' *`p2' ) )^2 ) ) )
+
+
+* Standard error, given kappa estimate k_hat=`k'
+
+ local sek = (sqrt(`Q')) / (sqrt(`agrN') )
+
+
+* CI
+
+ local klow = `k'-($zsc*`sek')
+ local kup = `k'+($zsc*`sek')
+
+ if `kup' >= 1 {
+ local kup = 1
+ }
+ if `klow' < -1 {
+ local klow = -1
+ }
+
+
+* Display
+
+ local type "analytical "
+ local typeab "A"
+
+ di _n in gr _col(42) "N=" `N'
+ di in gr "{hline 48}"
+ di in gr " Kappa (" %2.0f `level' "% CI) = " in ye %5.3f `k' _c
+ di in gr _col(24) " (" in ye %5.3f `klow' in gr " - " in ye %5.3f `kup' in gr ")" _c
+ di in gr _col(44) "(" "`typeab'" ")"
+ di in gr "{hline 48}"
+ di in gr _col(2) "`typeab'" " = " "`type'"
+
+
+* Return list
+
+ return scalar N = `agrN'
+ return scalar z = $zsc
+ return scalar se = `sek'
+ return scalar prop_o = `prop_o'
+ return scalar prop_e = `prop_e'
+ return scalar ub_an = `kup'
+ return scalar lb_an = `klow'
+ return scalar kappa = `k'
+
+
+} /* End of no bs situation */
+
+
+
+*****************************************************
+* Calculating analytical CI for kappa when estim!=an
+*****************************************************
+
+if (`bs' == 1) | ((`bs' == 0) & ("`estim'" ~= "an")) { /* Start of bs situation */
+
+ if "`estim'" ~= "an" {
+ if "`estim'" ~= "" {
+ if "`estim'" ~= "bc" {
+ if "`estim'" ~= "n" {
+ if "`estim'" ~= "p" {
+ if "`estim'" ~= "bsall" {
+ local estim "bc"
+ di in bl " "
+ di in bl "Note: Unknown bs CI type specified."
+ di in wh " bc " in gr "will be used."
+ }
+ }
+ }
+ }
+ }
+ }
+ if "`estim'" == "an" {
+ local estim "bc"
+ }
+
+
+* Preparing ...
+
+ tempfile mainfile
+ qui save `mainfile', replace
+ qui use `mainfile', clear
+
+ tempfile tmpsave0 tmpsave1
+ local byindex = _byindex()
+
+ *----------------------------------------------------------------------------
+ if ("`saving'" ~= "") & (_by()==1) {
+ local sa_str "saving(`tmpsave1')"
+ }
+ if ("`saving'" ~= "") & (_by()==0) {
+ local sa_str "saving(`tmpsave0')"
+ }
+ if "`saving'" == "" & (_by()==0) {
+ local sa_str ""
+ }
+ *----------------------------------------------------------------------------
+ if "`wgt'" ~= "" {
+ local wgt_str "wgt(`wgt')"
+ }
+ local n : word count `varlist'
+ if `n' > 2 & "`wgt'" ~= "" {
+ di _n in gr "Note: wgt() not allowed if varlist > 2. Option ignored."
+ local wgt_str ""
+ }
+ if "`wgt'" == "" {
+ local wgt_str ""
+ }
+ *----------------------------------------------------------------------------
+ if "`reps'" ~= "" {
+ local reps_str "reps(`reps')"
+ }
+ if "`reps'" == "" {
+ local reps_str "reps(5)"
+ local reps 5
+ di _n in gr "Note: default number of bootstrap replications " _c
+ di in gr "has been
+ di in gr " set to " in wh "5 " in gr "for syntax testing only." _c
+ di in wh "reps() " in gr "needs to "
+ di in gr " be increased when analysing real data." _n
+ }
+ *----------------------------------------------------------------------------
+ if "`seed'" ~= "" {
+ set seed `seed'
+ local seed_str "seed(`seed')"
+ }
+ *----------------------------------------------------------------------------
+ if "`size'" ~= "" {
+ if `size' < 5 {
+ di in gr "Note: size() set to N"
+ local size $N
+ }
+ local size_str "size(`size')"
+ }
+ if "`size'" == "" {
+ local size_str ""
+ local size $N
+ }
+ *----------------------------------------------------------------------------
+ if "`every'" ~= "" {
+ local every_str "every(`every')"
+ }
+ if "`every'" == "" {
+ local every_str ""
+ }
+ *----------------------------------------------------------------------------
+ if _by()==0 {
+ local first "kap `varlist' , `wgt_str'"
+ }
+ if _by()==1 {
+ local first "kap `varlist' if `touse' , `wgt_str'"
+ }
+
+
+* Calling bs
+
+ if `reps' > 100 & "`nomsg'" == "" {
+ di _n in gr "This may take quite a long time. Please wait ..."
+ }
+
+ qui bs " `first' " r(kappa), `reps_str' `sa_str' level(`level') `size_str' `every_str' nowarn
+
+ if ("`saving'" ~= "") & (_by()==0) {
+ qui use `tmpsave0'
+ qui label data "kapci: varlist is `varlist'"
+ qui rename _bs_1 _kapci_bs
+ label var _kapci_bs "Options: `wgt_str' `reps_str' `seed_str' `size_str' `every_str'"
+ qui save `saving', `replace'
+ restore
+ }
+
+ if ("`saving'" ~= "") & (_by()==1) {
+ qui use `tmpsave1'
+ qui label data "kapci: varlist is `varlist'; byvars is `_byvars'; by-group is (`byindex')"
+ qui rename _bs_1 _kapci_bs__`byindex'
+ label var _kapci_bs__`byindex' "Options: `wgt_str' `reps_str' `seed_str' `size_str' `every_str'"
+ qui save `saving'`byindex', `replace'
+ restore
+ }
+
+
+* Extracting sample size used (noting byable !)
+
+ qui summ `varlist' if `touse'
+ local N = `r(N)'
+
+
+* Matrix extraction
+
+ matrix tmp_mtx = e(b)
+ local k = tmp_mtx[1,1]
+
+ matrix tmp_mtx = e(ci_bc)
+ local klow_bc = tmp_mtx[1,1]
+ local kup_bc = tmp_mtx[2,1]
+
+ matrix tmp_mtx = e(ci_percentile)
+ local klow_p = tmp_mtx[1,1]
+ local kup_p = tmp_mtx[2,1]
+
+ matrix tmp_mtx = e(ci_normal)
+ local klow_n = tmp_mtx[1,1]
+ local kup_n = tmp_mtx[2,1]
+
+ matrix tmp_mtx = e(reps)
+ local numreps = tmp_mtx[1,1]
+
+ matrix tmp_mtx = e(bias)
+ local bias = tmp_mtx[1,1]
+
+ matrix tmp_mtx = e(se)
+ local se = tmp_mtx[1,1]
+ matrix drop tmp_mtx
+
+
+* Display
+
+ local dotdot "{hline 48}"
+ local col1 "_col(34)"
+ local col2 "_col(43)"
+
+ if "`estim'" ~= "bsall" {
+
+ if "`estim'" == "bc" {
+ local klow = `klow_bc'
+ local kup = `kup_bc'
+ }
+
+ if "`estim'" == "n" {
+ local klow = `klow_n'
+ local kup = `kup_n'
+ }
+
+ if "`estim'" == "p" {
+ local klow = `klow_p'
+ local kup = `kup_p'
+ }
+
+ if (`kup' >= 1) & (`kup' ~= .) {
+ local kup = 1
+ }
+ if (`klow' < -1) & (`klow' ~= .) {
+ local klow = -1
+ }
+
+ if "`estim'" == "bc" {
+ local type "bias corrected "
+ local typeab "BC"
+ }
+
+ if "`estim'" == "n" {
+ local type "normal "
+ local typeab "N"
+ }
+
+ if "`estim'" == "p" {
+ local type "percentile "
+ local typeab "P"
+ }
+
+
+ di _n in gr _col(34) "B=" `numreps' _col(42) "N=" `N'
+ di in gr "{hline 48}"
+ di in gr " Kappa (" %2.0f `level' "% CI) = " in ye %5.3f `k' _c
+ di in gr _col(24) " (" in ye %5.3f `klow' in gr " - " in ye %5.3f `kup' in gr ")" _c
+ di in gr _col(44) "(" "`typeab'" ")"
+ di in gr "{hline 48}"
+ di in gr _col(2) "`typeab'" " = " "`type'"
+
+ }
+
+
+
+ if "`estim'" == "bsall" {
+
+ if `kup_n' >= 1 {
+ local kup_n = 1
+ }
+ if `klow_n' < -1 {
+ local klow_n = -1
+ }
+
+ local type1 "bias corrected"
+ local typeab1 "BC"
+ local type2 "percentile"
+ local typeab2 "P"
+ local type3 "normal"
+ local typeab3 "N"
+
+
+ di _n in gr _col(34) "B=" `numreps' _col(42) "N=" `N'
+ di in gr "{hline 48}"
+ di in gr " Kappa (" %2.0f `level' "% CI) = " in ye %5.3f `k' _c
+ di in gr _col(24) " (" in ye %5.3f `klow_bc' in gr " - " in ye %5.3f `kup_bc' in gr ")" _c
+ di in gr _col(44) "(" "`typeab1'" ")"
+ di in gr _col(24) " (" in ye %5.3f `klow_p' in gr " - " in ye %5.3f `kup_p' in gr ")" _c
+ di in gr _col(44) "(" "`typeab2'" ")"
+ di in gr _col(24) " (" in ye %5.3f `klow_n' in gr " - " in ye %5.3f `kup_n' in gr ")" _c
+ di in gr _col(44) "(" "`typeab3'" ")"
+ di in gr "{hline 48}"
+ di in gr _col(2) "`typeab1'" " = " "`type1'" ", " _c
+ di in gr "`typeab2'" " = " "`type2'" ", " _c
+ di in gr "`typeab3'" " = " "`type3'"
+
+ }
+
+* Return list
+
+ return scalar N_bs = `size'
+ return scalar N = $N
+ return scalar z = $zsc
+ return scalar reps = `numreps'
+ return scalar bias = `bias'
+ return scalar se = `se'
+ return scalar lb_n = `klow_n'
+ return scalar ub_n = `kup_n'
+ return scalar lb_p = `klow_p'
+ return scalar ub_p = `kup_p'
+ return scalar lb_bc = `klow_bc'
+ return scalar ub_bc = `kup_bc'
+ return scalar kappa = `k'
+
+} /* End of no bs situation */
+
+
+* Cleaning up
+
+ macro drop zsc
+ macro drop N
+
+end
+
diff --git a/Modules/ado/personal/k/kgv.ado b/Modules/ado/personal/k/kgv.ado
new file mode 100644
index 0000000..e46be43
--- /dev/null
+++ b/Modules/ado/personal/k/kgv.ado
@@ -0,0 +1,212 @@
+capture program drop kgv
+program kgv,rclass
+syntax varlist, categ(varlist) [KGVBoxplots KGVGroupboxplots]
+
+local i = 1
+local j = 1
+local k = 0
+local max = 0
+local a : word count `categ'
+local nb:word count `varlist'
+
+di as result "{hline}"
+di "{bf:Known-groups validity}"
+di as result "{hline}"
+di
+
+foreach sco in `varlist' {
+ foreach cat in `categ' {
+ local nblev = 0
+ local maxlen`j' = 0
+ qui anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ qui levelsof `cat', local(levels)
+ local lbe : value label `cat'
+
+ foreach l of local levels {
+ qui count if `sco' !=. & `cat' == `l'
+ local `++k'
+ local eff`i'_`j'_`k' = r(N)
+
+ if "`lbe'" != "" {
+ local ll`j'_`k' : label `lbe' `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ else {
+ local ll`j'_`k' = `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ qui su `sco' if `cat' == `l'
+ local m`i'_`j'_`k' = r(mean)
+ local s`i'_`j'_`k' = r(sd)
+ local nblev = `nblev' + 1
+ }
+ if `nblev' > `max' local max = `nblev'
+ local `++j'
+ local k = 0
+ }
+ local `++i'
+ local j = 1
+}
+
+
+/* coupure noms des scores */
+/*
+local i = 1
+foreach s in `varlist' {
+ local len = length("`s'")
+ if `len' > 10 {
+ local c = substr("`s'",1,9)
+ local d = substr("`s'",-1,1)
+ local s`i' "`c'" "~" "`d'"
+ }
+ else local s`i' = "`s'"
+ local sc `sc' `s`i''
+ local `++i'
+}
+*/
+local i = 1
+foreach s in `varlist' {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+/*
+local max = 0
+foreach s in `scorename' {
+ local len = length("`s'")
+ if `len' > `max' local max = `len'
+}
+*/
+
+local maxs = 0
+forvalues j=1/`nb' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `maxs' local maxs = `len`j''
+}
+
+local i = 1
+local k = 0
+local j = 2
+
+foreach cat in `categ'{
+ local `++k'
+ tokenize `categ'
+ local c`k' = "``i'' ``j''"
+ local i = `i' + 2
+ local j = `j' + 2
+}
+
+
+local d = 1
+local f = 2
+forvalues h = 1/`a' {
+ if `f' > `a' local f = `f'-1
+ local j = 1
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`col') "{bf:`cat'}" _c
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+ di
+
+ local j = `d'
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`=`col'+`maxlen`j''+5') "{bf: mean }" _c
+ di "{bf:standard }" _c
+ di "{bf:p-value}" _c
+
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+ di
+
+ local j = `d'
+ local col = `maxs'+6
+
+ foreach cat in `c`h'' {
+ di _col(`=`col'+`maxlen`j''+6') "{bf: error}"_c
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+
+
+ di
+ di
+ local i = 1
+ local col = `maxs'+6
+
+ forvalues g = 1/`nb' {
+
+ di "{bf:`s`g''}" _c
+ forvalues k = 1/`max' {
+ forvalues j = `d'/`f' {
+
+ di _col(`col') "{bf:`ll`j'_`k''} " _c
+ if "`eff`i'_`j'_`k''" != "" di as text "(n=`eff`i'_`j'_`k'')" _c
+ local m : di %6.2f `m`i'_`j'_`k''
+ di _col(`=`col'+`maxlen`j''+10') "{text:`m'} " _c
+
+ local s : di %8.2f `s`i'_`j'_`k''
+ di "{text: `s'} " _c
+
+ if `k' == 1 {
+ local p : di %8.3f `p`i'_`j''
+ di _col(`=`col'+31') "{text:`p'} " _c
+ }
+ local col = `col' + `maxlen`j'' + 5 + 40
+ }
+ di
+ local col = `maxs'+6
+
+ }
+ di
+
+ local `++i'
+
+ }
+ local d = `d'+2
+ local f = `f'+2
+ if `d' > `a' continue, break
+ di
+}
+
+if "`kgvboxplots'" != "" {
+ *qui set autotabgraphs on
+ if "`kgvgroupboxplots'" != "" {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") nodraw
+ local g `g' `s'_`c'
+ }
+ }
+ gr combine `g', name(Known_groups_validity,replace)
+ }
+ else {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'")
+ local g `g' `s'_`c'
+ }
+ }
+ }
+}
+end
+*kgv HA-MOC, categ(radio chim) //kgvboxplots kgvgroupboxplots // radio_01 etud_01 actu_01)
diff --git a/Modules/ado/personal/l/loevH7.ado b/Modules/ado/personal/l/loevH7.ado
new file mode 100644
index 0000000..b8574d4
--- /dev/null
+++ b/Modules/ado/personal/l/loevH7.ado
@@ -0,0 +1,1168 @@
+*! Version 7 14 June 2007
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : LoevH
+* Loevinger H indexes, Mokken Analysis
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+*
+* dedication for Stefan Thau - Interuniversity Centre for Social Science Theory and Methodology - University of Groningen
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2007 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 loevH , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string)]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+preserve
+forvalues j=1/`nbitems' {
+ qui drop if ``j''==.
+ qui count
+ local nbtotindnm=r(N)
+}
+if "`pairwise'"!="" {
+ restore
+}
+
+qui count
+local nbobs=r(N)
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(`col') "`text'" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(24) "P(Xj=`value')" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `P`value''[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!="" {
+ local list
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+* di "`list'"
+* di "`li', `lj', `lk', `ii' `ij' `ik'"
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+*di " local z=abs(2*min(`a',`b')-(`a'+`b'))/sqrt(`a'+`b')"
+ local z=abs(2*min(`a',`b')-(`a'+`b'))/sqrt(`a'+`b')
+
+*di " if `z'>`=invnorm(1-`siglevel')'&`z'!=. {"
+
+ if `z'>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if `z'>`zmaxpp`tj'' {
+ local zmaxpp`tj'=`z'
+ }
+ local ++nbsigzpp`tk'
+ if `z'>`zmaxpp`tk'' {
+ local zmaxpp`tk'=`z'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+* di "`list'"
+* di "`li', `lj', `lk', `ii' `ij' `ik'"
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+*di " local z=abs(2*min(`a',`b')-(`a'+`b'))/sqrt(`a'+`b')"
+ local z=abs(2*min(`a',`b')-(`a'+`b'))/sqrt(`a'+`b')
+
+*di " if `z'>`=invnorm(1-`siglevel')'&`z'!=. {"
+
+ if `z'>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if `z'>`zmaxmm`tj'' {
+ local zmaxmm`tj'=`z'
+ }
+ local ++nbsigzmm`tk'
+ if `z'>`zmaxmm`tk'' {
+ local zmaxmm`tk'=`z'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`nipmatrix'"!="" {
+ *set trace on
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror' `generror'_0 `generror'_H
+ }
+ qui gen `generror'=0
+ qui gen `generror'_0=`eGutt0'/`nb'
+ forvalues i=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ forvalues j=1/`nbitems' {
+ qui replace `generror'=`generror'+1 if `P1'[1,`i']<`P1'[1,`j']&``i''==1&``j''==0
+ qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ di
+ di in green "Number of Guttman errors by individual"
+ qui su `generror'
+ di in green " Mean number: " in ye %7.2f r(mean)
+ di in green " Maximal number: " in ye %7.2f `=int(`nbitems'^2/4)'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of H<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
diff --git a/Modules/ado/personal/l/loevH72.ado b/Modules/ado/personal/l/loevH72.ado
new file mode 100644
index 0000000..8532dc1
--- /dev/null
+++ b/Modules/ado/personal/l/loevH72.ado
@@ -0,0 +1,1231 @@
+*! Version 7.2 19 November 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : LoevH
+* Loevinger H indexes, Mokken Analysis
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+*
+* dedication for Stefan Thau - Interuniversity Centre for Social Science Theory and Methodology - University of Groningen
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2008 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 loevH , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string)]
+preserve
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(`col') "`text'" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(24) "P(Xj=`value')" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `P`value''[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`nipmatrix'"!="" {
+ *set trace on
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
diff --git a/Modules/ado/personal/l/loevH73.ado b/Modules/ado/personal/l/loevH73.ado
new file mode 100644
index 0000000..4d3b65a
--- /dev/null
+++ b/Modules/ado/personal/l/loevH73.ado
@@ -0,0 +1,1234 @@
+*! Version 7.3 15 August 2009
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : LoevH
+* Loevinger H indexes, Mokken Analysis
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2008 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 loevH , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string)]
+preserve
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`nipmatrix'"!="" {
+ *set trace on
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
diff --git a/Modules/ado/personal/l/loevH73.hlp b/Modules/ado/personal/l/loevH73.hlp
new file mode 100644
index 0000000..988d156
--- /dev/null
+++ b/Modules/ado/personal/l/loevH73.hlp
@@ -0,0 +1,103 @@
+{smcl}
+{* 6november2004}{...}
+{hline}
+help for {hi:loevH}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Loevinger's H coefficients and non parametric Item Responses Models}
+
+{p 8 14 2}{cmd:loevH} {it:varlist} [{cmd:,} {cmdab:pairw:ise} {cmdab:pair} {cmdab:ppp} {cmdab:pmm} {cmdab:noadj:ust} {cmdab:gener:ror}({it:newvar}) {cmdab:rep:lace} {cmdab:gr:aph} {cmdab:mono:tonicity}({it:string}) {cmdab:nip:matrix}({it:string})]
+
+{p 8 14 2}{it:varlist} is a list of two or more existing dichotomous ou polytomous variables.
+
+{title:Description}
+
+{p 4 8 2}{cmd:loevH} allows verifying the fit of data to the Monotonely Homogeneous Mokken Model or to the Doubly Monotone Mokken Model.
+It computes the Loevinger H scalability coefficients, and several indexes in the field of the Non parametric Item Response Theory.
+
+{title:Options}
+
+{p 4 8 2}{cmd:pairwise}. By default, all the individuals with one or more missing values are omitted. {cmd:pairwise} allows to use the complete information by pair of items.
+
+{p 4 8 2}{cmd:pair} displays statistics and the value of the Loevinger H coefficient for each pair of items.
+
+{p 4 8 2}{cmd:ppp} displays the P++ matrix.
+
+{p 4 8 2}{cmd:pmm} displays the P-- matrix.
+
+{p 4 8 2}{cmd:noadjust} approximates the tests statistics like the MSP software (Molenaar et al. (2000)).
+
+{p 4 8 2}{cmd:generror} creates a new variable containing the number of Guttman errors produced by each individual.
+
+{p 4 8 2}{cmd:replace} allows replacing the variable defined by the {cmd:generror} option.
+
+{p 4 8 2}{cmd:graph} displays graphs (only with the {cmd:ppp}, {cmd:pmm} and {cmd:generror} options).
+
+{p 4 8 2}{cmd:monotonicity} displays indexes in order to check the monotonicity of the data (Monotone Homogeneity Mokken Model). This option produces outputs similar to the MSP software.
+The string contains several suboptions: {cmd:minvi}, {cmd:minsize}, {cmd:siglevel} and {cmd:details}. If you want use all the default values, type *.{p_end}
+{p 10 12 10}{cmd:minvi} defines the minimal size of a violation of monotonicity (0.03 by default){p_end}
+{p 10 12 10}{cmd:minsize} defines the minimum size of groups of patients to check the monotonicity (by default, the number of individuals divided by 10 with more than 500 individuals, the same number divided by 5 with more than 250 individuals, and the same number divided by 3 for a smaller number, with a minimum of 50){p_end}
+{p 10 12 10}{cmd:siglevel} defines the significance level for the tests (0.05 by default){p_end}
+{p 10 12 10}{cmd:details} displays more details with polytomous items
+
+{p 4 8 2}{cmd:nipmatrix} display indexes in order to check the non-intersection (Doubly Monotone Mokken Model). This option produces outputs similar to the MSP software.
+The string contains several suboptions: {cmd:minvi} and {cmd:siglevel}. If you want use all the default values, type *.{p_end}
+{p 10 12 10}{cmd:minvi} defines the minimal size of a violation of non-intersection (0.03 by default){p_end}
+{p 10 12 10}{cmd:siglevel} defines the significance level for the tests (0.05 by default){p_end}
+
+
+{title:Remarks}
+
+{p 4 8 2}For detailed informations on the Loevinger's H coefficients, see Loevinger (1948) or Hemker and al. (1995). For details about the analysis of non parametric Mokken models, see for example the MSP 5.0 manual.
+
+
+{title:Example}
+
+ {p 8 8}{inp:. loevH itemA1-itemA7}
+
+ {p 8 8}{inp:. loevH itemA*, pair monotonicity(*) ppp pmm nipmatrix(minvi(0.05) siglevel(0.01))}
+
+ {p 8 8}{inp:. loevH item*, pairwise generror(error) graph}
+
+{title:Results}
+
+{p 4 8 2}The Loevinger's H coefficients between all the pairs of items, for each item with respect of all the others items and for the set of items are respectively saved in the matrices {it:r(loevHjk)}, {it:r(loevHj)}
+and in the scalar {it:r(loevH)}.
+
+{p 4 8 2}The empirical Guttman errors between all the pairs of items, associated to each item and relied to the scale are respectively saved in the matrices {it:r(eGuttjk)}, {it:r(eGuttj)} and in the scalar {it:e(Gutt)}.
+
+{p 4 8 2}The theorical Guttman errors between all the pairs of items, associated to each item and relied to the scale are respectively saved in the matrices {it:r(eGuttjk0)}, {it:r(eGuttj0)} and in the scalar {it:e(Gutt0)}.
+
+{p 4 8 2}The values of the Z statistics and the corresponding p-values associated to the Loevinger H coefficients are respectively saved in the matrices {it:r(zHjk)}, {it:r(pvalHjk)}, {it:r(zHj)}, {it:r(pvalHj)}
+and in the scalars {it:e(zH)} and {it:r(pvalH)}.
+
+{p 4 8 2}The P++ and P-- matrices are saved in {it:r(ppp)} and {it:r(pmm)}.
+
+{p 4 8 2}The used number of individuals per items pair is saved in {it:r(Obs)}.
+
+
+{title:References}
+
+{p 4 8 2}Hemker B. T., Sijtsma K. and Molenaar I. W., Selection of unidimensional scales from a multidimensional item bank in the polytomous Mokken IRT
+model, {it: Applied Psychological Measurement}, vol.19(4), 1995, pp. 337-352.
+
+{p 4 8 2}Loevinger J., The technique of homogeneous tests compared with some aspects of "scale analysis" and factor analysis. {it:Psychological bulletin},
+vol. 45, 1948, pp. 507-530.
+
+{p 4 8 2}Molenaar I. W., Sijtsma K. and Boer P. {it:MSP5 for Windows - User's Manual}, 2000, 105 pages.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help traces}, {help msp}, {help gengroup}, {help mokken} if installed.{p_end}
diff --git a/Modules/ado/personal/l/loevHv1.hlp b/Modules/ado/personal/l/loevHv1.hlp
new file mode 100644
index 0000000..bab6a1a
--- /dev/null
+++ b/Modules/ado/personal/l/loevHv1.hlp
@@ -0,0 +1,71 @@
+{smcl}
+{* 31Aug2002}{...}
+{hline}
+help for {hi:loevH}
+{hline}
+
+{title:Loevinger's H coefficients}
+
+{p 8 14}{cmd:loevH} {it:varlist} [{cmd:,} {cmdab:h} {cmdab:hj} {cmdab:hjk}
+{cmdab:e} {cmdab:ej} {cmdab:ejk} {cmdab:e0} {cmdab:ej0} {cmdab:ejk0}]
+
+
+{p}{it:varlist} is a list of two existing dichotomous variables or more.
+
+{title:Options}
+
+{p 0 4}{cmd:h} display the Loevinger H coefficient for all the items of the scale.
+
+{p 0 4}{cmd:hj} display the Loevinger H coefficient for each item of the scale with respect of all the others items.
+
+{p 0 4}{cmd:hjk} display the Loevinger H coefficient for each pair of items of the scale.
+
+{p 0 4}{cmd:e} display the sum of the number of Guttman errors between all the pairs of items.
+
+{p 0 4}{cmd:ej} display the sum of the number of Guttman errors for each item of the scale.
+
+{p 0 4}{cmd:ejk} display the sum of the number of Guttman errors fror each pair of items of the scale.
+
+{p 0 4}{cmd:e0} display the sum of the number of expected Guttman errors between all the pairs of items.
+
+{p 0 4}{cmd:ej0} display the sum of the number of expected Guttman errors for each item of the scale.
+
+{p 0 4}{cmd:ejk0} display the sum of the number of expected Guttman errors fror each pair of items of the scale.
+
+
+{title:Description}
+
+{p}{cmd:loevH} calculate the Loevinger's H coefficient between all the pairs of items of {it:varlist}, and compute the Loevinger's Hj coefficient for each item of {it:varlist} with respect of all the others items and the Loevinger's H coefficient for the set of items of {it:varlist}.
+
+
+{title:Remarks}
+
+For detailed information on the Loevinger's H coefficients, see Loevinger (1948) or Hemker and al. (1995).
+
+{cmd:loevH} display none result by default. {cmd:loevH} don't permit the use of polytomous items.
+
+
+{title:Example}
+
+ {inp:. loevH item1 item2 item3 item4}
+
+{title:Results}
+
+The Loevinger's H coefficients between all the pais of items are saved in the matrix r(loevHjk).
+
+The Loevinger's H coefficients for each item with respect of all the others items are saved in the matrix r(loevHj).
+
+The Loevinger's H coefficient for the set of items is saved in the scalar r(loevH).
+
+{title:References}
+
+Hemker B. T., Sijtsma K. and Molenaar I. W., Selection of unidimensional scales from a multidimensional item bank in the polytomous Mokken IRT
+model, {it: Applied Psychological Measurement}, vol.19(4), 1995, pp. 337-352.
+
+Loevinger J., The technique of homogeneous tests compared with some aspects of "scale analysis" and factor analysis. {it:Psychological bulletin},
+vol. 45, 1948, pp. 507-530.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@neuf.fr":jean-benoit.hardouin@neuf.fr} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/l/loevh - Copie au 17 juin 2017.ado b/Modules/ado/personal/l/loevh - Copie au 17 juin 2017.ado
new file mode 100644
index 0000000..40e741d
--- /dev/null
+++ b/Modules/ado/personal/l/loevh - Copie au 17 juin 2017.ado
@@ -0,0 +1,1393 @@
+*! Version 8.1.5 23 March 2015
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8.1.3 : March 23, 2015 /*minor correction for displaying results*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 /*html option*/
+* Release 8.1.1 : November 20, 2012 /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2015 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]
+preserve
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di in gr ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+local loevH=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+if "`html'" == "" {
+ di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+ di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+ di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+ di in green "{hline 99}"
+ forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(36) %7.0f `eGuttj'[1,`j'] _col(45) %10.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+ }
+ di in green "{hline 99}"
+}
+else {
+ di in gr "
"
+ di in gr ""
+ di in gr "Item | Obs | Mean Score | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hj ≤ 0 p-value | "
+ di in gr "Number of NS Hjk |
"
+ forvalues j=1/`nbitems' {
+ di in green "``j'' | " `Obs'[`j',`j'] " | " %6.4f `diff'[1,`j'] " | " %5.0f `eGuttj'[1,`j'] " | " %8.2f `eGuttj0'[1,`j'] " | " %7.5f `loevHj'[1,`j'] " | " %8.4f `zHj'[1,`j'] " | " %7.5f `pvalHj'[1,`j'] " | " %2.0f `nbHjkNS`j'' " |
"
+ }
+}
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+if "`html'" == "" {
+ di in green "Scale" in yellow _col(15) `nb' _col(36) %7.0f `eGutt' _col(45) %10.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+}
+else {
+ di in green "Scale | " `nb' " | | " %5.0f `eGutt' " | " %8.2f `eGutt0' " | " %-8.5f `loevH' " | " %9.4f `zH' " | " %7.5f `pvalH' " | |
"
+ di in gr "
"
+}
+
+if "`pair'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary of results by items pairs"
+ di in green "Items | " "`text'" " Obs P(Xj=`value',Xk=`value') | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hjk ≤ 0 p-value |
"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "" "``j''" " | " "``k''" " | " `Obs'[`j',`k'] " | " %6.4f `P`value'`value''[`j',`k'] " | " %5.0f `eGuttjk'[`j',`k'] " | " %8.2f `eGuttjk0'[`j',`k'] " | " %8.5f `loevHjk'[`j',`k'] " | " %9.4f `zHjk'[`j',`k'] " | " %7.5f `pvalHjk'[`j',`k'] " |
"
+ }
+ }
+ di in green " |
---|
"
+ }
+}
+
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ if "`html'" == "" {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ }
+ else {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items
"
+ }
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of monotonicity"
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | zmax | #zsig | Crit |
"
+ }
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " | " %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `maxvi`i'_m`l'' " | " %6.4f `sumvi`i'_m`l'' " | " %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `zmaxvi`i'_m`l'' " | " %8.0f `nbzvi`i'_m`l'' " | |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " |
"
+ }
+ }
+ }
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | " %6.4f `=`vi`i''/`ac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`ac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzvi`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in gr "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ if "`html'" == "" {
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+ }
+ else {
+ di in green "Total | " `ac' " | " %8.0f `vi' " | " %6.4f `=`vi'/`ac'' " | " %6.4f `maxvi' " | " %6.4f `sumvi' " | " %6.4f `=`sumvi'/`ac'' " | " %6.4f `zmaxvi' " | " %8.0f `nbzvi' " | |
---|
"
+ }
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_ppp,replace) nodraw"
+ }
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving' xsize(2) ysize(2)
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_ppp.gph
+ qui graph export `c(tmpdir)'/`html'_ppp.eps, replace
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P++ values per items pair (The values should be increasing in each column) |
"
+ di ""
+ matrixlisthtml `matpp' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_pmm,replace) nodraw"
+ *qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *graph use `c(tmpdir)'/`html'_pmm.gph
+ *qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ *else {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *}
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_pmm.gph
+ qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P-- values per items pair (The values should be decreasing in each column) |
"
+ di ""
+ matrixlisthtml `matmm' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if "`nipmatrix'" !="" {
+ *set trace on
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of non-Intersection via Pmatrix
"
+ di in gr "Minvi=" in ye %5.3f `minvi' " Alpha=" in ye %5.3f `siglevel' ""
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | "
+ di in gr "zmax | #zsig | Crit |
"
+ }
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di in green " |
---|
"
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/loevh v8.2.ado b/Modules/ado/personal/l/loevh v8.2.ado
new file mode 100644
index 0000000..0615c18
--- /dev/null
+++ b/Modules/ado/personal/l/loevh v8.2.ado
@@ -0,0 +1,1068 @@
+*! Version 8.2 13 July 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 [Jean-Benoit Hardouin] /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 [Jean-Benoit Hardouin] /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 [Jean-Benoit Hardouin] /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 [Jean-Benoit Hardouin] /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 [Jean-Benoit Hardouin] /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 [Jean-Benoit Hardouin] /*html option*/
+* Release 8.1.1 : November 20, 2012 [Jean-Benoit Hardouin] /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 [Jean-Benoit Hardouin] /*minor correction*/
+* Release 8.1.3 : March 23, 2015 [Jean-Benoit Hardouin] /*minor correction for displaying results*/
+* Release 8.2 : July 13, 2019 [Jean-Benoit Hardouin] /*correction for the displaying and the saving of the graphs, deletion of the html option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE
+* Nantes University - University of Tours
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2015, 2019 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string) filesave dirsave(string) pro]
+preserve
+
+/***********************************************************************************************************
+TESTS INITIAUX
+***********************************************************************************************************/
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+if "`filesave'"!=""&"`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}*/
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+
+/***********************************************************************************************************
+CALCUL DES ERREURS DE GUTTMAN ET COEFFICIENTS DE LOEVINGER
+***********************************************************************************************************/
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+local loevH=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+/***********************************************************************************************************
+AFFICHAGE DES PREMIERS RESULTATS
+***********************************************************************************************************/
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(36) %7.0f `eGuttj'[1,`j'] _col(45) %10.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(36) %7.0f `eGutt' _col(45) %10.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/***********************************************************************************************************
+MONOTONICITY
+***********************************************************************************************************/
+
+
+if "`monotonicity'"!="" {
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ *set trace on
+ if `vi`i''!=0 {
+ if "`pro'"=="" {
+ local graph1 "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ local graph1
+ }
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "`graph1'"
+ }
+ else {
+ if "`pro'"=="" {
+ local graph1 "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ local graph1
+ }
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "`graph1'"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ if "`pro'"!=""&"`filesave'"!="" {
+ qui traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i'') filesave dirsave(`dirsave')
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+
+
+/***********************************************************************************************************
+PPP et PMM MATRICES
+***********************************************************************************************************/
+
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ qui local saving
+ }
+ else {
+ qui local saving saving(`dirsave'//ppp,replace)
+ }
+ if `scoremax'<20 {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving'
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ qui local saving
+ }
+ else {
+ qui local saving saving(`dirsave'//pmm,replace)
+ }
+ if `scoremax'<20 {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if `scoremax'>19&("`ppp'"!=""|"`pmm'"!="")&"`graph'"!="" {
+ di
+ di "Due to the total number of possibles scores (`=`scoremax'+1'), the P++ and P-- graphical representations cannot be displayed"
+}
+
+/***********************************************************************************************************
+NIPMATRIX
+***********************************************************************************************************/
+
+
+if "`nipmatrix'" !="" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+
+qui use "`loevHfile'",clear
+
+
+/***********************************************************************************************************
+GENERATION DE NOUVELLES VARIABLES
+***********************************************************************************************************/
+
+
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ forvalues i=1/`nbitems' {
+ capture drop `generror'_``i''
+ qui gen `generror'_``i''=0
+ }
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ *di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ }
+ }
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ local saving1
+ local saving2
+ local saving3
+ }
+ else {
+ local saving1 saving(`dirsave'//`generror', replace)
+ local saving2 saving(`dirsave'//`generror'_H, replace)
+ local saving3 saving(`dirsave'//`generror'_box, replace)
+ }
+ qui histogram `generror',discrete freq name(errors,replace) `saving1'
+ qui graph box `generror',name(errors_box,replace) `saving3'
+ qui histogram `generror'_H,discrete freq name(H,replace) `saving2'
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/loevh.ado b/Modules/ado/personal/l/loevh.ado
new file mode 100644
index 0000000..0145ad2
--- /dev/null
+++ b/Modules/ado/personal/l/loevh.ado
@@ -0,0 +1,1069 @@
+*! Version 8.3 29 August 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 [Jean-Benoit Hardouin] /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 [Jean-Benoit Hardouin] /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 [Jean-Benoit Hardouin] /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 [Jean-Benoit Hardouin] /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 [Jean-Benoit Hardouin] /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 [Jean-Benoit Hardouin] /*html option*/
+* Release 8.1.1 : November 20, 2012 [Jean-Benoit Hardouin] /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 [Jean-Benoit Hardouin] /*minor correction*/
+* Release 8.1.3 : March 23, 2015 [Jean-Benoit Hardouin] /*minor correction for displaying results*/
+* Release 8.2 : July 13, 2019 [Jean-Benoit Hardouin] /*correction for the displaying and the saving of the graphs, deletion of the html option*/
+* Release 8.3 : August 29, 2019 [Jean-Benoit Hardouin] /*correction of a bug with the graph and generror options*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE
+* Nantes University - University of Tours
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2015, 2019 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string) filesave dirsave(string) pro]
+preserve
+
+/***********************************************************************************************************
+TESTS INITIAUX
+***********************************************************************************************************/
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+if "`filesave'"!=""&"`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}*/
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+
+/***********************************************************************************************************
+CALCUL DES ERREURS DE GUTTMAN ET COEFFICIENTS DE LOEVINGER
+***********************************************************************************************************/
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+local loevH=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+/***********************************************************************************************************
+AFFICHAGE DES PREMIERS RESULTATS
+***********************************************************************************************************/
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(36) %7.0f `eGuttj'[1,`j'] _col(45) %10.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(36) %7.0f `eGutt' _col(45) %10.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/***********************************************************************************************************
+MONOTONICITY
+***********************************************************************************************************/
+
+
+if "`monotonicity'"!="" {
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ *set trace on
+ if `vi`i''!=0 {
+ if "`pro'"=="" {
+ local graph1 "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ local graph1
+ }
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "`graph1'"
+ }
+ else {
+ if "`pro'"=="" {
+ local graph1 "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ local graph1
+ }
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "`graph1'"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ if "`pro'"!=""&"`filesave'"!="" {
+ qui traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i'') filesave dirsave(`dirsave')
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+
+
+/***********************************************************************************************************
+PPP et PMM MATRICES
+***********************************************************************************************************/
+
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ qui local saving
+ }
+ else {
+ qui local saving saving(`dirsave'//ppp,replace)
+ }
+ if `scoremax'<20&"`ppp'"!="" {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving'
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ qui local saving
+ }
+ else {
+ qui local saving saving(`dirsave'//pmm,replace)
+ }
+ if `scoremax'<20 {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if `scoremax'>19&("`ppp'"!=""|"`pmm'"!="")&"`graph'"!="" {
+ di
+ di "Due to the total number of possibles scores (`=`scoremax'+1'), the P++ and P-- graphical representations cannot be displayed"
+}
+
+/***********************************************************************************************************
+NIPMATRIX
+***********************************************************************************************************/
+
+
+if "`nipmatrix'" !="" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+
+qui use "`loevHfile'",clear
+
+
+/***********************************************************************************************************
+GENERATION DE NOUVELLES VARIABLES
+***********************************************************************************************************/
+
+
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ forvalues i=1/`nbitems' {
+ capture drop `generror'_``i''
+ qui gen `generror'_``i''=0
+ }
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ *di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ }
+ }
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ if "`filesave'"=="" {
+ local saving1
+ local saving2
+ local saving3
+ }
+ else {
+ local saving1 saving(`dirsave'//`generror', replace)
+ local saving2 saving(`dirsave'//`generror'_H, replace)
+ local saving3 saving(`dirsave'//`generror'_box, replace)
+ }
+ qui histogram `generror',discrete freq name(errors,replace) `saving1'
+ qui graph box `generror',name(errors_box,replace) `saving3'
+ qui histogram `generror'_H,discrete freq name(H,replace) `saving2'
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/loevh.hlp b/Modules/ado/personal/l/loevh.hlp
new file mode 100644
index 0000000..3dec6e7
--- /dev/null
+++ b/Modules/ado/personal/l/loevh.hlp
@@ -0,0 +1,103 @@
+{smcl}
+{* 8december2010}{...}
+{hline}
+help for {hi:loevh}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Loevinger's H coefficients and non parametric Item Responses Models}
+
+{p 8 14 2}{cmd:loevh} {it:varlist} [{cmd:,} {cmdab:pairw:ise} {cmdab:pair} {cmdab:ppp} {cmdab:pmm} {cmdab:noadj:ust} {cmdab:gener:ror}({it:newvar}) {cmdab:rep:lace} {cmdab:gr:aph} {cmdab:mono:tonicity}({it:string}) {cmdab:nip:matrix}({it:string})]
+
+{p 8 14 2}{it:varlist} is a list of two or more existing dichotomous ou polytomous variables.
+
+{title:Description}
+
+{p 4 8 2}{cmd:loevh} allows verifying the fit of data to the Monotonely Homogeneous Mokken Model or to the Doubly Monotone Mokken Model.
+It computes the Loevinger H scalability coefficients, and several indexes in the field of the Non parametric Item Response Theory.
+
+{title:Options}
+
+{p 4 8 2}{cmd:pairwise}. By default, all the individuals with one or more missing values are omitted. {cmd:pairwise} allows to use the complete information by pair of items.
+
+{p 4 8 2}{cmd:pair} displays statistics and the value of the Loevinger H coefficient for each pair of items.
+
+{p 4 8 2}{cmd:ppp} displays the P++ matrix.
+
+{p 4 8 2}{cmd:pmm} displays the P-- matrix.
+
+{p 4 8 2}{cmd:noadjust} approximates the tests statistics like the MSP software (Molenaar et al. (2000)).
+
+{p 4 8 2}{cmd:generror} creates a new variable containing the number of Guttman errors produced by each individual.
+
+{p 4 8 2}{cmd:replace} allows replacing the variable defined by the {cmd:generror} option.
+
+{p 4 8 2}{cmd:graph} displays graphs (only with the {cmd:ppp}, {cmd:pmm} and {cmd:generror} options).
+
+{p 4 8 2}{cmd:monotonicity} displays indexes in order to check the monotonicity of the data (Monotone Homogeneity Mokken Model). This option produces outputs similar to the MSP software.
+The string contains several suboptions: {cmd:minvi}, {cmd:minsize}, {cmd:siglevel} and {cmd:details}. If you want use all the default values, type *.{p_end}
+{p 10 12 10}{cmd:minvi} defines the minimal size of a violation of monotonicity (0.03 by default){p_end}
+{p 10 12 10}{cmd:minsize} defines the minimum size of groups of patients to check the monotonicity (by default, the number of individuals divided by 10 with more than 500 individuals, the same number divided by 5 with more than 250 individuals, and the same number divided by 3 for a smaller number, with a minimum of 50){p_end}
+{p 10 12 10}{cmd:siglevel} defines the significance level for the tests (0.05 by default){p_end}
+{p 10 12 10}{cmd:details} displays more details with polytomous items
+
+{p 4 8 2}{cmd:nipmatrix} display indexes in order to check the non-intersection (Doubly Monotone Mokken Model). This option produces outputs similar to the MSP software.
+The string contains several suboptions: {cmd:minvi} and {cmd:siglevel}. If you want use all the default values, type *.{p_end}
+{p 10 12 10}{cmd:minvi} defines the minimal size of a violation of non-intersection (0.03 by default){p_end}
+{p 10 12 10}{cmd:siglevel} defines the significance level for the tests (0.05 by default){p_end}
+
+
+{title:Remarks}
+
+{p 4 8 2}For detailed informations on the Loevinger's H coefficients, see Loevinger (1948) or Hemker and al. (1995). For details about the analysis of non parametric Mokken models, see for example the MSP 5.0 manual.
+
+
+{title:Example}
+
+ {p 8 8}{inp:. loevh itemA1-itemA7}
+
+ {p 8 8}{inp:. loevh itemA*, pair monotonicity(*) ppp pmm nipmatrix(minvi(0.05) siglevel(0.01))}
+
+ {p 8 8}{inp:. loevh item*, pairwise generror(error) graph}
+
+{title:Results}
+
+{p 4 8 2}The Loevinger's H coefficients between all the pairs of items, for each item with respect of all the others items and for the set of items are respectively saved in the matrices {it:r(loevHjk)}, {it:r(loevHj)}
+and in the scalar {it:r(loevh)}.
+
+{p 4 8 2}The empirical Guttman errors between all the pairs of items, associated to each item and relied to the scale are respectively saved in the matrices {it:r(eGuttjk)}, {it:r(eGuttj)} and in the scalar {it:e(Gutt)}.
+
+{p 4 8 2}The theorical Guttman errors between all the pairs of items, associated to each item and relied to the scale are respectively saved in the matrices {it:r(eGuttjk0)}, {it:r(eGuttj0)} and in the scalar {it:e(Gutt0)}.
+
+{p 4 8 2}The values of the Z statistics and the corresponding p-values associated to the Loevinger H coefficients are respectively saved in the matrices {it:r(zHjk)}, {it:r(pvalHjk)}, {it:r(zHj)}, {it:r(pvalHj)}
+and in the scalars {it:e(zH)} and {it:r(pvalH)}.
+
+{p 4 8 2}The P++ and P-- matrices are saved in {it:r(ppp)} and {it:r(pmm)}.
+
+{p 4 8 2}The used number of individuals per items pair is saved in {it:r(Obs)}.
+
+
+{title:References}
+
+{p 4 8 2}Hemker B. T., Sijtsma K. and Molenaar I. W., Selection of unidimensional scales from a multidimensional item bank in the polytomous Mokken IRT
+model, {it: Applied Psychological Measurement}, vol.19(4), 1995, pp. 337-352.
+
+{p 4 8 2}Loevinger J., The technique of homogeneous tests compared with some aspects of "scale analysis" and factor analysis. {it:Psychological bulletin},
+vol. 45, 1948, pp. 507-530.
+
+{p 4 8 2}Molenaar I. W., Sijtsma K. and Boer P. {it:MSP5 for Windows - User's Manual}, 2000, 105 pages.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help traces}, {help msp}, {help gengroup}, {help mokken} if installed.{p_end}
diff --git a/Modules/ado/personal/l/loevh8-1-3.ado b/Modules/ado/personal/l/loevh8-1-3.ado
new file mode 100644
index 0000000..00a2a00
--- /dev/null
+++ b/Modules/ado/personal/l/loevh8-1-3.ado
@@ -0,0 +1,1393 @@
+*! Version 8.1.5 23 March 2015
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8.1.3 : March 23, 2015 /*minor correction for displaying results*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 /*html option*/
+* Release 8.1.1 : November 20, 2012 /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 /*minor correction*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2015 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]
+preserve
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di in gr ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+local loevH=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+if "`html'" == "" {
+ di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+ di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+ di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+ di in green "{hline 99}"
+ forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(36) %7.0f `eGuttj'[1,`j'] _col(45) %10.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+ }
+ di in green "{hline 99}"
+}
+else {
+ di in gr ""
+ di in gr ""
+ di in gr "Item | Obs | Mean Score | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hj ≤ 0 p-value | "
+ di in gr "Number of NS Hjk |
"
+ forvalues j=1/`nbitems' {
+ di in green "``j'' | " `Obs'[`j',`j'] " | " %6.4f `diff'[1,`j'] " | " %5.0f `eGuttj'[1,`j'] " | " %8.2f `eGuttj0'[1,`j'] " | " %7.5f `loevHj'[1,`j'] " | " %8.4f `zHj'[1,`j'] " | " %7.5f `pvalHj'[1,`j'] " | " %2.0f `nbHjkNS`j'' " |
"
+ }
+}
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+if "`html'" == "" {
+ di in green "Scale" in yellow _col(15) `nb' _col(36) %7.0f `eGutt' _col(45) %10.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+}
+else {
+ di in green "Scale | " `nb' " | | " %5.0f `eGutt' " | " %8.2f `eGutt0' " | " %-8.5f `loevH' " | " %9.4f `zH' " | " %7.5f `pvalH' " | |
"
+ di in gr "
"
+}
+
+if "`pair'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary of results by items pairs"
+ di in green "Items | " "`text'" " Obs P(Xj=`value',Xk=`value') | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hjk ≤ 0 p-value |
"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "" "``j''" " | " "``k''" " | " `Obs'[`j',`k'] " | " %6.4f `P`value'`value''[`j',`k'] " | " %5.0f `eGuttjk'[`j',`k'] " | " %8.2f `eGuttjk0'[`j',`k'] " | " %8.5f `loevHjk'[`j',`k'] " | " %9.4f `zHjk'[`j',`k'] " | " %7.5f `pvalHjk'[`j',`k'] " |
"
+ }
+ }
+ di in green " |
---|
"
+ }
+}
+
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ if "`html'" == "" {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ }
+ else {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items
"
+ }
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of monotonicity"
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | zmax | #zsig | Crit |
"
+ }
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " | " %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `maxvi`i'_m`l'' " | " %6.4f `sumvi`i'_m`l'' " | " %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `zmaxvi`i'_m`l'' " | " %8.0f `nbzvi`i'_m`l'' " | |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " |
"
+ }
+ }
+ }
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | " %6.4f `=`vi`i''/`ac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`ac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzvi`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in gr "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ if "`html'" == "" {
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+ }
+ else {
+ di in green "Total | " `ac' " | " %8.0f `vi' " | " %6.4f `=`vi'/`ac'' " | " %6.4f `maxvi' " | " %6.4f `sumvi' " | " %6.4f `=`sumvi'/`ac'' " | " %6.4f `zmaxvi' " | " %8.0f `nbzvi' " | |
---|
"
+ }
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_ppp,replace) nodraw"
+ }
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving' xsize(2) ysize(2)
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_ppp.gph
+ qui graph export `c(tmpdir)'/`html'_ppp.eps, replace
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P++ values per items pair (The values should be increasing in each column) |
"
+ di ""
+ matrixlisthtml `matpp' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_pmm,replace) nodraw"
+ *qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *graph use `c(tmpdir)'/`html'_pmm.gph
+ *qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ *else {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *}
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_pmm.gph
+ qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P-- values per items pair (The values should be decreasing in each column) |
"
+ di ""
+ matrixlisthtml `matmm' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if "`nipmatrix'" !="" {
+ *set trace on
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of non-Intersection via Pmatrix
"
+ di in gr "Minvi=" in ye %5.3f `minvi' " Alpha=" in ye %5.3f `siglevel' ""
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | "
+ di in gr "zmax | #zsig | Crit |
"
+ }
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di in green " |
---|
"
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ forvalues i=1/`nbitems' {
+ qui gen `generror'_``i''=0
+ }
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/loevh8.ado b/Modules/ado/personal/l/loevh8.ado
new file mode 100644
index 0000000..5788472
--- /dev/null
+++ b/Modules/ado/personal/l/loevh8.ado
@@ -0,0 +1,1235 @@
+*! Version 8 8 December 2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2008 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string)]
+preserve
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+
+di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+di in green "{hline 99}"
+forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+}
+di in green "{hline 99}"
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+if "`pair'"!="" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+}
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+if "`nipmatrix'"!="" {
+ *set trace on
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
diff --git a/Modules/ado/personal/l/loevh81.ado b/Modules/ado/personal/l/loevh81.ado
new file mode 100644
index 0000000..b94814a
--- /dev/null
+++ b/Modules/ado/personal/l/loevh81.ado
@@ -0,0 +1,1346 @@
+*! Version 8.1 19 October 2012
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8.1: October 19, 2012 /*html option*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2008 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 loevh , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]
+preserve
+
+if "`html'" != "" {
+ di in gr ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+if "`html'" == "" {
+ di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+ di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+ di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+ di in green "{hline 99}"
+ forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+ }
+ di in green "{hline 99}"
+}
+else {
+ di in gr ""
+ di in gr ""
+ di in gr "Item | Obs | Mean Score | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hj ≤ 0 p-value | "
+ di in gr "Number of NS Hjk |
"
+ forvalues j=1/`nbitems' {
+ di in green "``j'' | " `Obs'[`j',`j'] " | " %6.4f `diff'[1,`j'] " | " %5.0f `eGuttj'[1,`j'] " | " %8.2f `eGuttj0'[1,`j'] " | " %7.5f `loevHj'[1,`j'] " | " %8.4f `zHj'[1,`j'] " | " %7.5f `pvalHj'[1,`j'] " | " %2.0f `nbHjkNS`j'' " |
"
+ }
+}
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+if "`html'" == "" {
+ di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+}
+else {
+ di in green "Scale | " `nb' " | | " %5.0f `eGutt' " | " %8.2f `eGutt0' " | " %-8.5f `loevH' " | " %9.4f `zH' " | " %7.5f `pvalH' " | |
"
+ di in gr "
"
+}
+
+if "`pair'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary of results by items pairs"
+ di in green "Items | " "`text'" " Obs P(Xj=`value',Xk=`value') | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hjk ≤ 0 p-value |
"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "" "``j''" " | " "``k''" " | " `Obs'[`j',`k'] " | " %6.4f `P`value'`value''[`j',`k'] " | " %5.0f `eGuttjk'[`j',`k'] " | " %8.2f `eGuttjk0'[`j',`k'] " | " %8.5f `loevHjk'[`j',`k'] " | " %9.4f `zHjk'[`j',`k'] " | " %7.5f `pvalHjk'[`j',`k'] " |
"
+ }
+ }
+ di in green " |
---|
"
+ }
+}
+
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ if "`html'" == "" {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ }
+ else {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items
"
+ }
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of monotonicity"
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | zmax | #zsig | Crit |
"
+ }
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " | " %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `maxvi`i'_m`l'' " | " %6.4f `sumvi`i'_m`l'' " | " %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `zmaxvi`i'_m`l'' " | " %8.0f `nbzvi`i'_m`l'' " | |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " |
"
+ }
+ }
+ }
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | " %6.4f `=`vi`i''/`ac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`ac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzvi`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in gr "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ if "`html'" == "" {
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+ }
+ else {
+ di in green "Total | " `ac' " | " %8.0f `vi' " | " %6.4f `=`vi'/`ac'' " | " %6.4f `maxvi' " | " %6.4f `sumvi' " | " %6.4f `=`sumvi'/`ac'' " | " %6.4f `zmaxvi' " | " %8.0f `nbzvi' " | |
---|
"
+ }
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ local saving "saving(`c(tmpdir)'/`html'_ppp.jpg,replace) nodraw"
+ }
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving'
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+ if "`ppp'"!="" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ local saving "saving(`c(tmpdir)'/`html'_pmm.jpg,replace) nodraw"
+ }
+ twoway conn `list' `id2' in 1/`scoremax',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if "`nipmatrix'" !="" {
+ *set trace on
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of non-Intersection via Pmatrix
"
+ di in gr "Minvi=" in ye %5.3f `minvi' " Alpha=" in ye %5.3f `siglevel' ""
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | "
+ di in gr "zmax | #zsig | Crit |
"
+ }
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di in green " |
---|
"
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+capture restore, not
+
+end
diff --git a/Modules/ado/personal/l/loevh812.zip b/Modules/ado/personal/l/loevh812.zip
new file mode 100644
index 0000000..a47962d
Binary files /dev/null and b/Modules/ado/personal/l/loevh812.zip differ
diff --git a/Modules/ado/personal/l/loevh813.ado b/Modules/ado/personal/l/loevh813.ado
new file mode 100644
index 0000000..170220a
--- /dev/null
+++ b/Modules/ado/personal/l/loevh813.ado
@@ -0,0 +1,1403 @@
+*! Version 8.1.3 April 14, 2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8.1.3 : April 14, 2014 /*minor correction*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 /*html option*/
+* Release 8.1.1 : November 20, 2012 /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 /*minor correction*/
+* Release 8.1.3 : April 14, 2014 [Jean-Benoit Hardouin, Bastien Perrot] /*generror graph with the html option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2012 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 loevh813 , rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]
+preserve
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di in gr ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+if "`html'" == "" {
+ di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+ di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+ di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+ di in green "{hline 99}"
+ forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+ }
+ di in green "{hline 99}"
+}
+else {
+ di in gr ""
+ di in gr ""
+ di in gr "Item | Obs | Mean Score | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hj ≤ 0 p-value | "
+ di in gr "Number of NS Hjk |
"
+ forvalues j=1/`nbitems' {
+ di in green "``j'' | " `Obs'[`j',`j'] " | " %6.4f `diff'[1,`j'] " | " %5.0f `eGuttj'[1,`j'] " | " %8.2f `eGuttj0'[1,`j'] " | " %7.5f `loevHj'[1,`j'] " | " %8.4f `zHj'[1,`j'] " | " %7.5f `pvalHj'[1,`j'] " | " %2.0f `nbHjkNS`j'' " |
"
+ }
+}
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+if "`html'" == "" {
+ di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+}
+else {
+ di in green "Scale | " `nb' " | | " %5.0f `eGutt' " | " %8.2f `eGutt0' " | " %-8.5f `loevH' " | " %9.4f `zH' " | " %7.5f `pvalH' " | |
"
+ di in gr "
"
+}
+
+if "`pair'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary of results by items pairs"
+ di in green "Items | " "`text'" " Obs P(Xj=`value',Xk=`value') | Observed Guttman Errors | Expected Guttman Errors | "
+ di in gr "Loevinger H coeff | z-stat. | H0: Hjk ≤ 0 p-value |
"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "" "``j''" " | " "``k''" " | " `Obs'[`j',`k'] " | " %6.4f `P`value'`value''[`j',`k'] " | " %5.0f `eGuttjk'[`j',`k'] " | " %8.2f `eGuttjk0'[`j',`k'] " | " %8.5f `loevHjk'[`j',`k'] " | " %9.4f `zHjk'[`j',`k'] " | " %7.5f `pvalHjk'[`j',`k'] " |
"
+ }
+ }
+ di in green " |
---|
"
+ }
+}
+
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ if "`html'" == "" {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ }
+ else {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items
"
+ }
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of monotonicity"
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | zmax | #zsig | Crit |
"
+ }
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " | " %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `maxvi`i'_m`l'' " | " %6.4f `sumvi`i'_m`l'' " | " %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' " | " %6.4f `zmaxvi`i'_m`l'' " | " %8.0f `nbzvi`i'_m`l'' " | |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ else {
+ di in gr "``i''>=`l' | " %8.0f `ac`i'_m`l'' " | " %8.0f `vi`i'_m`l'' " |
"
+ }
+ }
+ }
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | " %6.4f `=`vi`i''/`ac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`ac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzvi`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in gr "``i'' | " %8.0f `ac`i'' " | " %8.0f `vi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ if "`html'" == "" {
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+ }
+ else {
+ di in green "Total | " `ac' " | " %8.0f `vi' " | " %6.4f `=`vi'/`ac'' " | " %6.4f `maxvi' " | " %6.4f `sumvi' " | " %6.4f `=`sumvi'/`ac'' " | " %6.4f `zmaxvi' " | " %8.0f `nbzvi' " | |
---|
"
+ }
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_ppp,replace) nodraw"
+ }
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving' xsize(2) ysize(2)
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_ppp.gph
+ qui graph export `c(tmpdir)'/`html'_ppp.eps, replace
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P++ values per items pair (The values should be increasing in each column) |
"
+ di ""
+ matrixlisthtml `matpp' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_pmm,replace) nodraw"
+ *qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *graph use `c(tmpdir)'/`html'_pmm.gph
+ *qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ *else {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *}
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_pmm.gph
+ qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+ if "`html'" == "" {
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+ }
+ else {
+ di ""
+ di " | P-- values per items pair (The values should be decreasing in each column) |
"
+ di ""
+ matrixlisthtml `matmm' "%5.3f"
+ di "
"
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if "`nipmatrix'" !="" {
+ *set trace on
+ if "`html'" == "" {
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+ }
+ else {
+ di in gr ""
+ di in gr "Summary per item for check of non-Intersection via Pmatrix
"
+ di in gr "Minvi=" in ye %5.3f `minvi' " Alpha=" in ye %5.3f `siglevel' ""
+ di in gr "Items | #ac | #vi | #vi / #ac | maxvi | sum | sum / #ac | "
+ di in gr "zmax | #zsig | Crit |
"
+ }
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | " %6.4f `=`nbvi`i''/`nbac`i''' " | " %6.4f `maxvi`i'' " | " %6.4f `sumvi`i'' " | " %6.4f `=`sumvi`i''/`nbac`i''' " | " %6.4f `zmaxvi`i'' " | " %8.0f `nbzsig`i'' " | " %4.0f `crit`i'' " |
"
+ }
+ }
+ else {
+ if "`html'" == "" {
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+ }
+ else {
+ di in green "" "``i''" " | " %8.0f `nbac`i'' " | " %8.0f `nbvi`i'' " | | | | | | | " %4.0f `crit`i'' " |
"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di in green " |
---|
"
+ }
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph'"!="" {
+ qui histogram `generror',discrete freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ if "`graph'" != "" & "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_errors,replace) nodraw"
+ qui histogram `generror',discrete freq name(errors,replace) title("Number of Guttman errors per individual") `saving'
+ qui graph use `c(tmpdir)'/`html'_errors.gph
+ qui graph export `c(tmpdir)'/`html'_errors.eps, replace
+ di ""
+ }
+
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/loevh82.ado b/Modules/ado/personal/l/loevh82.ado
new file mode 100644
index 0000000..2605c8d
--- /dev/null
+++ b/Modules/ado/personal/l/loevh82.ado
@@ -0,0 +1,1347 @@
+*! Version 8.2 May 23, 2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : loevh
+* Loevinger H indexes, Mokken Analysis
+* Release 8.2 : May 23, 2014 /*remove html tags*/
+*
+*
+* Historic :
+* Version 1 (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (June 22, 2003) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 6 (July 3, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 (September 19, 2005) [Jean-Benoit Hardouin]
+* Version 6.2 (January 31, 2006) [Jean-Benoit Hardouin]
+* Release 6.3 (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.4 (January 19, 2007) [Jean-Benoit Hardouin] /*Tests to compare Loevinger coefficients to 0 identical to the MSP software (dichotomous and polytomous case)*/
+* Release 6.5 (January 22, 2007) [Jean-Benoit Hardouin] /*Correction of a bug concerning the p-values with the pair option*/
+* Release 6.6 (Februar 16, 2007) [Jean-Benoit Hardouin] /*Correction of a bug with the displaying of Easyness with polytomous items, option graph, option generror, improvements*/
+* Release 7: June 21, 2007 /*Check of monotonicity and Non intersection via P matrices*/
+* Release 7.1: November 6, 2008 /*Correction for the z-tests for the check of non intersection via P matrices*/
+* Release 7.2: November 19, 2008 /*Implementation of the GPN indexes*/
+* Release 7.3: August 15, 2009 /*Print the difficulties of the items instead of P(X=0)*/
+* Release 8: December 8, 2010 /*loevH is renamed loevh*/
+* Release 8.1: October 19, 2012 /*html option*/
+* Release 8.1.1 : November 20, 2012 /*graphs with the html option*/
+* Release 8.1.2 : December 7, 2012 /*minor correction*/
+* Release 8.1.3 : April 14, 2014 [Jean-Benoit Hardouin, Bastien Perrot] /*generror graph with the html option*/
+* Release 8.2 : May 23, 2014 [Jean-Benoit Hardouin, Bastien Perrot] /*remove html tags*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* Requiered Stata modules:
+* -anaoption- (version 1)
+* -traces- (version 3.2)
+* -gengroup- (version 1)
+* -guttmax- (version 1)
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2002-2012 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 loevh82, rclass
+version 8.2
+syntax varlist(min=2 numeric) [if] [,PAIRWise PAIR ppp pmm noADJust GENERror(string) REPlace GRaph MONOtonicity(string) NIRESTscore(string) NIPmatrix(string) HTML(string)]
+preserve
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di in gr ""
+ di ""
+}
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempname corr cov P1 P0 diff P11 P00 H1jk vHjk zHjk chi2Hjk dfHjk pvalHjk H1j vHj zHj pvalHj H1 vH zH pvalH Obs eGuttjk eGuttjk0 loevHjk eGuttj eGuttj0 loevHj eGutt eGutt0 loevH e1 e2
+tempfile loevHfile
+qui save "`loevHfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`adjust'"!="" {
+ local adj=0
+}
+else {
+ local adj=1
+}
+
+qui count
+local nbobs=r(N)
+
+forvalues j=1/`nbitems' {
+ if "`pairwise'"=="" {
+ qui drop if ``j''==.
+ }
+}
+qui count
+local nbtotindnm=r(N)
+
+matrix define `eGuttjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttjk0'=J(`nbitems',`nbitems',0)
+matrix define `loevHjk'=J(`nbitems',`nbitems',0)
+matrix define `eGuttj'=J(1,`nbitems',0)
+matrix define `eGuttj0'=J(1,`nbitems',0)
+matrix define `loevHj'=J(1,`nbitems',0)
+scalar define `eGutt'=0
+scalar define `eGutt0'=0
+scalar define `loevH'=0
+matrix define `Obs'=J(`nbitems',`nbitems',0)
+matrix define `P00'=J(`nbitems',`nbitems',0)
+
+tempname modamax
+scalar `modamax'=0
+local scoremax=0
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ local m`j'=r(max)
+ local scoremax=`scoremax'+`m`j''
+ if r(max)>`modamax' {
+ scalar `modamax'=r(max)
+ }
+ local nbHjkNS`j'=0
+}
+
+/*if "`generror'"!=""&`modamax'!=1 {
+ di in ye "It is not possible to define the {cmd:generror} option with polytomous items"
+ local generror
+} */
+*di "scoremax `scoremax'"
+
+if "`graph'"!="" & "`generror'"!=""{
+ local graph2 = "graph"
+}
+
+if "`graph'"!=""&`scoremax'>19 {
+ di in ye "The {cmd:graph} option is disabled because of a large number of possible scores (>20)"
+ local graph
+}
+
+matrix define `cov'=J(`nbitems',`nbitems',0)
+matrix define `corr'=J(`nbitems',`nbitems',0)
+matrix define `P11'=J(`nbitems',`nbitems',0)
+matrix define `H1jk'=J(`nbitems',`nbitems',0)
+matrix define `vHjk'=J(`nbitems',`nbitems',0)
+matrix define `zHjk'=J(`nbitems',`nbitems',0)
+matrix define `pvalHjk'=J(`nbitems',`nbitems',0)
+matrix define `P1'=J(1,`nbitems',0)
+matrix define `P0'=J(1,`nbitems',0)
+matrix define `diff'=J(1,`nbitems',0)
+matrix define `H1j'=J(1,`nbitems',0)
+matrix define `vHj'=J(1,`nbitems',0)
+matrix define `zHj'=J(1,`nbitems',0)
+matrix define `pvalHj'=J(1,`nbitems',0)
+
+forvalues j=1/`nbitems' {
+ qui su ``j''
+ matrix `cov'[`j',`j']=r(Var)
+ matrix `corr'[`j',`j']=1
+ local tmp=`j'+1
+ qui count if ``j''!=.
+ matrix `Obs'[`j',`j']=r(N)
+ forvalues k=`tmp'/`nbitems' {
+ qui count if ``j''!=.&``k''!=.
+ matrix `Obs'[`j',`k']=r(N)
+ matrix `Obs'[`k',`j']=r(N)
+ qui corr ``j'' ``k'',cov
+ matrix `cov'[`j',`k']=r(cov_12)
+ matrix `cov'[`k',`j']=r(cov_12)
+ qui corr ``j'' ``k''
+ matrix `corr'[`j',`k']=r(rho)
+ matrix `corr'[`k',`j']=r(rho)
+ matrix `zHjk'[`j',`k']=`corr'[`j',`k']*(`Obs'[`j',`k']-`adj')^.5
+ matrix `zHjk'[`k',`j']=`H1jk'[`j',`k']
+ matrix `pvalHjk'[`j',`k']=1-norm(`zHjk'[`j',`k'])
+ matrix `pvalHjk'[`k',`j']=`pvalHjk'[`j',`k']
+ if `pvalHjk'[`j',`k']>0.05 {
+ local nbHjkNS`j'=`nbHjkNS`j''+1
+ local nbHjkNS`k'=`nbHjkNS`k''+1
+ }
+ forvalues mod1=1/`m`j'' {
+ forvalues mod2=1/`m`k'' {
+ qui count if ``j''<`mod1'&``k''>=`mod2'&``j''!=.&``k''!=.
+ scalar `e1'=r(N)
+ qui count if ``j''>=`mod1'&``k''<`mod2'&``j''!=.&``k''!=.
+ scalar `e2'=r(N)
+ matrix `eGuttjk'[`j',`k']=`eGuttjk'[`j',`k']+min(`e1',`e2')
+ qui count if ``j''<`mod1'&``j''!=.&``k''!=.
+ local t1=r(N)
+ qui count if ``k''<`mod2'&``j''!=.&``k''!=.
+ local t2=r(N)
+ qui count if ``j''>=`mod1'&``j''!=.&``k''!=.
+ local t3=r(N)
+ qui count if ``k''>=`mod2'&``j''!=.&``k''!=.
+ local t4=r(N)
+ if min(`e1',`e2')==`e1' {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t1'*`t4'/`Obs'[`j',`k']
+ }
+ else {
+ matrix `eGuttjk0'[`j',`k']=`eGuttjk0'[`j',`k']+`t2'*`t3'/`Obs'[`j',`k']
+ }
+
+ }
+ }
+ qui count if ``j''==0&``k''==0
+ matrix `P00'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P00'[`k',`j']=r(N)/`Obs'[`k',`j']
+ if `modamax'==1 {
+ qui count if ``j''==1&``k''==1
+ matrix `P11'[`j',`k']=r(N)/`Obs'[`j',`k']
+ matrix `P11'[`k',`j']=r(N)/`Obs'[`k',`j']
+ }
+
+ matrix `eGuttjk'[`k',`j']=`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`j']=`eGuttj'[1,`j']+`eGuttjk'[`j',`k']
+ matrix `eGuttj'[1,`k']=`eGuttj'[1,`k']+`eGuttjk'[`j',`k']
+ matrix `eGuttjk0'[`k',`j']=`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`j']=`eGuttj0'[1,`j']+`eGuttjk0'[`j',`k']
+ matrix `eGuttj0'[1,`k']=`eGuttj0'[1,`k']+`eGuttjk0'[`j',`k']
+
+ matrix `loevHjk'[`j',`k']=1-`eGuttjk'[`j',`k']/`eGuttjk0'[`j',`k']
+ matrix `loevHjk'[`k',`j']=`loevHjk'[`j',`k']
+
+ }
+ qui count if ``j''!=.
+ local tmp=r(N)
+ qui count if ``j''==1
+ matrix `P1'[1,`j']=r(N)/`tmp'
+ qui count if ``j''==0
+ matrix `P0'[1,`j']=r(N)/`tmp'
+ qui su ``j''
+ matrix `diff'[1,`j']=r(mean)
+ matrix `loevHj'[1,`j']=1-`eGuttj'[1,`j']/`eGuttj0'[1,`j']
+ scalar `eGutt'=`eGutt'+`eGuttj'[1,`j']/2
+ scalar `eGutt0'=`eGutt0'+`eGuttj0'[1,`j']/2
+}
+scalar `H1'=0
+scalar `vH'=0
+scalar `zH'=0
+forvalues j=1/`nbitems'{
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ matrix `zHj'[1,`j']=`zHj'[1,`j']+`cov'[`j',`k']
+ matrix `vHj'[1,`j']=`vHj'[1,`j']+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ if `j'<`k' {
+ scalar `zH'=`zH'+`cov'[`j',`k']
+ scalar `vH'=`vH'+`cov'[`j',`j']*`cov'[`k',`k']/(`Obs'[`j',`k']-`adj')
+ }
+ }
+ matrix `zHj'[1,`j']=`zHj'[1,`j']/sqrt(`vHj'[1,`j'])
+ matrix `pvalHj'[1,`j']=1-norm(`zHj'[1,`j'])
+}
+scalar `zH'=`zH'/sqrt(`vH')
+scalar `pvalH'=1-norm(`zH')
+scalar `loevH'=1-`eGutt'/`eGutt0'
+
+if `modamax'==1 {
+ local text="Easyness"
+ local value=1
+ local col=23
+}
+else {
+ local text="Difficulty"
+ local value=0
+ local col=21
+}
+
+
+ di in green _col(35) "Observed" _col(47) "Expected" _col(93) "Number"
+ di in green _col(27) "Mean" _col(36) "Guttman" _col(48) "Guttman" _col(59) "Loevinger" _col(83) "H0: Hj<=0" _col(94) "of NS"
+ di in green "Item" _col(15) "Obs" _col(26) "Score" _col(37) "errors" _col(49) "errors" _col(61) "H coeff" _col(73) "z-stat." _col(85) "p-value" _col(96) "Hjk"
+ di in green "{hline 99}"
+ forvalues j=1/`nbitems' {
+ di in green "``j''" in yellow _col(15) `Obs'[`j',`j'] _col(25) %6.4f `diff'[1,`j'] _col(38) %5.0f `eGuttj'[1,`j'] _col(47) %8.2f `eGuttj0'[1,`j'] _col(61) %7.5f `loevHj'[1,`j'] _col(72) %8.4f `zHj'[1,`j'] _col(85) %7.5f `pvalHj'[1,`j'] _col(97) %2.0f `nbHjkNS`j''
+ }
+ di in green "{hline 99}"
+
+
+
+if "`pairwise'"=="" {
+ local nb=`nbtotindnm'
+}
+else {
+ local nb=`nbobs'
+}
+
+ di in green "Scale" in yellow _col(15) `nb' _col(38) %5.0f `eGutt' _col(47) %8.2f `eGutt0' _col(61) %-8.5f `loevH' _col(71) %9.4f `zH' _col(85) %7.5f `pvalH'
+
+
+if "`pair'"!="" {
+
+ di
+ di in green _col(45) "Observed" _col(57) "Expected"
+ di in green _col(`=`col'+10') "`text'" _col(46) "Guttman" _col(58) "Guttman" _col(69) "Loevinger" _col(92) "H0: Hjk<=0"
+ di in green "Items" _col(25) "Obs" _col(29) "P(Xj=`value',Xk=`value')" _col(47) "errors" _col(59) "errors" _col(71) "H coeff" _col(83) "z-stat." _col(95) "p-value"
+ di in green "{hline 101}"
+ forvalues j=1/`nbitems' {
+ forvalues k=`=`j'+1'/`nbitems' {
+ qui count if ``j''!=.
+ local obs=r(N)
+ di in green "``j''" _col(10) "``k''" in yellow _col(25) `Obs'[`j',`k'] _col(35) %6.4f `P`value'`value''[`j',`k'] _col(48) %5.0f `eGuttjk'[`j',`k'] _col(57) %8.2f `eGuttjk0'[`j',`k'] _col(70) %8.5f `loevHjk'[`j',`k'] _col(81) %9.4f `zHjk'[`j',`k'] _col(95) %7.5f `pvalHjk'[`j',`k']
+ }
+ }
+ di in green "{hline 101}"
+
+}
+
+/*if `modamax'>1&"`ppp'"!="" {
+ di in green "It is not possible to obtain the P++ diagnostics with polytomous items"
+ local ppp
+}
+if `modamax'>1&"`pmm'"!="" {
+ di in green "It is not possible to obtain the P-- diagnostics with polytomous items"
+ local pmm
+} */
+
+tempname P11g P00g item id id2 p1 monlabel
+
+/*if "`monotonicity'"!=""&`modamax'>1 {
+ if "`html'" == "" {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items"
+ }
+ else {
+ di in green "It is not possible to obtain the latent monotonicity diagnostics with polytomous items
"
+ }
+ local monotonicity
+} */
+
+if "`monotonicity'"!="" {
+*set trace on
+ if "`monotonicity'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`monotonicity'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+
+ di
+ di in green _col(10) "Summary per item for check of monotonicity"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+
+
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ tempname restscore`i'
+ qui gen `restscore`i''=`score'-``i''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroup`i'
+ qui gengroup `restscore`i'',newvariable(`restgroup`i'') minsize(`minsize')
+ local list`i'=r(list)
+ qui su `restgroup`i''
+ local nbgroups`i'=r(max)
+ forvalues j=0/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'
+ local rgroup`j'=r(N)
+ }
+ local vi`i'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ }
+ forvalues l=1/`m`i'' {
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ local nbzvi`i'_`l'=0
+ forvalues j=1/`nbgroups`i'' {
+ qui count if `restgroup`i''==`j'&``i''>=`l'
+ local nbitem`i'rgroup`j'_`l'=r(N)
+ forvalues k=1/`=`j'-1' {
+ local diff=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ if `nbitem`i'rgroup`j'_`l''!=`rgroup`j''&`nbitem`i'rgroup`k'_`l''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitem`i'rgroup`k'_`l''/`rgroup`k''-`nbitem`i'rgroup`j'_`l''/`rgroup`j''
+ }
+ local p=(`nbitem`i'rgroup`k'_`l''+`nbitem`i'rgroup`j'_`l'')/(`rgroup`j''+`rgroup`k'')
+ *local z=`diff'/sqrt(`p'*(1-`p')*(1/`rgroup`j''+1/`rgroup`k''))
+ *di "local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1)) "
+ local z=abs(2*(sqrt(`nbitem`i'rgroup`j'_`l''+1)*sqrt(`rgroup`k''-`nbitem`i'rgroup`k'_`l''+1)-sqrt((`rgroup`j''-`nbitem`i'rgroup`j'_`l'')*`nbitem`i'rgroup`k'_`l''))/sqrt(`rgroup`j''+`rgroup`k''-1))
+ *di "=`z'"
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ }
+ if `j'==`nbgroups`i'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+
+ }
+ else {
+
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+
+ }
+ }
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+
+
+ }
+ else {
+
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+
+
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ if "`html'" == "" {
+ di in green "{dup 97:-}"
+ }
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+
+}
+/*if "`nirestscore'"!="" {
+*set trace on
+ if "`nirestscore'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nirestscore'
+ }
+ local minvi=r(minvi)
+ local siglevel=r(siglevel)
+ local minsize=r(minsize)
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+
+*set trace on
+ tempname score
+ qui genscore `varlist',score(`score')
+ di
+ di in green _col(10) "Summary per item for check of Non-Intersection via Rest-score"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) in green "Minsize=" in ye %5.0f `minsize' _col(40) in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+*set trace on
+ local vi=0
+ local ac=0
+ local sumvi=0
+ local maxvi=0
+ local zmaxvi=0
+ local nbzvi=0
+ forvalues i=1/`nbitems' {
+ local vi`i'`j'=0
+ local ac`i'=0
+ local sumvi`i'=0
+ local maxvi`i'=0
+ local zmaxvi`i'=0
+ local nbzvi`i'=0
+ forvalues l=1/`m`i'' {
+ local vi`i'_m`l'=0
+ local ac`i'_m`l'=0
+ local sumvi`i'_m`l'=0
+ local maxvi`i'_m`l'=0
+ local zmaxvi`i'_m`l'=0
+ local nbzvi`i'_m`l'=0
+ local vi`i'_`l'=0
+ local ac`i'_`l'=0
+ local sumvi`i'_`l'=0
+ local maxvi`i'_`l'=0
+ local zmaxvi`i'_`l'=0
+ }
+ forvalues j=1/`nbitems' {
+ if `j'!=`i' {
+ tempname restscorei`i'j`j'
+ qui gen `restscorei`i'j`j''=`score'-``i''-``j''
+ local restscoremax`i'=`scoremax'-`m`i''
+ tempname restgroupi`i'j`j'
+ qui gengroup `restscorei`i'j`j'',newvariable(`restgroupi`i'j`j'') minsize(`minsize')
+ local listi`i'j`j'=r(list)
+ qui su `restgroupi`i'j`j''
+ local nbgroupsi`i'j`j'=r(max)
+ forvalues k=0/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`k'
+ local rgroup`k'=r(N)
+ }
+ forvalues l=1/`m`i'' {
+ forvalues k=1/`m`j'' {
+ forvalues m=1/`nbgroupsi`i'j`j'' {
+ qui count if `restgroupi`i'j`j''==`m'&``i''>=`l'&``j''>=`k'
+ local nbitemi`i'j`j'rgroup`m'_`l'_`k'=r(N)
+ forvalues n=1/`=`m'-1' {
+ local diff=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ if `nbitemi`i'j`j'rgroup`m'_`l'_`k''!=`rgroup`m''&`nbitemi`i'j`j'rgroup`m'_`l'_`k''!=0 {
+ local ac`i'_`l'=`ac`i'_`l''+1
+ if `diff'>`minvi' {
+ local vi`i'_`l'=`vi`i'_`l''+1
+ local sumvi`i'_`l'=`sumvi`i'_`l''+`diff'
+ if `diff'>`maxvi`i'_`l'' {
+ local maxvi`i'_`l'=`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''/`rgroup`m''
+ }
+ local p=(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+`nbitemi`i'j`j'rgroup`m'_`l'_`k'')/(`rgroup`m''+`rgroup`n'')
+ local z=abs(2*(sqrt(`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)*sqrt(`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k''+1)-sqrt((`rgroup`m''-`nbitemi`i'j`j'rgroup`m'_`l'_`k'')*`nbitemi`i'j`j'rgroup`m'_`l'_`k''))/sqrt(`rgroup`m''+`rgroup`n''-1))
+ if `z'>`=invnorm(1-`siglevel')' {
+ local nbzvi`i'_`l'=`nbzvi`i'_`l''+1
+ }
+ if `z'>`zmaxvi`i'_`l'' {
+ local zmaxvi`i'_`l'=`z'
+ }
+ }
+ }
+ if `m'==`nbgroupsi`i'j`j'' {
+ local vi`i'_m`l'=`vi`i'_`l''
+ local ac`i'_m`l'=`ac`i'_`l''
+ local sumvi`i'_m`l'=`sumvi`i'_`l''
+ local maxvi`i'_m`l'=`maxvi`i'_`l''
+ local zmaxvi`i'_m`l'=`zmaxvi`i'_`l''
+ *local nbzvi`i'_m`l'=`nbzvi`i'_`l''
+ }
+ }
+ }
+ local vi`i'=`vi`i''+`vi`i'_`l''
+ local ac`i'=`ac`i''+`ac`i'_`l''
+ local sumvi`i'=`sumvi`i''+`sumvi`i'_`l''
+ *local nbzvi`i'=`nbzvi`i''+`nbzvi`i'_`l''
+ if `maxvi`i''<`maxvi`i'_`l'' {
+ local maxvi`i'=`maxvi`i'_`l''
+ }
+ if `zmaxvi`i''<`zmaxvi`i'_`l'' {
+ local zmaxvi`i'=`zmaxvi`i'_`l''
+ }
+ }
+ }
+ }
+ if "`details'"!=""&`m`i''!=1 {
+ forvalues l=1/`m`i'' {
+ if `vi`i'_m`l''!=0 {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l'' _col(33) %6.4f `=`vi`i'_m`l''/`ac`i'_m`l''' _col(43) %6.4f `maxvi`i'_m`l'' _col(53) %6.4f `sumvi`i'_m`l'' _col(63) %6.4f `=`sumvi`i'_m`l''/`ac`i'_m`l''' _col(73) %6.4f `zmaxvi`i'_m`l'' _col(81) %8.0f `nbzvi`i'_m`l''
+ }
+ else {
+ di in green "``i''>=`l'" in yellow _col(15) %8.0f `ac`i'_m`l'' _col(23) %8.0f `vi`i'_m`l''
+ }
+ }
+ di in green "{dup 97:-}"
+ }
+ local vi=`vi'+`vi`i''
+ local ac=`ac'+`ac`i''
+ local sumvi=`sumvi'+`sumvi`i''
+ local nbzvi=`nbzvi'+`nbzvi`i''
+ if `maxvi'<`maxvi`i'' {
+ local maxvi=`maxvi`i''
+ }
+ if `zmaxvi'<`zmaxvi`i'' {
+ local zmaxvi=`zmaxvi`i''
+ }
+ *set trace on
+ local t=`loevHj'[1,`i']
+ local crit`i'=50*(.3-`t')+sqrt(`vi`i'')+100*`vi`i''/`ac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`ac`i''+5*`zmaxvi`i''+10*sqrt(`nbzvi`i'')+100*`nbzvi`i''/`ac`i''
+ if `vi`i''!=0 {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(33) %6.4f `=`vi`i''/`ac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`ac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzvi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ else {
+ di in green "``i''" in yellow _col(15) %8.0f `ac`i'' _col(23) %8.0f `vi`i'' _col(93) %4.0f `crit`i'' _col(99) "{stata traces `varlist',rest nodrawcomb cumulative onlyone(``i'') thres(`list`i''):graph}"
+ }
+ if "`details'"!=""&`i'!=`nbitems' {
+ di in green "{dup 97:-}"
+ }
+ local ac=`ac'+`ac`i''
+ local vi=`vi'+`vi`i''
+ }
+ di in green "{hline 97}"
+ di in green "Total" in yellow _col(15) %8.0f `ac' _col(23) %8.0f `vi' _col(33) %6.4f `=`vi'/`ac'' _col(43) %6.4f `maxvi' _col(53) %6.4f `sumvi' _col(63) %6.4f `=`sumvi'/`ac'' _col(73) %6.4f `zmaxvi' _col(81) %8.0f `nbzvi'
+ di in green "{hline 97}"
+} */
+
+if "`ppp'"!=""|"pmm"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ local list
+ local listi
+ local listm
+ local listv
+ forvalues i=1/`nbitems' {
+ forvalues l=1/`m`i'' {
+ tempname item`i'_`l'
+ qui gen `item`i'_`l''=``i''>=`l' if ``i''!=.
+ local list `list' ``i''_`l'
+ local listi `listi' ``i''
+ local listm `listm' `l'
+ local listv `listv' `item`i'_`l''
+ }
+ }
+ tempname matppp matpmm
+ matrix `matppp'=J(`=`scoremax'',`=`scoremax'+2',0)
+ matrix `matpmm'=J(`=`scoremax'',`=`scoremax'+2',0)
+ local row=1
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`m`i'' {
+ local col=1
+ forvalues j=1/`nbitems' {
+ forvalues l=1/`m`j'' {
+ if `i'!=`j' {
+ qui count if `item`i'_`k''!=.&`item`j'_`l''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1&`item`j'_`l''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0&`item`j'_`l''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ }
+ else {
+ matrix `matppp'[`row',`col']=-1
+ matrix `matpmm'[`row',`col']=-1
+ }
+ local col=`col'+1
+ }
+ }
+ qui count if `item`i'_`k''!=.
+ local denom=r(N)
+ qui count if `item`i'_`k''==1
+ local pos=r(N)
+ matrix `matppp'[`row',`col']=`=`pos'/`denom''
+ qui count if `item`i'_`k''==0
+ local pos=r(N)
+ matrix `matpmm'[`row',`col']=`=`pos'/`denom''
+ matrix `matppp'[`row',`=`scoremax'+2']=`i'
+ matrix `matpmm'[`row',`=`scoremax'+2']=`i'
+ local row=`row'+1
+ }
+ }
+ matrix colnames `matppp'=`list' p1 item
+ matrix rownames `matppp'=`list'
+ matrix colnames `matpmm'=`list' p1 item
+ matrix rownames `matpmm'=`list'
+ if "`nipmatrix'"!="" {
+ if "`nipmatrix'"=="*" {
+ anaoption
+ }
+ else {
+ anaoption,`nipmatrix'
+ }
+ local minvi=`r(minvi)'
+ local siglevel=`r(siglevel)'
+ local minsize=`r(minsize)'
+ local details `r(details)'
+ if `minsize'==0 {
+ if `nbobs'>500 {
+ local minsize=round(`nbobs'/10)
+ }
+ else if `nbobs'>250 {
+ local minsize=round(`nbobs'/5)
+ }
+ else {
+ local minsize=max(50,round(`nbobs'/3))
+ }
+ }
+ forvalues i=1/`nbitems' {
+ local nbacpp`i'=0
+ local nbvipp`i'=0
+ local maxvipp`i'=0
+ local sumvipp`i'=0
+ local zmaxpp`i'=0
+ local nbsigzpp`i'=0
+ local nbacmm`i'=0
+ local nbvimm`i'=0
+ local maxvimm`i'=0
+ local sumvimm`i'=0
+ local zmaxmm`i'=0
+ local nbsigzmm`i'=0
+ }
+ }
+
+}
+tempfile temporaryfile
+qui save `temporaryfile'
+
+if "`ppp'"!=""|"`nipmatrix'"!=""|"`generror'"!="" {
+ drop *
+ qui svmat `matppp',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ sort p1
+ qui set obs `=`scoremax'+1'
+ local listitem
+ forvalues i=1/`scoremax' {
+ local t=item[`i']
+ local listitem `listitem' `t'
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_ppp,replace) nodraw"
+ }
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P++ diagnostics") name(ppp,replace) `saving' xsize(2) ysize(2)
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_ppp.gph
+ qui graph export `c(tmpdir)'/`html'_ppp.eps, replace
+ }
+ }
+
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matpp
+ matrix define `matpp'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local ti:word `i' of `listv'
+ local tj:word `j' of `listv'
+ local t:word `j' of `list2'
+ matrix `matpp'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matpp'=`list2'
+ matrix rownames `matpp'=`list2'
+
+ if "`ppp'"!="" {
+
+ di
+ di in green _col(10) "P++ values per items pair (The values should be increasing in each column)"
+ matrix list `matpp',format(%5.3f) nohalf noheader
+
+ if "`html'" != "" {
+
+ //matrixlisthtml `matpp' "%5.3f"
+
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+
+ label drop `monlabel'
+ *set trace on
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacpp`ti'
+ *local ++nbacmm`tk'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==1&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==1&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "++ `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzpp`tj'
+ if abs(`z')>`zmaxpp`tj'' {
+ local zmaxpp`tj'=abs(`z')
+ }
+ local ++nbsigzpp`tk'
+ if abs(`z')>`zmaxpp`tk'' {
+ local zmaxpp`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+/* if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!= `tk'&`ti'!=`tk'&`ti'!=`tj' {
+ local ++nbacpp`ti'
+ local diff=`matpp'[`j',`i']-`matpp'[`k',`i']
+ if `diff'>`minsize'&`diff'!=. {
+ local ++nbvipp`tj'
+ local ++nbvipp`tk'
+ local sumvipp`tj'=`sumvipp`tj''+`diff'
+ local sumvipp`tk'=`sumvipp`tk''+`diff'
+ if `diff'>`maxvipp`tj'' {
+ local maxvipp`tj'=`diff'
+ }
+ if `diff'>`maxvipp`tk'' {
+ local maxvipp`tk'=`diff'
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+*/
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ drop _all
+ qui svmat `matpmm',names(col)
+ qui recode `list' (-1=.)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ local list2
+ local listw2
+ gsort -p1
+ qui set obs `=`scoremax'+1'
+ forvalues i=1/`scoremax' {
+ local w:word `i' of `list'
+ qui replace `item'="`w'" if `id'==`i'
+ qui replace `w'=. if `id'==`i'
+ local connect "`connect' l"
+ local z=regexr("`w'","_",">=")
+ label define `monlabel' `i' "`z'", add
+ label variable `w' "`z'"
+ qui su p1 if `id'==`i'
+ local prop=r(mean)
+ qui replace `w'=`prop' in `=`scoremax'+1'
+ }
+ forvalues i=1/`scoremax' {
+ local v=`item'[`i']
+ local list2 `list2' `v'
+ local v=`id'[`i']
+ local listw2 `listw2' `v'
+ }
+ label define `monlabel' `=`scoremax'+1' "Prop",add
+ order `list2'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ if "`html'"!="" {
+ qui local saving "saving(`c(tmpdir)'/`html'_pmm,replace) nodraw"
+ *qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *graph use `c(tmpdir)'/`html'_pmm.gph
+ *qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ *else {
+ qui twoway conn `list' `id2' in 1/`scoremax',`htmlregion' connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace) `saving'
+ *}
+ if "`html'"!="" {
+ qui graph use `c(tmpdir)'/`html'_pmm.gph
+ qui graph export `c(tmpdir)'/`html'_pmm.eps, replace
+ }
+ }
+ format `list' %5.3f
+ label variable `id' "Item"
+ rename `id' Item
+ label value Item `monlabel'
+ qui replace Item=`=`scoremax'+1' in `=`scoremax'+1'
+ tempname matmm
+ matrix define `matmm'=J(`scoremax',`scoremax',0)
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ local t:word `j' of `list2'
+ matrix `matmm'[`i',`j']=`t'[`i']
+ }
+ }
+ matrix colnames `matmm'=`list2'
+ matrix rownames `matmm'=`list2'
+ if "`pmm'"!="" {
+
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ matrix list `matmm',format(%5.3f) nohalf noheader
+
+ if "`html'" != "" {
+ //matrixlisthtml `matmm' "%5.3f"
+
+ if ("`graph'" != "") {
+ di ""
+ }
+ }
+ }
+ label drop `monlabel'
+ qui use "`temporaryfile'",clear
+ if "`nipmatrix'"!="" {
+ forvalues i=1/`scoremax' {
+ forvalues j=1/`scoremax' {
+ forvalues k=`=`j'+1'/`scoremax' {
+*di "`listv' `listw2'"
+ local ti:word `i' of `listitem'
+ local tj:word `j' of `listitem'
+ local tk:word `k' of `listitem'
+ if `tj'!=`tk'&`tj'!=`ti'&`ti'!=`tk'/*`matmm'[`k',`i']!=.&`matmm'[`j',`i']!=.*/ {
+ local ++nbacmm`ti'
+ *local ++nbacmm`tk'
+ local diff=`matmm'[`k',`i']-`matmm'[`j',`i']
+ if `diff'>`minvi'&`diff'!=. {
+ local ++nbvimm`tj'
+ local ++nbvimm`tk'
+ local sumvimm`tj'=`sumvimm`tj''+`diff'
+ local sumvimm`tk'=`sumvimm`tk''+`diff'
+ if `diff'>`maxvimm`tj'' {
+ local maxvimm`tj'=`diff'
+ }
+ if `diff'>`maxvimm`tk'' {
+ local maxvimm`tk'=`diff'
+ }
+ local wi:word `i' of `listw2'
+ local wj:word `j' of `listw2'
+ local wk:word `k' of `listw2'
+ local li:word `wi' of `listv'
+ local lj:word `wj' of `listv'
+ local lk:word `wk' of `listv'
+ local ii:word `wi' of `list'
+ local ij:word `wj' of `list'
+ local ik:word `wk' of `list'
+
+ qui count if `li'==0&`lj'==1&`lk'==0
+ local a=r(N)
+ qui count if `li'==0&`lj'==0&`lk'==1
+ local b=r(N)
+ local n=`a'+`b'
+ local k=`b'
+ local b=((2*`k'+1-`n')^2-10*`n')/(12*`n')
+ local z=sqrt(2*`k'+2+`b')-sqrt(2*`n'-2*`k'+`b')
+ *di "-- `li', `lj', `lk', `ii', `ij', `ik' : `n', `k', `z'"
+
+ if abs(`z')>`=invnorm(1-`siglevel')'&`z'!=. {
+ local ++nbsigzmm`tj'
+ if abs(`z')>`zmaxmm`tj'' {
+ local zmaxmm`tj'=abs(`z')
+ }
+ local ++nbsigzmm`tk'
+ if abs(`z')>`zmaxmm`tk'' {
+ local zmaxmm`tk'=abs(`z')
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if "`nipmatrix'" !="" {
+ *set trace on
+
+ di
+ di in green _col(10) "Summary per item for check of non-Intersection via Pmatrix"
+ di in green _col(10) "Minvi=" in ye %5.3f `minvi' _col(25) /*in green "Minsize=" in ye %5.0f `minsize' _col(40)*/ in green "Alpha=" in ye %5.3f `siglevel'
+ di
+ di in green "Items" _col(20) "#ac" _col(28) "#vi" _col(32) "#vi/#ac" _col(44) "maxvi" _col(56) "sum" _col(62) "sum/#ac" _col(75) "zmax" _col(84) "#zsig" _col(93) "Crit"
+ di in green "{hline 97}"
+
+
+ forvalues i=1/`nbitems' {
+ local nbac`i'=`nbacpp`i''+`nbacmm`i''
+ local nbvi`i'=`nbvipp`i''+`nbvimm`i''
+ local maxvi`i'=max(`maxvipp`i'',`maxvimm`i'')
+ local sumvi`i'=`sumvipp`i''+`sumvimm`i''
+ local zmaxvi`i'=max(`zmaxpp`i'',`zmaxmm`i'')
+
+ local nbzsig`i'=`nbsigzpp`i''+`nbsigzmm`i''
+ local zmax`i'=0
+ *local nbsigz`i'=0
+ local t=`loevHj'[1,`i']
+* di "local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmax`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i'' "
+ local crit`i'=50*(.3-`t')+sqrt(`nbvi`i'')+100*`nbvi`i''/`nbac`i''+100*`maxvi`i''+10*sqrt(`sumvi`i'')+1000*`sumvi`i''/`nbac`i''+5*`zmaxvi`i''+10*sqrt(`nbzsig`i'')+100*`nbzsig`i''/`nbac`i''
+
+ *di `nbac`i'' " " `nbvi`i'' " " `sumvi`i''
+ if `nbvi`i''!=0 {
+
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(33) %6.4f `=`nbvi`i''/`nbac`i''' _col(43) %6.4f `maxvi`i'' _col(53) %6.4f `sumvi`i'' _col(63) %6.4f `=`sumvi`i''/`nbac`i''' _col(73) %6.4f `zmaxvi`i'' _col(81) %8.0f `nbzsig`i'' _col(93) %4.0f `crit`i''
+
+ }
+ else {
+
+ di in green "``i''" in yellow _col(15) %8.0f `nbac`i'' _col(23) %8.0f `nbvi`i'' _col(93) %4.0f `crit`i''
+
+ }
+ }
+
+}
+
+/*if "`pmm'"!="" {
+ drop _all
+ matrix `P00g'=`P00',`P1''
+ matrix colnames `P00g'=`varlist' `p1'
+ matrix rownames `P00g'=`varlist'
+ qui svmat `P00g' , names(col)
+ qui gen `id'=_n
+ qui gen str9 `item'=""
+ local connect "l"
+ forvalues i=1/`nbitems' {
+ qui replace `item'="``i''" if `id'==`i'
+ qui replace ``i''=. if `id'==`i'
+ local connect "`connect' l"
+ label define `monlabel' `i' "``i''", add
+ }
+ sort `p1'
+ qui gen `id2'=_n
+ label value `id2' `monlabel'
+ label variable `id2' " "
+ if "`graph'"!="" {
+ twoway connected `varlist' `id2',connect(`connect') ytitle("") title("P-- diagnostics") name(pmm,replace)
+ }
+ format `varlist' %5.3f
+ label variable `id' "Item"
+ label value `id' `monlabel'
+ di
+ di in green _col(10) "P-- values per items pair (The values should be decreasing in each column)"
+ list `id' `varlist' , table compress separator(`nbitems') noobs divider
+ label drop `monlabel'
+}
+
+
+
+if "`pairwise'"=="" {
+ restore, not
+}*/
+
+
+*di "listw2:`listw2'"
+*di "listv:`listv'"
+*di "list:`list'"
+*di "listi:`listi'"
+*di "listm:`listm'"
+*di "listitem:`listitem'"
+
+
+qui use "`loevHfile'",clear
+*set trace on
+if "`generror'"!="" {
+ if "`replace'"!="" {
+ capture drop `generror'_0
+ capture drop `generror'_H
+ capture drop `generror'_max
+ capture drop `generror'_GPN
+ capture drop `generror'
+ }
+ qui gen `generror'=0
+ *forvalues i=1/`nbitems' {
+ * qui gen `generror'_``i''=0
+ *}
+ qui gen `generror'_0=`eGutt0'/`nb'
+ local nbsteps:word count `listitem'
+ if "`pairwise'"=="" {
+ forvalues i=1/`nbitems' {
+ qui replace `generror'=. if ``i''==.
+ qui replace `generror'_0=. if ``i''==.
+ }
+ }
+ forvalues i=0/`nbsteps' {
+ //di "qui guttmax `listitem', score(`i')"
+ qui guttmax `listitem', score(`i')
+ local errmax`i'=r(maxegutt)
+ }
+* matrix list `P0'
+ forvalues i=1/`nbsteps' {
+ forvalues j=`=`i'+1'/`nbsteps' {
+ local w2i:word `i' of `listw2'
+ local w2j:word `j' of `listw2'
+ local itemi:word `w2i' of `listi'
+ local modai:word `w2i' of `listm'
+ local itemj:word `w2j' of `listi'
+ local modaj:word `w2j' of `listm'
+ qui replace `generror'=`generror'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemi'=`generror'_`itemi'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+ *qui replace `generror'_`itemj'=`generror'_`itemj'+1 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.
+* qui replace `generror'=`generror'+.5 if `itemi'>=`modai'&`itemj'<`modaj'&`itemi'!=.&`itemj'!=.&`P1'[1,`i']==`P1'[1,`j']
+ *qui replace `generror'=`generror'+.5 if `P1'[1,`i']==`P1'[1,`j']&``i''==1&``j''==0
+ }
+ }
+* set trace on
+ tempvar flag
+ qui gen `flag'=0
+ qui replace `flag'=1 `if'
+ qui replace `generror'=. if `flag'==0
+ qui replace `generror'_0=. if `flag'==0
+ qui gen `generror'_H=1-`generror'/`generror'_0
+ tempvar score
+ qui genscore `varlist' `if',score(`score')
+ qui gen `generror'_max=.
+ forvalues i=1/`nbsteps' {
+ qui replace `generror'_max=`errmax`i'' if `score'==`i'
+ }
+ qui gen `generror'_GPN=`generror'/`generror'_max
+ label variable `generror' "Number of Guttman errors per individual"
+ label variable `generror'_H "H indice per individual"
+ if "`graph2'"!="" {
+ qui histogram `generror',discrete width(0.5) freq name(errors,replace)
+ qui histogram `generror'_H,discrete freq name(H,replace)
+ }
+ if "`html'" != "" {
+ di
+ qui local saving "saving(`c(tmpdir)'/`html'_errors,replace) nodraw"
+ qui histogram `generror',discrete width(0.5) freq name(errors,replace) title("Number of Guttman errors per individual") `saving'
+ qui graph use `c(tmpdir)'/`html'_errors.gph
+ qui graph export `c(tmpdir)'/`html'_errors.eps, replace
+ di ""
+ }
+
+ qui su `generror' ,det
+ local meane=r(mean)
+ local mede=r(p50)
+ local mine=r(min)
+ local maxe=r(max)
+ qui su `generror'_GPN ,det
+ local meanGPN=r(mean)
+ local medGPN=r(p50)
+ local minGPN=r(min)
+ local maxGPN=r(max)
+ di
+ di in green "Number of Guttman errors by individual" _col(50) in green "Normalized number of Guttamn errors by individual"
+ di in green " Mean number: " in ye %7.2f `meane' _col(50) in green " Mean number: " in ye %7.2f `meanGPN'
+ di in green " Median number: " in ye %7.2f `mede' _col(50) in green " Median number: " in ye %7.2f `medGPN'
+ di in green " Minimal number: " in ye %7.2f `mine' _col(50) in green " Minimal number: " in ye %7.2f `minGPN'
+ di in green " Maximal number: " in ye %7.2f `maxe' _col(50) in green " Maximal number: " in ye %7.2f `maxGPN'
+ di in green "Expected Guttman errors: " in ye %7.2f `=`eGutt0'/`nb''
+ qui count if `generror'_H<0
+ di in green " Rate of Hn<0: " in ye %7.2f `=r(N)/`nb'*100' "%"
+
+}
+
+matrix colnames `loevHj'=`varlist'
+matrix rownames `loevHj'=Hj
+return matrix loevHj `loevHj'
+
+matrix colnames `loevHjk'=`varlist'
+matrix rownames `loevHjk'=`varlist'
+return matrix loevHjk `loevHjk'
+
+matrix colnames `eGuttj'=`varlist'
+matrix rownames `eGuttj'=ej
+return matrix eGuttj `eGuttj'
+
+matrix colnames `eGuttjk'=`varlist'
+matrix rownames `eGuttjk'=`varlist'
+return matrix eGuttjk `eGuttjk'
+
+matrix colnames `eGuttj0'=`varlist'
+matrix rownames `eGuttj0'=ejk
+return matrix eGuttj0 `eGuttj0'
+
+matrix colnames `eGuttjk0'=`varlist'
+matrix rownames `eGuttjk0'=`varlist'
+return matrix eGuttjk0 `eGuttjk0'
+
+return scalar loevH=`loevH'
+return scalar eGutt =`eGutt'
+return scalar eGutt0 =`eGutt0'
+
+if `modamax'==1 {
+ matrix colnames `P11'=`varlist'
+ matrix rownames `P11'=`varlist'
+ return matrix P11 `P11'
+}
+
+matrix colnames `P00'=`varlist'
+matrix rownames `P00'=`varlist'
+return matrix P00 `P00'
+
+if "`ppp'"!=""|"`nipmatrix'"!="" {
+ return matrix ppp=`matpp'
+}
+if "`pmm'"!=""|"`nipmatrix'"!="" {
+ return matrix pmm=`matmm'
+}
+
+matrix colnames `zHj'=`varlist'
+matrix rownames `zHj'=zHj
+return matrix zHj `zHj'
+
+matrix colnames `pvalHj'=`varlist'
+matrix rownames `pvalHj'=pval
+return matrix pvalHj `pvalHj'
+
+return scalar zH=`zH'
+return scalar pvalH=`pvalH'
+if "`pair'"!="" {
+ matrix colnames `zHjk'=`varlist'
+ matrix rownames `zHjk'=`varlist'
+ return matrix zHjk `zHjk'
+
+ matrix colnames `pvalHjk'=`varlist'
+ matrix rownames `pvalHjk'=`varlist'
+ return matrix pvalHjk `pvalHjk'
+}
+
+matrix colnames `Obs'=`varlist'
+matrix rownames `Obs'=`varlist'
+return matrix Obs `Obs'
+
+
+capture restore, not
+
+end
+
diff --git a/Modules/ado/personal/l/lstrfun.ado b/Modules/ado/personal/l/lstrfun.ado
new file mode 100644
index 0000000..14a9ccd
--- /dev/null
+++ b/Modules/ado/personal/l/lstrfun.ado
@@ -0,0 +1,368 @@
+*! lstrfun Version 1.2 dan_blanchette@unc.edu 09Aug2011
+*! the carolina population center, unc-ch
+* -Nick Cox let me know that the regular expersion functions were available in Stata 9.2
+* but were just not documented
+* lstrfun Version 1.1 dan_blanchette@unc.edu 22Jul2011
+** -it now can run regexr(), regexm() and regexs()
+** lstrfun Version 1.0 dan_blanchette@unc.edu 09Aug2010
+** Center for Entrepreneurship and Innovation Duke University's Fuqua School of Business
+* modify long local macros with mata string functions
+
+program define lstrfun
+version 9.2
+
+syntax [namelist(local)] [, lower(string asis) upper(string asis) proper(string asis) ///
+ ltrim(string asis) itrim(string asis) rtrim(string asis) trim(string asis) ///
+ substr(string asis) subinstr(string asis) subinword(string asis) ///
+ reverse(string asis) strdup(string asis) soundex(string asis) soundex_nara(string asis) ///
+ strlen(string asis) strpos(string asis) _substr(string asis) indexnot(string asis) ///
+ strmatch(string asis) regexr(string asis) regexm(string asis) regexms(string asis) ///
+ ]
+
+if missing(`"`namelist'"') {
+ display as error "need to specify a local macro variable name to modify or create"
+ exit 198
+}
+local n_locals : word count `namelist'
+if `n_locals' > 1 {
+ display as error "only one local macro variable name can be submitted"
+ exit 198
+}
+
+// local m1= !missing(`"`macval(lower)'"'
+// says "too few quotes" when a fairly long macro submitted but only inside a program
+// using short macro names and no spaces to make it even shoerter
+local m1=`"`macval(lower)'"'!=""
+local m2=`"`macval(proper)'"'!=""
+local m3=`"`macval(upper)'"'!=""
+local m4=`"`macval(ltrim)'"'!=""
+local m5=`"`macval(itrim)'"'!=""
+local m6=`"`macval(rtrim)'"'!=""
+local m7=`"`macval(trim)'"'!=""
+local m8=`"`macval(substr)'"'!=""
+local m9=`"`macval(subinstr)'"'!=""
+local m10=`"`macval(subinword)'"'!=""
+local m11=`"`macval(strdup)'"'!=""
+local m12=`"`macval(reverse)'"'!=""
+local m13=`"`macval(soundex)'"'!=""
+local m14=`"`macval(soundex_nara)'"'!=""
+local m15=`"`macval(strlen)'"'!=""
+local m16=`"`macval(strpos)'"'!=""
+local m17=`"`macval(_substr)'"'!=""
+local m18=`"`macval(indexnot)'"'!=""
+local m19=`"`macval(strmatch)'"'!=""
+local m20=`"`macval(regexr)'"'!=""
+local m21=`"`macval(regexm)'"'!=""
+local m22=`"`macval(regexms)'"'!=""
+
+
+if `m1' ///
+ + `m2' ///
+ + `m3' ///
+ + `m4' ///
+ + `m5' ///
+ + `m6' ///
+ + `m7' ///
+ + `m8' ///
+ + `m9' ///
+ + `m10' ///
+ + `m11' ///
+ + `m12' ///
+ + `m13' ///
+ + `m14' ///
+ + `m15' ///
+ + `m16' ///
+ + `m17' ///
+ + `m18' ///
+ + `m19' ///
+ + `m20' ///
+ + `m21' > 1 {
+ display as error "you can only specify 1 option in {helpb lstrfun:lstrfun}"
+ exit 198
+ }
+
+if `m1' == 1 {
+ mata: long_lower(`macval(lower)')
+ c_local `namelist' `"`macval(lower)'"'
+}
+else if `m2' == 1 {
+ mata: long_proper(`macval(proper)')
+ c_local `namelist' `"`macval(proper)'"'
+}
+else if `m3' == 1 {
+ mata: long_upper(`macval(upper)')
+ c_local `namelist' `"`macval(upper)'"'
+}
+else if `m4' == 1 {
+ mata: long_ltrim(`macval(ltrim)')
+ c_local `namelist' `"`macval(ltrim)'"'
+}
+else if `m5' == 1 {
+ mata: long_itrim(`macval(itrim)')
+ c_local `namelist' `"`macval(itrim)'"'
+}
+else if `m6' == 1 {
+ mata: long_rtrim(`macval(rtrim)')
+ c_local `namelist' `"`macval(rtrim)'"'
+}
+else if `m7' == 1 {
+ mata: long_trim(`macval(trim)')
+ c_local `namelist' `"`macval(trim)'"'
+}
+else if `m8' == 1 {
+ mata: long_substr(`macval(substr)')
+ c_local `namelist' `"`macval(substr)'"'
+}
+else if `m9' == 1 {
+ mata: long_subinstr(`macval(subinstr)')
+ c_local `namelist' `"`macval(subinstr)'"'
+}
+else if `m10' == 1 {
+ mata: long_subinword(`macval(subinword)')
+ c_local `namelist' `"`macval(subinword)'"'
+}
+else if `m11' == 1 {
+ mata: long_strdup(`macval(strdup)')
+ local len_strdup : length local strdup
+ if `len_strdup' < `len_m_var' {
+ local clen_m_var= string(`len_m_var',"%11.0gc")
+ if c(SE) & c(maxvar) < 32767 & `len_m_var' <= 1081511 {
+ display as error "{cmd:strdup()} generated a string that has `clen_m_var' characters which is more than Stata can handle" ///
+ " when {helpb maxvar:maxvar} is set to `c(maxvar)'."
+ display as error "Increase your {helpb maxvar:maxvar} setting higher and try again."
+ exit 149
+ }
+ else {
+ display as error "{cmd:strdup()} generated a string that has `clen_m_var' characters (which is more than Stata can handle)"
+ exit 149
+ }
+ }
+ c_local `namelist' `"`macval(strdup)'"'
+}
+else if `m12' == 1 {
+ mata: long_reverse(`macval(reverse)')
+ c_local `namelist' `"`macval(reverse)'"'
+}
+else if `m13' == 1 {
+ mata: long_soundex(`macval(soundex)')
+ c_local `namelist' `"`macval(soundex)'"'
+}
+else if `m14' == 1 {
+ mata: long_soundex_nara(`macval(soundex_nara)')
+ c_local `namelist' `"`macval(soundex_nara)'"'
+}
+else if `m15' == 1 {
+ mata: long_strlen(`macval(strlen)')
+ c_local `namelist' `"`macval(strlen)'"'
+}
+else if `m16' == 1 {
+ mata: long_strpos(`macval(strpos)')
+ c_local `namelist' `"`macval(strpos)'"'
+}
+else if `m17' == 1 {
+ mata: long__substr(`macval(_substr)')
+ c_local `namelist' `"`macval(_substr)'"'
+}
+else if `m18' == 1 {
+ mata: long_indexnot(`macval(indexnot)')
+ c_local `namelist' `"`macval(indexnot)'"'
+}
+else if `m19' == 1 {
+ mata: long_strmatch(`macval(strmatch)')
+ c_local `namelist' `"`macval(strmatch)'"'
+}
+else if `m20' == 1 {
+ mata: long_regexr(`macval(regexr)')
+ c_local `namelist' `"`macval(regexr)'"'
+}
+else if `m21' == 1 {
+ mata: long_regexm(`macval(regexm)')
+ c_local `namelist' `"`macval(regexm)'"'
+}
+else if `m22' == 1 {
+ mata: long_regexms(`macval(regexms)')
+ c_local `namelist' `"`macval(regexms)'"'
+}
+else {
+ display as error "need to specify an option in {helpb lstrfun:lstrfun}"
+ exit 198
+}
+
+
+end
+
+
+mata:
+void long_lower(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strlower(lstring)
+ st_local("lower",m_var)
+}
+
+void long_proper(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strproper(lstring)
+ st_local("proper",m_var)
+}
+
+void long_upper(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strupper(lstring)
+ st_local("upper",m_var)
+}
+
+void long_ltrim(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strltrim(lstring)
+ st_local("ltrim",m_var)
+}
+
+void long_itrim(string scalar lstring)
+{
+ string scalar m_var
+ m_var= stritrim(lstring)
+ st_local("itrim",m_var)
+}
+
+void long_rtrim(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strrtrim(lstring)
+ st_local("rtrim",m_var)
+}
+
+void long_trim(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strtrim(lstring)
+ st_local("trim",m_var)
+}
+
+void long_substr(string scalar lstring, real scalar start, real scalar length)
+{
+ string scalar m_var
+ m_var= substr(lstring,start,length)
+ st_local("substr",m_var)
+}
+
+void long_subinstr(string scalar lstring, string scalar old, string scalar snew, real scalar cnt)
+{
+ string scalar m_var
+ m_var= subinstr(lstring,old,snew,cnt)
+ st_local("subinstr",m_var)
+}
+
+void long_subinword(string scalar lstring, string scalar old, string scalar snew, real scalar cnt)
+{
+ string scalar m_var
+ m_var= subinword(lstring,old,snew,cnt)
+ st_local("subinword",m_var)
+}
+
+void long_strdup(string scalar lstring, real scalar n)
+{
+ string scalar m_var
+ m_var= n*lstring
+ real scalar len_lstring
+ len_lstring= n * strlen(lstring)
+ real scalar len_m_var
+ len_m_var= strlen(m_var)
+ string scalar slen_m_var
+ slen_m_var= strofreal(len_m_var)
+ st_local("len_m_var",slen_m_var)
+ st_local("strdup",m_var)
+}
+
+void long_reverse(string scalar lstring)
+{
+ string scalar m_var
+ m_var= strreverse(lstring)
+ st_local("reverse",m_var)
+}
+
+void long_soundex(string scalar lstring)
+{
+ string scalar m_var
+ m_var= soundex(lstring)
+ st_local("soundex",m_var)
+}
+
+void long_soundex_nara(string scalar lstring)
+{
+ string scalar m_var
+ m_var= soundex_nara(lstring)
+ st_local("soundex_nara",m_var)
+}
+
+void long_strlen(string scalar lstring)
+{
+ string scalar m_var
+ real scalar nm_var
+ nm_var= strlen(lstring)
+ m_var= strofreal(nm_var)
+ st_local("strlen",m_var)
+}
+
+void long_strpos(string scalar lstring, string scalar needle)
+{
+ string scalar m_var
+ real scalar nm_var
+ nm_var= strpos(lstring,needle)
+ m_var= strofreal(nm_var)
+ st_local("strpos",m_var)
+}
+
+void long__substr(string scalar lstring, string scalar tosub, real scalar pos)
+{
+ _substr(lstring, tosub, pos)
+ st_local("_substr",lstring)
+}
+
+void long_indexnot(string scalar lstring, string scalar needle)
+{
+ string scalar m_var
+ real scalar nm_var
+ nm_var= indexnot(lstring,needle)
+ m_var= strofreal(nm_var)
+ st_local("indexnot",m_var)
+}
+
+void long_strmatch(string scalar lstring, string scalar pattern)
+{
+ string scalar m_var
+ real scalar nm_var
+ nm_var= strmatch(lstring,pattern)
+ m_var= strofreal(nm_var)
+ st_local("strmatch",m_var)
+}
+
+void long_regexr(string scalar lstring, string scalar pattern, string scalar rep)
+{
+ string scalar m_var
+ m_var= regexr(lstring,pattern,rep)
+ st_local("regexr",m_var)
+}
+
+void long_regexm(string scalar lstring, string scalar pattern)
+{
+ string scalar m_var
+ real scalar nm_var
+ nm_var= regexm(lstring,pattern)
+ m_var= strofreal(nm_var)
+ st_local("regexm",m_var)
+}
+
+void long_regexms(string scalar lstring, string scalar pattern, real scalar ss)
+{
+ string scalar m_var
+ if (regexm(lstring,pattern)) {
+ m_var= regexs(ss)
+ }
+ st_local("regexms",m_var)
+}
+
+end
diff --git a/Modules/ado/personal/m/Multirsoort_indicefit.ado b/Modules/ado/personal/m/Multirsoort_indicefit.ado
new file mode 100644
index 0000000..6bf538b
--- /dev/null
+++ b/Modules/ado/personal/m/Multirsoort_indicefit.ado
@@ -0,0 +1,1530 @@
+*! version 1.4 29January2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+* Version 1.1 (2013-06-03): Jean-Benoit Hardouin /*some improvements*/
+* Version 1.2 (2013-06-03): Jean-Benoit Hardouin /*model1 model2 model3 and covariances options*/
+* Version 1.3 (2013-06-03): Jean-Benoit Hardouin /**/
+* Version 1.4 (2014-01-29): Jean-Benoit Hardouin /*add an iterate option on model 1*/
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013-2014 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
+************************************************************************************************************/
+
+
+/***************************************************************************
+MODIFICATIONS ALICE
+- précedemment, boucles pour les différents cas THA, qui permettent le test général, la hiérarchie et l'ajustement.
+- avant l'été 2015, modification pour l'amélioration du fit des modèles 1 et 4
+- (22/09/2015): modification dans l'ajout pour l'amélioration du fit avec le fichier déposé en temporaire
+-(12/2015): modification, dans les cas sans hierarchie, programme recodé pour la boucle typeRS=2 car pb dans les contraintes
+-(01/2016) : modification de l'étape 4, lorsque la procédure entre dans la boucle pour les covariances, M4 modifié (car il était équivalent au M1 donc faux) + réinitialisation de arret_covfit avant modele 4
+
+*****************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define Multirsoort_indicefit,rclass
+
+syntax varlist(min=2 numeric) [if] [in] [,METHod(string) nocov12 UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch html(string) model1 model2 model4 COVariances(string) MATrixrs(string) Cas(string)]
+tempfile saveMultirsoort_indicefit
+qui save `saveMultirsoort_indicefit',replace
+preserve
+
+if "`matrixrs'"!="" {
+ if "`uniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:uniformrecalibration} options in the same time"
+ error
+ }
+ if "`nonuniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:nonuniformrecalibration} options in the same time"
+ error
+ }
+ if "`reprioritization'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:reprioritization} options in the same time"
+ error
+ }
+}
+
+
+if "`html'" != "" {
+ di ""
+}
+
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+if "`html'"== "" {
+ di _col(20) "{hline 30}"
+ di _col(20) in gr "Time 1" _col(40) "Time 2"
+ di _col(20) "{hline 30}"
+ forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+ }
+ di _col(20) "{hline 30}"
+}
+else {
+ di "
"
+ di ""
+ di "Time 1 | Time2 |
"
+ di ""
+ forvalues i=1/`nbitems' {
+ di "``i'' | ``=`i'+`nbitems''' |
"
+ }
+ di "
"
+}
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+if "`model1'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+local cov12b
+forvalues i=1/`nbitems' {
+ local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
+}
+if "`cov12'"!="" {
+ local cov12b
+}
+
+/*if ("`cas'"=="cas3" | "`cas'"=="cas4" | "`cas'"=="cas5" | "`cas'"=="cas6" ) {*/
+
+`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covariances') iterate(100)
+tempname b
+matrix `b'=r(table)
+
+estat gof
+local rmsea1=r(rmsea)
+
+
+local covfit
+local r =999
+local arret_covfit=999
+
+while `rmsea1' >0.08 {
+
+di"`rmsea1'"
+tempfile data
+save `data', replace
+di "`data'"
+/*on récupère les indices de modifs*/
+estat mindice
+matrix indice = r(mindices)
+clear
+/* on ajoute dans une colonne le nom des items concernés*/
+svmat2 indice , r(nomcol) full
+
+/*on controle l'ajout de covariances uniquement sur un même temps*/
+gen tmp=substr(nomcol,1,3)
+drop if tmp!="cov"
+
+gen tmp1=substr(nomcol,11,1)
+gen tmp2=substr(nomcol,20,1)
+drop if tmp1 != tmp2
+
+matrix list indice
+
+/*On vérifie qu'il reste des lignes de covariances à ajouter*/
+local vide = indice1[1]
+if "`vide'" == "." {
+local covfit= "`covfit'"
+local arret_covfit=1
+local rmsea1=0
+use "`data'",clear
+
+}
+else {
+/*on trie par ordre croissant pour ajouter les covariances les plus influentes*/
+local arret_covfit=0
+gsort - indice1
+
+local tmp3=nomcol[1]
+lstrfun e, subinstr("`tmp3'","cov(","",.)
+lstrfun e, subinstr("`e'",")","",.)
+lstrfun e, subinstr("`e'",":_cons","",.)
+lstrfun e, subinstr("`e'",",","*",.)
+
+
+local covfit= "`covfit' `e'"
+use "`data'", clear
+
+
+`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covariances' `covfit') iterate(100)
+tempname b
+matrix `b'=r(table)
+
+estat gof
+local rmsea1=r(rmsea)
+
+di "`covfit'"
+
+local tmp4="`covfit'"
+lstrfun r, subinstr("`tmp4'","e.itemA","0",.)
+lstrfun r, subinstr("`r'","e.itemB","1",.)
+lstrfun r, subinstr("`r'","*","",.)
+lstrfun r, subinstr("`r'"," ","",.)
+}
+}
+
+
+/*return list
+ereturn list*/
+
+estat gof
+qui estat gof, stat(all)
+tempname iter1 V
+local iter1=e(ic)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local pclose1= r(pclose)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+local bic1=r(bic)
+local convergence1=e(converged)
+local cov_fit1="`r'"
+local arret_covfit1=`arret_covfit'
+
+
+return matrix b1=`b'
+return scalar iter1=`iter1'
+return scalar tli1=`tli1'
+return scalar cfi1=`cfi1'
+return scalar srmr1=`srmr1'
+return scalar rmsea1=`rmsea1'
+return scalar ubrmsea1=`ubrmsea1'
+return scalar lbrmsea1=`lbrmsea1'
+return scalar pclose1=`pclose1'
+return scalar chi21=`chi21'
+return scalar df1=`df1'
+return scalar dfc1=`dfc1'
+return scalar p1=`p1'
+return scalar bic1=`bic1'
+return scalar convergence1=`convergence1'
+return local cov_fit1 = "`cov_fit1'"
+return scalar arret_covfit1 =`arret_covfit1'
+/*}*/
+
+
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+if "`model2'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+
+`qui' sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+di "`sem'"
+di"`var'"
+tempname b V
+matrix `b'=r(table)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+
+
+estat gof
+qui estat gof, stat(all)
+local iter2=e(ic)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local pclose2=r(pclose)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+local convergence2=e(converged)
+
+return matrix b2=`b'
+return scalar iter2=`iter2'
+return scalar tli2=`tli2'
+return scalar cfi2=`cfi2'
+return scalar srmr2=`srmr2'
+return scalar rmsea2=`rmsea2'
+return scalar ubrmsea2=`ubrmsea2'
+return scalar lbrmsea2=`lbrmsea2'
+return scalar pclose2=`pclose2'
+return scalar chi22=`chi22'
+return scalar df2=`df2'
+return scalar dfc2=`dfc2'
+return scalar p2=`p2'
+return scalar bic2=`bic2'
+return scalar convergence2=`convergence2'
+return scalar truechange2=`truechange2'
+return scalar setruechange2=`=sqrt(`Vtruechange2')'
+return scalar ztruechange2=`=`truechange2'/sqrt(`Vtruechange2')'
+return scalar ptruechange2=`=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ *di " | | Test of global Response-Shift | Comparison with model 1 |
"
+ di "Models | Chi-square | df | p-value | BIC |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %6.4f `p1' " | " %7.2f `bic1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %6.4f `p2' " | " %7.2f `bic2' " |
"
+ di "
"
+}
+else {
+ di "{hline 51}"
+ di in gr /*_col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"*/
+ di in gr "Models" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 51}"
+ di in gr "Model 1" _col(20) %8.2f in ye `chi21' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
+ di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
+ di "{hline 51}"
+}
+
+
+if "`cas'"=="cas3" | "`cas'"=="cas4" | "`cas'"=="cas5" | "`cas'"=="cas6"{
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+if (`p21'>0.05) {
+local search="nosearch"
+}
+
+return scalar pvaleurM1M2=`p21'
+
+}
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+/**************************************************************************************************************
+HIERARCHIE
+***************************************************************************************************************/
+if "`cas'"=="cas1" | "`cas'"=="cas2" | "`cas'"=="cas3" | "`cas'"=="cas4" {
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+forvalues j=1/`nbitems' {
+ local unav_nonunif`j'=.
+}
+
+if "`matrixrs'"=="" {
+ forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `reprioritization'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `reprioritization'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+ }
+}
+else {
+ matrix `RS'=`matrixrs'
+}
+*matrix list `RS'
+
+if "`search'"=="" {
+
+ if "`html'"=="" {
+ di
+ di "{hline 88}"
+ di in green _col(40) "Model 3"
+ di "{hline 88}"
+ di
+ di in white _col(10) "Non uniform Recalibration"
+ }
+ else {
+ di "
Model 3
"
+ di ""
+ di "Non uniform Recalibration"
+ }
+ local continue=1
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ }
+ local prec_chi2=`chi22'
+ local testNU_varchi2=0
+ local testNU_p=1
+
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ /*di "`covfit'"*/
+ /* di "`sem'"
+ di"`var'"*/
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+ di "`sem'"
+ di"`var'"
+ qui estat gof
+
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+
+ if "`cas'"=="cas4" | "`cas'"=="cas2" {
+ local nbtest=1-(0.05/(`nbitems'-`cpt'))
+ }
+ if "`cas'"=="cas1" | "`cas'"=="cas3" {
+ local nbtest=0.95
+ }
+
+
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ local unav_nonunif`j'=0
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ local unav_nonunif`j'=1
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ return scalar unav_nonunif`j'= `unav_nonunif`j''
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Uniform recalibration
+ ***************************************************************************************************************/
+forvalues j=1/`nbitems' {
+ local unav_unif`j'=.
+}
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Uniform Recalibration"
+ }
+ else {
+ di ""
+ di "Uniform Recalibration"
+ }
+ local continue=1
+ local var
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+
+ /* di "`sem'"
+ di"`var'"*/
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+ di "`sem'"
+ di"`var'"
+ qui estat gof
+
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+
+ if "`cas'"=="cas4" | "`cas'"=="cas2" {
+ local nbtest=1-(0.05/(`nbitems'-`cpt'))
+ }
+ if "`cas'"=="cas1" | "`cas'"=="cas3" {
+ local nbtest=0.95
+ }
+
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+
+ if ( `chi2encours'<`prec_chi2') {
+ local unav_unif`j'=0
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ local unav_unif`j'=1
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ return scalar unav_unif`j'= `unav_unif`j''
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Reprioritization
+ ***************************************************************************************************************/
+forvalues j=1/`nbitems' {
+ local unav_reprio`j'=.
+}
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Reprioritization"
+ }
+ else {
+ di ""
+ di "Reprioritization"
+ }
+
+ local continue=1
+ local var
+ local sem
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ di "`sem'"
+ di"`var'"
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+ di "`sem'"
+ di"`var'"
+ qui estat gof
+
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+
+ if "`cas'"=="cas4" | "`cas'"=="cas2" {
+ local nbtest=1-(0.05/(`nbitems'-`cpt'))
+ }
+ if "`cas'"=="cas1" | "`cas'"=="cas3" {
+ local nbtest=0.95
+ }
+
+
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ local unav_reprio`j'= 0
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ local unav_reprio`j'= 1
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ return scalar unav_reprio`j'= `unav_reprio`j''
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+
+
+}
+
+
+
+/**************************************************************************************************************
+PAS DE HIERARCHIE
+***************************************************************************************************************/
+
+if "`cas'"=="cas5" | "`cas'"=="cas6" | "`cas'"=="cas7" | "`cas'"=="cas8" {
+
+
+
+/**************************************************************************************************************
+Model 3 / Type of Response Shift
+***************************************************************************************************************/
+forvalues nbpass=0/63 {
+ forvalues j=1/`nbitems' {
+ forvalues typeRS=1/3{
+ local unav`=`nbpass'`j'`typeRS''=.
+ }
+ }
+}
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+if "`matrixrs'"=="" {
+ forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `reprioritization'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `reprioritization'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+ }
+}
+else {
+ matrix `RS'=`matrixrs'
+}
+*matrix list `RS'
+
+if "`search'"=="" {
+
+
+ if "`html'"=="" {
+ di
+ di "{hline 88}"
+ di in green _col(40) "Model 3"
+ di "{hline 88}"
+ di
+ di in white _col(10) "Type of response shift"
+ }
+ else {
+ di "
Model 3
"
+ di ""
+ di "Non uniform Recalibration"
+ }
+ local continue=1
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ }
+ local prec_chi2=`chi22'
+ local test_varchi2=0
+ local test_p=1
+
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+
+ local nbpass=0
+ local ajust=0
+ while (`continue') {
+
+ local cpt=0
+ local test_varchi2_temp=0
+ local test_p_temp=0
+ local test_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues typeRS=1/3{
+
+
+ forvalues v=1/`nbitems' {
+ if `RS'[`v',2]==1&`RS'[`v',1]==1 {
+ local ajust=1
+ }
+ }
+
+
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+
+ forvalues i=1/`nbitems' {
+
+ if `typeRS'==1 {
+ if `RS'[`i',2]==0 & `RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0 & `RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1 & `RS'[`i',3]==0{
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1 & `RS'[`i',3]==1{
+ local sem "`sem' `semrecUrep`i''"
+ }
+
+
+
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+
+ }
+
+ if `typeRS'==2 {
+ /*matrix list `RS'*/
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+
+ }
+
+
+ if `typeRS'==3 {
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+
+
+ }
+
+ }
+
+
+ /*set trace off*/
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+ di "`sem' "
+ di "`var' "
+ qui estat gof
+
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if "`cas'"=="cas6" | "`cas'"=="cas8" {
+ local nbtest=1-(0.05/(`nbitems'*3-(`=`cpt'+`nbpass'+`ajust'')))
+ }
+ if "`cas'"=="cas5" | "`cas'"=="cas7" {
+ local nbtest=0.95
+ }
+
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,`nbtest')&abs(`chi2encours'-`prec_chi2')>`test_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local test_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local test_p_temp =1-chi2(1,`test_varchi2_temp')
+ local test_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ local typeRS_encours=`typeRS'
+ }
+
+ if ( `chi2encours'<`prec_chi2') {
+ local unav`=`nbpass'`j'`typeRS''=0
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ local unav`=`nbpass'`j'`typeRS''=1
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ return scalar unav`=`nbpass'`j'`typeRS''= `unav`=`nbpass'`j'`typeRS'''
+
+ local ++cpt
+
+
+
+ }
+ }
+
+ }
+
+ if (`test_item_temp'!=0) {
+ if `typeRS_encours'==1 {
+ matrix `RS'[`test_item_temp',1]=1
+ }
+ if `typeRS_encours'==2 {
+ matrix `RS'[`test_item_temp',2]=1
+ }
+ if `typeRS_encours'==3 {
+ matrix `RS'[`test_item_temp',3]=1
+ }
+
+ /*matrix list `RS'*/
+ local ++df3
+ local test_varchi2=`test_varchi2_temp'
+ local test_p=`test_p_temp'
+ local test_item_temp=0
+ local prec_chi2=`tmp'
+
+
+ }
+ local ++nbpass
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+
+
+}
+
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+
+qui sem `sem',var(T1@1) var(T2@1) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances' `covfit')
+di "`sem'"
+di"`var'"
+tempname b V
+matrix `b'=r(table)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local iter3=e(ic)
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local pclose3=r(pclose)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+local bic3=r(bic)
+local convergence3= e(converged)
+
+
+return matrix b3=`b'
+return scalar iter3=`iter3'
+return scalar tli3=`tli3'
+return scalar cfi3=`cfi3'
+return scalar srmr3=`srmr3'
+return scalar rmsea3=`rmsea3'
+return scalar ubrmsea3=`ubrmsea3'
+return scalar lbrmsea3=`lbrmsea3'
+return scalar pclose3=`pclose3'
+return scalar chi23=`chi23'
+return scalar df3=`df3'
+return scalar dfc3=`dfc3'
+return scalar p3=`p3'
+return scalar bic3=`bic3'
+return scalar convergence3=`convergence3'
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+if "`html'"=="" {
+ di
+ di "{hline 74}"
+ di in gr _col(22) "Non uniform" _col(46) "Uniform"
+ di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(58) "Reprioritization"
+ di "{hline 74}"
+}
+else {
+ di ""
+ di ""
+ di "Items | Non-uniform Recalibration | Uniform Recalibration | Repriorisation |
"
+ di ""
+}
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ if "`html'"=="" {
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+ }
+ else {
+ di "``i'' | `recNU' | `recU' | `rep' |
"
+ }
+}
+if "`html'"=="" {
+ di "{hline 74}"
+}
+else {
+ di "
"
+}
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+if "`model4'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+local arret_covfit=999
+
+
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) cov(`cov12b' `covariances' `covfit') method(`method')
+di "`sem'"
+di"`var'"
+tempname b
+matrix `b'=r(table)
+
+estat gof
+local rmsea4=r(rmsea)
+
+*set trace on
+
+while `rmsea4' >0.08 {
+
+di"`rmsea4'"
+tempfile data
+save `data', replace
+/*on récupère les indices de modifs*/
+estat mindice
+matrix indice = r(mindices)
+clear
+/* on ajoute dans une colonne le nom des items concernés*/
+svmat2 indice , r(nomcol) full
+/*on controle l'ajout de covariances uniquement sur un même temps*/
+gen tmp=substr(nomcol,1,3)
+drop if tmp!="cov"
+
+gen tmp1=substr(nomcol,11,1)
+gen tmp2=substr(nomcol,20,1)
+drop if tmp1 != tmp2
+
+/*On vérifie qu'il reste des lignes de covariances à ajouter*/
+local vide = indice1[1]
+if "`vide'" == "." {
+local covfit= "`covfit'"
+local arret_covfit=1
+local rmsea4=0
+use "`data'", clear
+}
+else {
+/*on trie par ordre croissant pour ajouter les covariances les plus influentes*/
+local arret_covfit=0
+gsort - indice1
+
+local tmp3=nomcol[1]
+lstrfun e, subinstr("`tmp3'","cov(","",.)
+lstrfun e, subinstr("`e'",")","",.)
+lstrfun e, subinstr("`e'",":_cons","",.)
+lstrfun e, subinstr("`e'",",","*",.)
+
+/*matrix list indice */
+
+local covfit= "`covfit' `e'"
+di "`covfit'"
+
+use "`data'", clear
+di "`data'"
+
+
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) cov(`cov12b' `covariances' `covfit') method(`method')
+di "`sem'"
+di"`var'"
+tempname b
+matrix `b'=r(table)
+
+estat gof
+local rmsea4=r(rmsea)
+
+
+local tmp4="`covfit'"
+lstrfun r, subinstr("`tmp4'","e.itemA","0",.)
+lstrfun r, subinstr("`r'","e.itemB","1",.)
+lstrfun r, subinstr("`r'","*","",.)
+lstrfun r, subinstr("`r'"," ","",.)
+}
+}
+
+
+
+
+di "`covfit'"
+tempname V
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+
+qui estat gof,stat(all)
+local iter4=e(ic)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local pclose4=r(pclose)
+local chi24=r(chi2_ms)
+local df4=r(df_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+local bic4=r(bic)
+local convergence4=e(converged)
+local cov_fit4="`r'"
+local arret_covfit4=`arret_covfit'
+local z=`truechange'/sqrt(`Vtruechange')
+
+
+return matrix b4=`b'
+return scalar iter4=e(ic)
+return scalar tli4=`tli4'
+return scalar cfi4=`cfi4'
+return scalar srmr4=`srmr4'
+return scalar rmsea4=`rmsea4'
+return scalar ubrmsea4=`ubrmsea4'
+return scalar lbrmsea4=`lbrmsea4'
+return scalar pclose4=`pclose4'
+return scalar chi24=`chi24'
+return scalar df4=`df4'
+return scalar dfc4=`dfc4'
+return scalar p4=`p4'
+return scalar bic4=`bic4'
+return scalar convergence4=`convergence4'
+return local cov_fit4 = "`cov_fit4'"
+return scalar arret_covfit4 = `arret_covfit4'
+return scalar truechange=`truechange'
+return scalar setruechange=`=sqrt(`Vtruechange')'
+return scalar ztruechange=`=`truechange'/sqrt(`Vtruechange')'
+return scalar ptruechange=`=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+
+
+
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di "Models | chi2 | df | p | BIC | RMSEA | IC90%(RMSEA) | SRMR | CFI | TLI |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %7.2f `bic1' " | " %6.4f `p1' " | " %6.4f `rmsea1' " | " %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' " | " %6.4f `srmr1' " | " %6.2f `cfi1' " | " %6.2f `tli1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %7.2f `bic2' " | " %6.4f `p2' " | " %6.4f `rmsea2' " | " %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' " | " %6.4f `srmr2' " | " %6.2f `cfi2' " | " %6.2f `tli2' " |
"
+ di "Model 4 | " %8.2f `chi24' " | " %4.0f `df4' " | " %7.2f `bic4' " | " %6.4f `p4' " | " %6.4f `rmsea4' " | " %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' " | " %6.4f `srmr4' " | " %6.2f `cfi4' " | " %6.2f `tli4' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 95}"
+ di in gr "Models" _col(14) "chi2" _col(22) "df" _col(31) "p" _col(40) "BIC" _col(47) "RMSEA" _col(55) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+ di "{hline 95}"
+ di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `df1' _col(26) %6.4f `p1' _col(36) %7.2f `bic1' _col(46) %6.4f `rmsea1' _col(54) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+ di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `df2' _col(26) %6.4f `p2' _col(36) %7.2f `bic2' _col(46) %6.4f `rmsea2' _col(54) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+ *di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+ di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `df4' _col(26) %6.4f `p4' _col(36) %7.2f `bic4' _col(46) %6.4f `rmsea4' _col(54) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+ di "{hline 95}"
+}
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di " | Estimation | s.e. | z | p-value |
"
+ di ""
+ di "True change (Model 2) | " %8.4f `truechange2' " | " %8.4f `=sqrt(`Vtruechange2')' " | " %6.2f `=`truechange2'/sqrt(`Vtruechange2')' " | " %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))' " |
"
+ di "True change (Model 4) | " %8.4f `truechange' " | " %8.4f `=sqrt(`Vtruechange')' " | " %6.2f `=`truechange'/sqrt(`Vtruechange')' " | " %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 77}"
+ di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+ di "{hline 77}"
+ di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+ di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+ di "{hline 77}"
+ di
+}
+qui use `saveMultirsoort_indicefit',clear
+
+
+
+end
diff --git a/Modules/ado/personal/m/matrixlisthtml.ado b/Modules/ado/personal/m/matrixlisthtml.ado
new file mode 100644
index 0000000..12c1988
--- /dev/null
+++ b/Modules/ado/personal/m/matrixlisthtml.ado
@@ -0,0 +1,24 @@
+program define matrixlisthtml
+args matrixname precision
+*mat li `matrixname'
+local rownames: rown `matrixname'
+local colnames: coln `matrixname'
+
+di " | "
+foreach mycol in `colnames' {
+ di "" as text "`mycol'" " | "
+}
+di "
"
+
+local rowindex=1
+
+forvalues rowptr=1/`=rowsof(`matrixname')' {
+ local rowname: word `rowindex' of `rownames'
+ di "" "`rowname'" " | "
+ forvalues colptr=1/`=colsof(`matrixname')' {
+ di "" `precision' `matrixname'[`rowptr', `colptr'] " | "
+ }
+ di "
"
+ local ++rowindex
+}
+end
diff --git a/Modules/ado/personal/m/mdreplace.ado b/Modules/ado/personal/m/mdreplace.ado
new file mode 100644
index 0000000..e6e9256
--- /dev/null
+++ b/Modules/ado/personal/m/mdreplace.ado
@@ -0,0 +1,57 @@
+*! version 1 19september2018
+*! Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Stata program : mdreplace
+* Missing data handling in a dataset
+*
+* Historic
+* Version 1 (2018-09-19): Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, Plateforme de MĂ©thodologie et de Biostatistique - DRCi - CHU de Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2018 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 mdreplace
+version 7.0
+syntax varlist(min=1) , list(string)
+
+if "`list'"=="" {
+ di in red "Please indicate in the list option the strings to replace by missing data"
+}
+
+foreach i of varlist `varlist' {
+ foreach e in `list' {
+ *di "variable : `i' code : `e'"
+
+ capture replace `i'="." if `i'=="`e'"
+ if (_rc==0) {
+ qui replace `i'="" if `i'=="`e'"
+ }
+ }
+ capture destring `i', replace
+ if (_rc==0) {
+ qui destring `i', replace
+ }
+}
+
+
+end
+
diff --git a/Modules/ado/personal/m/mi_twoway.ado b/Modules/ado/personal/m/mi_twoway.ado
new file mode 100644
index 0000000..06c9183
--- /dev/null
+++ b/Modules/ado/personal/m/mi_twoway.ado
@@ -0,0 +1,210 @@
+program define mi_twoway,rclass
+syntax varlist [, SCorename(string) REPlace ADD(int 10) STyle(string) clear DA ITerate(int 10)]
+qui{
+tempfile bddini
+save `bddini', replace
+if "`scorename'"==""{
+ local scorename score
+}
+capture tab `scorename'
+if _rc==0{
+ if "`replace'"!=""{
+ drop `scorename'
+ }
+ else{
+ noi di in red "variable `scorename' already exists"
+ use `bddini',replace
+ error 100
+ }
+}
+local nombase ""
+if wordcount("`style'")==0{
+ local style mlong
+}
+else if wordcount("`style'")==1{
+ if "`=word("`style'", 1)'"=="ml" | "`=word("`style'", 1)'"=="mlo" | "`=word("`style'", 1)'"=="mlon" | "`=word("`style'", 1)'"=="mlong" | "`=word("`style'", 1)'"=="fl" | "`=word("`style'", 1)'"=="flo" | "`=word("`style'", 1)'"=="flon" | "`=word("`style'", 1)'"=="flong" | "`=word("`style'", 1)'"=="w" | "`=word("`style'", 1)'"=="wi" | "`=word("`style'", 1)'"=="wid" | "`=word("`style'", 1)'"=="wide"{
+ local style `style'
+ }
+ else{
+ noi di in red "option {it:style} improperly fulfilled"
+ noi di in red " Only {it:mlong}, {it:flong}, {it:wide} and {it:flongsep} are available"
+ noi di in red " A database name must be proposed if the style {it:flongsep} is selected (see mi_styles)"
+ use `bddini',replace
+ error 100
+ }
+}
+else if wordcount("`style'")==2{
+ if "`=word("`style'", 1)'"=="flongs" | "`=word("`style'", 1)'"=="flongse" | "`=word("`style'", 1)'"=="flongsep"{
+ local nombase `=word("`style'", 2)'
+ local style `=word("`style'", 1)'
+ }
+ else{
+ noi di in red "option {it:style} improperly fulfilled"
+ noi di in red " Only {it:mlong}, {it:flong}, {it:wide} and {it:flongsep} are available"
+ noi di in red " A database name must be proposed if the style {it:flongsep} is selected (see mi_styles)"
+ use `bddini',replace
+ error 100
+ }
+}
+
+
+
+
+tempvar var
+
+local M `_dta[_mi_M]'
+if "`M'"!=""{
+ if "`clear'"==""{
+ noi di in red "no; data are mi set"
+ noi di in red " Use {it:clear} option to replace imputed values using mi_twoway, or"
+ noi di in red " other MI commands (like {it:mi extract})"
+ use `bddini',replace
+ error 100
+ }
+ else{
+ mi extract 0, clear
+ }
+}
+
+
+
+
+
+gen `var'id=_n
+sort `var'id
+save `bddini'_bis, replace
+tokenize `varlist'
+if `add'==.{
+ local add==10
+}
+if `iterate'==.{
+ local iterate==10
+}
+
+egen keep=rowmean(`varlist')
+keep if keep!=.
+drop keep
+local Nb=_N
+local nbit: word count `varlist'
+egen `var'i=rowmean(`varlist')
+forvalues j=1/`nbit'{
+ gen it_`var'_`j'=``j''
+}
+keep it_`var'_* `var'id `var'i
+reshape long it_`var'_, i(`var'id) j(it)
+rename it_`var'_ it_`var'
+bysort it: egen Mj=mean(it_`var')
+su it_`var'
+local MM=r(mean)
+gen Me=`var'i+Mj-`MM'
+gen Dif2=(Me-it_`var')^2
+su Dif2
+local Var=r(sum)/(r(N)-1)
+gen __miss=it_`var'==.
+forvalues it=1/`add'{
+ gen _`it'_`var'=it_`var'
+ replace _`it'_`var'=rnormal(Me, `=sqrt(`Var')') if __miss==1
+}
+/* Data augmentation */
+
+
+if "`da'"!=""{
+
+ gen `var'present=1-__miss
+ bysort `var'id: egen `var'Cpre=total(`var'present)
+ bysort it: egen `var'CItpre=total(`var'present)
+ su `var'present
+ local Nobs=r(sum)
+ gen `var'Pre=_1_`var'
+ su `var'Pre
+ local mu=r(mean)
+ bysort it: egen `var'Be=mean(`var'Pre)
+ replace `var'Be=`var'Be-`mu'
+ bysort `var'id: egen `var'Al=mean(`var'Pre)
+ gen `var'sigInt=(`var'Pre-`var'Be-`var'Al)^2
+ su `var'sigInt
+ local sigma2=r(sum)/(`nbit'-1)/(`Nb'-1)
+ gen `var'tauInt=(`var'Al-`mu')^2
+ su `var'tauInt if it==1
+ local tau2=r(sum)/(`Nb'-1)
+ forvalues it=1/`add'{
+ forvalues g=1/`iterate'{
+/* noi di "it = `g'"*/
+ /* Redéfinition alpha */
+ capture drop A2 `var'A2 `var'A2V B2 `var'Be2 Vbe2 S2 TAU
+ gen A2=(it_`var'-`var'Be)/`sigma2'
+ bysort `var'id: egen `var'A2=total(A2)
+ replace `var'A2=(`var'A2+`mu'/`tau2')/(1/`tau2' + `var'Cpre/`sigma2')
+ gen `var'A2V=sqrt(1/(1/`tau2'+`var'Cpre/`sigma2'))
+ replace `var'Al=rnormal(`var'A2, `var'A2V)
+
+ /* Redéfinition beta */
+ gen B2=(it_`var'-`var'Al)
+ bysort it: egen `var'Be2=mean(B2)
+ gen Vbe2=sqrt(`sigma2'/`var'CItpre)
+ replace `var'Be=rnormal(`var'Be2, Vbe2)
+
+ /* Redefinition Sigma */
+ gen S2=(it_`var'-`var'Al-`var'Be)^2
+ su S2
+ local sigma2b=`=r(N)'*`r(mean)'/rchi2(`=r(N)')
+ if `sigma2b'!=0{
+ local sigma2=`sigma2b'
+ }
+
+
+
+
+ /* Redefinition mu */
+ su `var'Al if it==1
+ local mu=rnormal(`=r(mean)', `=sqrt(`tau2'/r(N))')
+
+ /* Redefinition tau2 */
+ gen TAU=(`var'Al-`mu')^2
+ su TAU if it==1
+ local tau2b=`=r(N)'*`r(mean)'/rchi2(`=r(N)')
+ /* 1/(rgamma(`=r(N)/2', `=2/r(N)/r(mean)')) OU `=r(N)'*`r(mean)'/rchi2(`=r(N)')*/
+ if `tau2b'!=0{
+ local tau2=`tau2b'
+ }
+ /*noi di "mu: `mu' tau2: `tau2' sigma2: `sigma2'"
+ noi su `var'Al `var'Be*/
+
+ }
+ replace _`it'_`var'=rnormal(`mu',`=sqrt(`tau2')')+`var'Be+rnormal(0,`=sqrt(`sigma2')') if __miss==1
+ }
+
+}
+/* Fin de data augmentation */
+bysort `var'id: egen _mi_miss=max(__miss)
+drop Mj Me Dif2 `var'i __miss
+keep *_`var' `var'id it _mi_miss
+reshape wide *_`var', i(`var'id) j(it)
+egen `scorename'=rowtotal(it_`var'*)
+replace `scorename'=. if _mi_miss==1
+forvalues j=1/`add'{
+ egen _`j'_`scorename'=rowtotal(_`j'_*), missing
+}
+forvalues i=1/`nbit'{
+ rename it_`var'`i' ``i''
+ forvalues j=1/`add'{
+ rename _`j'_`var'`i' _`j'_``i''
+ label variable _`j'_``i'' ""
+ }
+}
+drop `varlist'
+order `scorename' _mi_miss, first
+sort `var'id
+save `bddini'_ter, replace
+use `bddini'_bis
+merge `var'id using `bddini'_ter
+drop _merge `var'id
+char _dta[_mi_pvars] `scorename'
+char _dta[_mi_M] `add'
+char _dta[_mi_ivars] `varlist'
+char _dta[_mi_style] wide
+char _dta[_mi_marker] _mi_ds_1
+char _dta[_miTW] TW
+mi convert `style' `nombase', clear
+}
+end
diff --git a/Modules/ado/personal/m/mi_twoway.hlp b/Modules/ado/personal/m/mi_twoway.hlp
new file mode 100644
index 0000000..506e63c
--- /dev/null
+++ b/Modules/ado/personal/m/mi_twoway.hlp
@@ -0,0 +1,97 @@
+{smcl}
+{hline}
+
+{hline}
+help for {hi:mi_twoway}{right:Jean-François HAMEL}
+{hline}
+
+{title:Two-way imputations: estimating missing item responses in questionnaires for computing scores}
+
+{p 8 14 2}{cmd:mi_twoway} {it:varlist}, [{cmdab:sc:orename}({it:newvarname})
+{cmdab:rep:lace}
+{cmdab:add:}({it:#})
+{cmdab:st:yle}({it:keyword})
+{cmdab:clear}
+{cmdab:da}
+{cmdab:it:erate}({it:#})]
+
+{title:Description}
+
+{p 8 14 2}{cmd:mi_twoway} is an implementation of multiple imputation methods for tests and questionnaires
+based on a two-way ANOVA model of persons by items.{p_end}
+{p 14 14 2}Two methods are available: imputations based on a fixed effects two-way ANOVA, and imputations
+generated using data augmentation based on a mixed effect two-way ANOVA (with a random person effect
+assumed to follow a Norma distribution and a fixed item effect.{p_end}
+{p 14 14 2}{cmd:mi_twoway} is compatible with the Sata {help mi} procedures. The data is {help mi_set:set}
+and {help mi_impute:imputed} using {cmd:mi_twoway}, but all the estimations using multiple imputations are
+performed using the standard mi {help mi_estimate:estimate} procedures.
+
+{p 4 8 2}{it:varlist} is the list of the variables containing the item responses of the questionnaire
+(with possible missing data).
+
+{title:Options}
+
+{p 4 14 2}{cmd:scorename} specifies the name of the new variable containing, for each individual, the value of the
+score computed as the sum of the item responses. {it:scorename} is missing for each individual with at least one item
+missing response.
+
+{p 4 14 2}{cmd:replace} allows to replace individual scores in existing variables
+
+{p 4 14 2}{cmd:add} specifies the number of imputations to add; required with no imputations
+
+{p 4 14 2}{cmd:style} specifies in which style should be recorded the data: wide, mlong, flong,
+ or flongsep; see {help mi_styles:[MI] styles}.
+
+{p 4 14 2}{cmd:clear} allows performing new imputations by remouving the previous one.
+
+{p 4 14 2}{cmd:da} generates imputations using data augmentation based on a mixed effect two-way
+ANOVA (with a random person effect and a fixed item effect. By default, imputations are generated
+using a fixed effects two-way ANOVA.
+
+{p 4 14 2}{cmd:iterate} defines the number of iterations of the data augmentation algorithm.
+By default, this number is fixed to 10.
+
+{marker example}{...}
+{title:Example}
+
+{pstd}
+Simulation of the data (using {help simirt}):
+
+ {cmd:. simirt, nbobs(200) dim(5) group(0.5) deltagroup(0.4) clear}{right:(1) }
+
+{pstd}
+Creating the missing data, with a non-response rate of 10%:
+
+ . {cmd:set more off }{right:(2) }
+ . {cmd:forvalues i=1/200{c -(} }{right:(3) }
+ 2. {cmd:forvalues j=1/5{c -(}}{right:(4) }
+ 3. {cmd:replace item`j'=. if runiform()<0.1 & id==`i'}{right:(5) }
+ 4. {cmd:{c )-}}{right:(6) }
+ 5. {cmd:{c )-}}{right:(7) }
+
+{pstd}
+Generating 10 multiple imputations using a fixed effects two-way ANOVA:
+
+ . {cmd:mi_twoway item*, scorename(score) add(10) style(wide)}{right:(8) }
+
+{pstd}
+Modeling score depending on {it:group} covariate using multiple imputations estimates ({help mi_estimate}):
+
+ . {cmd:mi estimate: regress score i.group}{right:(9) }
+
+{pstd}
+Changing the way to impute data, using data augmentation based on a mixed effect two-way ANOVA:
+
+ . {cmd:mi_twoway item*, scorename(score) replace add(10) style(wide) da clear}{right:(10) }
+
+{pstd}
+Changing the style of the data from {it:wide} to {it:mlong} ({help mi_convert}):
+
+ . {cmd:mi convert mlong}{right:(11) }
+
+{pstd}
+Removal of the multiple imputations ({help mi_set##unset:mi_unset}):
+
+ . {cmd:mi extract 0, clear}{right:(12) }
+
+
diff --git a/Modules/ado/personal/m/mmsrm.ado b/Modules/ado/personal/m/mmsrm.ado
new file mode 100644
index 0000000..3ee196f
--- /dev/null
+++ b/Modules/ado/personal/m/mmsrm.ado
@@ -0,0 +1,320 @@
+*! Version 4 7December2012
+************************************************************************************************************
+* Stata program : mmsrm
+* Estimate the parameters of the Multidimensional Marginally Sufficient Rasch Model (MMSRM)
+* Version 4 : December 7, 2012 /* id option*/
+*
+* Historic :
+* Version 1 (May 14, 2004) [Jean-Benoit Hardouin]
+* Version 2 (May 26, 2004) [Jean-Benoit Hardouin]
+* Version 3 (July 3, 2005) [Jean-Benoit Hardouin]
+* Version 3.1 : July 8, 2010 /* correction of a bug for the name of the items */
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* 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
+*
+* Copyright 2004-2005, 2010, 2012 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) [if] [in] , id(varname) [PARTition(numlist) NODETails TRAce ITerate(int 30) ADapt METHod(string)]
+preserve
+tempfile mmsrmfile
+qui save `mmsrmfile',replace
+
+/*******************************************************************************
+INTRODUCTION AND TESTS
+********************************************************************************/
+
+marksample touse
+qui keep if `touse'
+
+local nbitems : word count `varlist'
+if "`partition'"=="" {
+ local partition=`nbitems'
+}
+if "`method'"=="" {
+ local method mml
+}
+local method=lower("`method'")
+local nbpart:word count `partition'
+
+if `nbpart'>3 {
+ di in red "{p}The mmsrm module cannot estimate the parameters of the models with more than three dimensions.{p_end}"
+ error 198
+ exit
+}
+else if `nbpart'==3&"`method'"=="gee" {
+ di in red "{p}You cannot estimate the parameters of a MMSRM with 3 dimension and the GEE method.{p_end}"
+ error 198
+ exit
+}
+
+if "`adapt'"!=""&"`method'"!="mml" {
+ di in green "{p}the {cmd:adapt} option is ignored with GEE.{p_end}"
+}
+
+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 "{p}Your {cmd:partition} describes less items than the number of items defined in the {it:varlist}.{p_end}"
+ error 198
+ exit
+}
+if `comptitems'>`nbitems' {
+ di in error "{p}Your {cmd:partition} describes more items than the number of items defined in the {it:varlist}.{p_end}"
+ error 198
+ exit
+}
+
+/*******************************************************************************
+FORMATING AND ESTIMATION (with MML)
+********************************************************************************/
+if `nbpart'== 1 {
+ raschtestv7 `varlist', test(none) method(`method') id(`id')
+ local ll=r(ll)
+ tempname beta1 Varbeta1 M
+ matrix `beta1'=r(beta)
+ matrix `Varbeta1'=r(Varbeta)
+ local sigma1=r(sigma)
+ matrix `M'=(`sigma1'^2)
+}
+else if "`method'"=="mml" {
+ forvalues i=1/`nbpart' {
+ if "`details'"=="" {
+ di in green "{p}Estimation of the difficulty parameters of the dimension `i'.{p_end}"
+ }
+ *set trace on
+ if `part`i''>1 {
+ qui raschtestv7 `set`i'',meth(`method') test(none) id(`id')
+ tempname beta`i' Varbeta`i'
+ matrix `beta`i''=r(beta)
+ matrix `Varbeta`i''=r(Varbeta)
+ local sigma`i'=r(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 "{p}Estimation of the parameters of the distribution of the multidimensional latent trait.{p_end}"
+ di in green "{p}This process could be long to run. Be patient !{p_end}"
+ }
+
+ 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',0,`sigma2')
+ 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(6) dots `trace' `adapt' iterate(`iterate')
+ 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''
+}
+/*******************************************************************************
+FORMATING AND ESTIMATION (with GEE)
+********************************************************************************/
+else if "`method'"=="gee" {
+ tempname coef
+ matrix `coef'=J(`nbitems',`nbpart',0)
+ forvalues i=1/`nbpart' {
+ forvalues j=`firstpart`i''/`=`firstpart`i''+`part`i''-1' {
+ matrix `coef'[`j',`i']=1
+ }
+ }
+ if "`trace'"!="" {
+ local quigee
+ }
+ else {
+ local quigee quietly
+ }
+ `quigee' geekel2d `varlist',coef(`coef') ll nbit(`iterate')
+ local ll=r(ll)
+ tempname cosig varsig M
+ matrix `cosig'=r(b)
+ matrix `M'=J(2,2,0)
+ matrix `M'[1,1]=`cosig'[1,`=`nbitems'+1']
+ matrix `M'[2,2]=`cosig'[1,`=`nbitems'+2']
+ matrix `M'[1,2]=`cosig'[1,`=`nbitems'+3']
+ matrix `M'[2,1]=`cosig'[1,`=`nbitems'+3']
+ matrix `cosig'=`cosig'[1,1..`nbitems']
+ matrix `varsig'=r(V)
+ matrix `varsig'=`varsig'[1..`nbitems',1..`nbitems']
+ forvalues i=1/`nbpart' {
+ tempname beta`i' Varbeta`i'
+ matrix `beta`i''=`cosig'[1,`firstpart`i''..`=`firstpart`i''+`part`i''-1']
+ matrix `Varbeta`i''=`varsig'[`firstpart`i''..`=`firstpart`i''+`part`i''-1',`firstpart`i''..`=`firstpart`i''+`part`i''-1']
+ if `part`i''==1 {
+ local parambeta`firstpart`i''=`cosig'[1,`firstpart`i'']
+ }
+ }
+}
+
+/*******************************************************************************
+DISPLAYING OF THE RESULTS
+********************************************************************************/
+
+local AIC=-2*`ll'+2*(`nbitems'+`nbpart'*(`nbpart'+1)/2)
+
+if `nbpart'>1 {
+ forvalues i=1/`nbpart' {
+ local var`i'=`M'[`i',`i']
+ forvalues j=`=`i'+1'/`nbpart' {
+ local cov`i'`j'=`M'[`i',`j']
+ }
+ }
+ 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 p=1/`nbpart' {
+ forvalues i=1/`part`p'' {
+ local name:word `i' of `set`p''
+ if `part`p''!=1 {
+ noi di in yellow _col(4) "`name'" _col(18) %8.5f `beta`p''[1,`i'] _col(30) %6.5f sqrt(`Varbeta`p''[`i',`i'])
+ }
+ else {
+ noi di in yellow _col(4) "`name'" _col(18) %8.5f `parambeta`firstpart`p''' _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''
+ }
+
+ forvalues i=1/`nbpart' {
+ forvalues j=`=`i'+1'/`nbpart' {
+ di in green _col(4) in yellow "cov`i'`j'" _col(18) %8.5f `cov`i'`j''
+ }
+ }
+ di in green _col(4) "{hline 33}"
+}
+if "`trace'"==""&"`details'"=="" {
+ di in green "{p}Add the -trace- option to obtain the standard errors of the elements of the covariance matrix of the latent traits.{p_end}"
+}
+
+/*******************************************************************************
+OUTPUTS
+********************************************************************************/
+
+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 {
+ matrix colnames `beta`i''=`set`i''
+ matrix rownames `beta`i''=beta
+ ereturn matrix beta`i'=`beta`i''
+ matrix colnames `Varbeta`i''=`set`i''
+ matrix rownames `Varbeta`i''=`set`i''
+ ereturn matrix Varbeta`i' `Varbeta`i''
+ }
+ else {
+ ereturn scalar beta`i'=`parambeta`firstpart`i'''
+ }
+}
+
+tempname matrixsigma
+matrix `matrixsigma'=`M'
+local list
+forvalues i=1/`nbpart' {
+ local list `list' latenttrait`i'
+}
+matrix colnames `matrixsigma'=`list'
+matrix rownames `matrixsigma'=`list'
+ereturn matrix covar=`matrixsigma'
+
+drop _all
+qui use `mmsrmfile'
+end
diff --git a/Modules/ado/personal/m/mmsrm.hlp b/Modules/ado/personal/m/mmsrm.hlp
new file mode 100644
index 0000000..f3f07d1
--- /dev/null
+++ b/Modules/ado/personal/m/mmsrm.hlp
@@ -0,0 +1,72 @@
+{smcl}
+{* 5may2013}{...}
+{hline}
+help for {hi:mmsrm}
+{hline}
+
+{title:Estimation of the parameters of a Multidimensional Marginally Sufficient Rasch Model (MMSRM)}
+
+{p 8 14 2}{cmd:mmsrm} {it:varlist} {cmd:id}({it:varname}) [{cmd:,} {cmdab:part:ition}({it:numlist}) {cmdab:nodet:ails} {cmdab:trac:e} {cmdab:it:erate}({it:#}) {cmdab:ad:apt} {cmdab:meth:od}({it:mml/gee})]
+
+{p 8 14 2}{it:varlist} is a list of two existing binary variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:mmsrm} estimates by marginal maximum likelihood (MML) or
+generalized estimating equations (GEE) the parameters of the Multidimensional
+Marginally Sufficient Rasch Model (MMSRM) defined by Hardouin and Mesbah (2004).
+This model is an Item Response Model (IRM) with one or several latent traits.
+This is a particular multidimensionnal extension of the Rasch model. In this
+model, the items are separated in Q groups and each group of items is linked to
+one and only one latent trait. Each group fits a Rasch model relatively to the
+corresponding latent trait, so the score computed in each group of item is a
+sufficient statistics of this latent trait (to a specific value of this score
+is associated only one value for the latent trait). The program allows
+computing the parameter of a MMSRM with less than 4 latent traits.
+To improve the time of computing, the difficulty parameters are estimated in
+each unidimensional Rasch model and used as an offset variable to estimate the
+parameters of the distribution of the multidimensional latent trait. This model
+allows estimating the correlations between different latent traits measured by
+Rasch models.
+
+{title:Options}
+
+{p 4 8 2}{cmd:id} defines an identifiant variable of the individuals.
+
+{p 4 8 2}{cmd:partition} allows defining the number of items relied to each
+latent trait. The sum of the numbers indicated in the {it:numlist} must be
+equal to the total number of items. The number of elements indicates the number of
+latent traits. The items are taken in the same order than this one of {it:varlist}.
+By default, only one latent trait is assumed (Rasch model). The number of elements of
+{cmd:partition} must be inferior or equal to 3.
+
+{p 4 8 2}{cmd:method} defines the estimation method between the marginal maximum
+likelihood ({it:mml} - by default) and the generalized estimating equations ({it:gee}).
+You cannot estimate the parameters of a MMSRM with 3 dimensions with the GEE method.
+
+{p 4 8 2}{cmd:nodetails} deletes the details about the procedure.
+
+{p 4 8 2}{cmd:trace} displays details about the estimation algorithm.
+
+{p 4 8 2}{cmd:iterate} defines the maximal number of iterations of the estimation algorithm
+ (30 by default).
+
+{p 4 8 2}{cmd:adapt} allows using the adaptive quadrature if you use the MML method of estimation. This option
+is useless if you use GEE.
+
+{title:Example}
+
+{p 16 22 2} {inp:. mmsrm item1-item9 , part(4 5) trace method(gee)}
+
+{p 16 22 2} {inp:. mmsrm item1 item2 item3 item4 /*Rasch model*/}
+
+{p 16 22 2} {inp:. mmsrm c1-c9 , part(3 3 3) nodetails adapt iterate(10)}
+
+{title:References}
+
+{p 4 8 2}Hardouin J.-B. and Mesbah M. Clustering binary variables in subscales using an extended Rasch model and Akaike Information Criterion. {it:Communications in Statistics - Theory and Methods}, {cmd:33}(6), pp. 1277-1294, (2004).
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France.
+You can contact the author at {browse "mailto:jean-benoit.hardouin@neuf.fr":jean-benoit.hardouin@neuf.fr} and visit the websites {browse "http://anaqol.free.fr":AnaQol} and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/m/mmsrm2.ado b/Modules/ado/personal/m/mmsrm2.ado
new file mode 100644
index 0000000..e0e3499
--- /dev/null
+++ b/Modules/ado/personal/m/mmsrm2.ado
@@ -0,0 +1,241 @@
+************************************************************************************************************
+* 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
diff --git a/Modules/ado/personal/m/msp.ado b/Modules/ado/personal/m/msp.ado
new file mode 100644
index 0000000..eef143a
--- /dev/null
+++ b/Modules/ado/personal/m/msp.ado
@@ -0,0 +1,454 @@
+*! Version 8.1.1 26 September 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : msp
+* Mokken Scale Procedure
+* Release 8.1.1: (September 26, 2013) [Jean-Benoit Hardouin] /*correction of a rare bug */
+*
+* Historic :
+* Version 1 - lose version (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (September 25, 2002) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 5.1 (May 1st, 2004) [Jean-Benoit Hardouin]
+* Version 6 : (July 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 : (September 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.2 : (January 22, 2006) [Jean-Benoit Hardouin] /*English improvements*/
+* Release 6.3 : (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.6: (Februar 16, 2007) [Jean-Benoit Hardouin] /*Tests of the loevinger H indices, adaptation for loevH 6.6, noadjust option, improvements*/
+* Release 8: (December 8, 2010) [Jean-Benoit Hardouin] /*Adaptation for loevh version 8*/
+* Release 8.1: (December 19, 2012) [Jean-Benoit Hardouin] /*correction of a bug with the notest option*/
+* Release 8.1.1: (September 26, 2013) [Jean-Benoit Hardouin] /*correction of a rare bug */
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@anaqol.org
+*
+* The Stata program loevh is needed. It can be downloaded on http://www.anaqol.org
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2007, 2010, 2012 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 msp , rclass
+version 7.0
+syntax varlist(min=2 numeric) [,c(real 0.3) noDETails KERnel(integer 0) noTEst p(real 0.05) PAIRWise MINValue(real 0) noBon noADJust]
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempfile mspfile
+qui save "`mspfile'"
+
+if "`pairwise'"=="" {
+ forvalues j=1/`nbitems' {
+ qui drop if ``j''==.
+ }
+}
+if "`test'"!="" {
+ local p=1
+ local minvalue=-99
+ local bon nobon
+}
+
+
+
+qui loevh `varlist',`pairwise' pair `adjust'
+tempname pvalHjk loevHjk loevHjks loevHj loevH Hjk stopscale stop dim plusitems Hjkmax Hjmax Hmax nbitemsel
+matrix `loevHjk'=r(loevHjk)
+matrix `loevHjks'=r(loevHjk)
+matrix `pvalHjk'=r(pvalHjk)
+matrix `loevHj'=r(loevHj)
+scalar `loevH'=r(loevH)
+matrix `Hjk'=`loevHjk'
+
+matrix define `dim'=J(1,`nbitems',0)
+
+global scale=0
+scalar `stopscale'=0
+
+while `stopscale'!=1 { /*WHILE IT IS POSSIBLE TO CONSTRUCT SCALES*/
+ global scale=$scale+1
+ local dimension=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp'
+ global `scaletmpnum'
+ if "`details'"=="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+
+/**********************************************************************************************************
+BEGINING OF THE INITIAL STEP
+**********************************************************************************************************/
+
+/****NONE KERNEL OR NOT THE FIRST SCALE****/
+ if $scale>1|`kernel'==0 {
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ local nbitemsbon=0
+ forvalues j1=1/`nbitems' {
+ if `dim'[1,`j1']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ if `nbitemsbon'<=1 {
+ local nbitemsbon=2
+ }
+ local kbon=`nbitemsbon'*(`nbitemsbon'-1)/2
+ if "`bon'"==""&"`test'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`test'"!="" {
+ local pbon=1
+ local p=1
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j1=1/`nbitems' { /*WE SEARCH THE BEST PAIR OF ITEMS*/
+ if `dim'[1,`j1']==0 {
+ scalar `plusitems'=1
+ forvalues j2=`=`j1'+1'/`nbitems' {
+ if `dim'[1,`j2']==0 {
+ if `Hjk'[`j1',`j2']>`Hjkmax'&`pvalHjk'[`j1',`j2']<=`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j1',`j2']
+ global j1max=`j1'
+ global j2max=`j2'
+ }
+ }
+ }
+ }
+ }
+
+ if `Hjkmax'==-99 { /*IF NONE PAIR OF ITEM VERIFY Hjk>0*/
+ if `plusitems'==0 {
+ if "`details'"=="" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ }
+ else {
+ if "`details'"=="" {
+ di as green "{p}None pair of items has a significantly positive Hjk coefficient.{p_end}"
+ }
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE PAIR OF ITEM VERIFY Hjk>c*/
+ if $scale==1 {
+ if "`details'"=="" {
+ di as green "{p}None pair of items verifies Hjk>`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ }
+ else {
+ if "`details'"=="" {
+ di as green "{p}None new scale can be constructed because none pair of items, among the remaining items, verifies Hjk>`c'{p_end}"
+ }
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /*IF THERE IS AT LEAST ONE PAIR OF ITEM WHO VERIFY Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j1max' `$j2max'"
+ global `scaletmpnum' "$j1max $j2max"
+ if "`details'"=="" {
+ di in green "{p}The two first items selected in the scale " in yellow "$scale " in green "are " in yellow "`$j1max' " in green "and " in yellow "`$j2max'" in green " (Hjk=" in yellow %6.4f `Hjkmax' in green "){p_end}"
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE TWO SELECTED ITEMS*/
+ if ((`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ if ((`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF ONE ITEM****/
+ if $scale==1&`kernel'==1 {
+ global j1max=1
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ if "`details'"=="" {
+ di in green "The item " in yellow "`1'" in green " is the kernel of the first scale"
+ }
+ local nbitemsbon=0
+ forvalues i=2/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE ITEM OF THE KERNEL*/
+ if (`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`nbitemsbon'
+ if "`bon'"==""&"`test'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=2/`nbitems' {/*WE SEARCH THE BEST ITEM TO SELECT WITH THE KERNEL*/
+ if `Hjk'[`j2',1]>`Hjkmax'&`pvalHjk'[`j2',1]<`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j2',1]
+ global j2max=`j2'
+ }
+ }
+
+ if `Hjkmax'==-99 {/*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk<*/
+ if "`details'"=="" {
+ di as green "{p}None item associated to the item " in yellow "$j1 " in green "allows obtaining a significantly positive value for the Hjk coefficient.{p_end}"
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /* IF AT LEAST ONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j2max' `$j1max'"
+ global `scaletmpnum' "$j2max $j1max"
+ if "`details'"=="" {
+ di in green "The second item selected in the first scale is " in yellow "`$j2max' " in green "(Hjk=" in yellow %6.4f `Hjkmax' in green")"
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE NEW SELECTED ITEM*/
+ if (`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>`p')&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF SEVERAL ITEMS****/
+ if $scale==1&`kernel'>=2 {
+ global scale1
+ local scalenum1
+ local kbon=1
+ local pbon=`p'
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=1/`kernel' {
+ global scale1 ``j2'' $scale1
+ global scalenum1 $scalenum1 `j2'
+ matrix `dim'[1,`j2']=1
+ }
+ if "`details'"=="" {
+ di in green "{p}The kernel of the first scale is composed of the items " in yellow "$scale1{p_end}"
+ }
+ scalar `nbitemsel'=`kernel'
+ forvalues j=1/`kernel' {
+ forvalues i=1/`nbitems' { /* WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE ITEMS OF THE KERNEL*/
+ if (`loevHjks'[`i',`j']<`minvalue'|`pvalHjk'[`i',`j']>`p')&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ local excluded `excluded' ``i''
+ matrix `dim'[1,`i']=-2
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ scalar `stop'=0
+
+/**********************************************************************************************************
+END OF THE INITIAL STEP
+**********************************************************************************************************/
+
+ while `stop'!=1 { /*WHILE THE PROCEDURE TO CONSTRUCT THE ACTUAL SCALE IS NOT STOPPED*/
+
+ scalar `Hjmax'=-99
+ scalar `Hmax'=-99
+ global jmax=0
+
+ global stopmax=0
+ local nbitemsbon=0
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`kbon'+`nbitemsbon'
+ if "`bon'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+
+
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {/*IF THE ITEM J0 IS UNSELECTED*/
+ global stopmax=1
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ qui loevh ``j0'' $`scaletmp' ,`pairwise' pair `adjust'
+ tempname pvalHj0
+ matrix `pvalHj0'=r(pvalHj)
+ scalar `pvalHj0'=`pvalHj0'[1,1]
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ local nbitsc : word count $`scaletmp'
+ local nbitsc=`nbitsc'+1
+ if `loevHj'[1,1]>`c'&`pvalHj0'<`pbon' {/*IF THE ITEM J0 CAN BE SELECTED*/
+ if `loevH'>`Hmax' {/*AND IF IT IS THE BEST ITEM (COMPARED TO THE PRECEEDING ITEMS)*/
+ scalar `Hjmax'=`loevHj'[1,1]
+ scalar `Hmax'=`loevH'
+ global j="``j0''"
+ global j0=`j0'
+ }
+ }
+ }
+ }
+
+ if $stopmax==1&`Hjmax'==-99 { /*IF THERE IS ITEMS REMAINING BUT NONE OF THEM CAN BE SELECTED*/
+
+ if "`details'"=="" {
+ di in green "{p}None new item can be selected in the scale $scale because all the Hj are lesser than `c' or none new item has all the related Hjk coefficients significantly greater than 0{p_end}."
+ }
+ scalar `stop'=1
+ continue,break
+ }
+ if $stopmax==0 { /*IF THERE IS NO MORE ITEM REMAINING*/
+ if "`details'"=="" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ scalar `stopscale'=1
+ scalar `stop'=1
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ scalar `stopscale'=0
+ }
+ }
+ *global scale=$scale-1
+ continue,break
+ }
+
+
+ if `stop'!=1 { /*IF THE PROCEDURE IS NOT STOPPED*/
+ matrix `dim'[1,$j0]=$scale
+ local `scaletmp'="scale$scale"
+ local `scaletmpnum'="scalenum$scale"
+ global `scaletmp' $j $`scaletmp'
+ global `scaletmpnum' $j0 $`scaletmpnum'
+ if "`details'"=="" {
+ di in green "The item " in yellow "`$j0' " in green "is selected in the scale " in yellow "$scale" _col(50) in green "Hj=" in yellow %6.4f `Hjmax' _col(65) in green "H=" in yellow %6.4f `Hmax' ""
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ matrix `dim'[1,`i']=-2
+ }
+ if `dim'[1,`i']==0 { /*WE EXCLUDE ITEMS WHO HAVE A NEGATIVE Hjk WITH THE NEW SELECTED ITEM*/
+ if `loevHjks'[`i',$j0]<`minvalue'|`pvalHjk'[`i',$j0]>`p' {
+ matrix `dim'[1,`i']=-1
+ local excluded `excluded' ``i''
+ }
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ }
+ }
+ di
+ local scaleencours="scale$scale"
+ local scalenumencours="scalenum$scale"
+ local nbitemscale : word count $`scaleencours'
+ return scalar nbitems`dimension'=`nbitemscale'
+ if `nbitemscale'>0 { /* IF AT LEAST TWO ITEMS HAVE BEEN SELECTED*/
+ if "`details'"!="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+ loevh $`scaleencours',`pairwise' `adjust'
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ return scalar H`dimension'=`loevH'
+ return local scale`dimension' $`scaleencours'
+ return local scalenum`dimension' $`scalenumencours'
+ local j=`nbitemscale'
+ di
+ }
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ matrix `dim'[1,`i']=0
+ }
+ }
+
+ local restnbitems=0
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {
+ local restnbitems=`restnbitems'+1
+ local restitem ``j0''
+ }
+ }
+
+ if `restnbitems'==1 { /*IF THERE IS ONLY ONE ITEM REMAINING*/
+ di
+ di in green "{p}There is only one item remaining (" in yellow "`restitem'" in green ").{p_end}"
+ local stopscale=1
+ return local lastitem "`restitem'"
+ }
+
+}
+
+return scalar dim=$scale
+matrix colnames `dim'=`varlist'
+return matrix selection=`dim'
+
+qui use "`mspfile'",clear
+end
diff --git a/Modules/ado/personal/m/msp.hlp b/Modules/ado/personal/m/msp.hlp
new file mode 100644
index 0000000..7a51eb4
--- /dev/null
+++ b/Modules/ado/personal/m/msp.hlp
@@ -0,0 +1,94 @@
+{smcl}
+{* 8december2010}{...}
+{hline}
+help for {hi:msp}
+{hline}
+
+{title:Mokken Scale Procedure}
+
+{p 8 14 2}{cmd:msp} {it:varlist} [{cmd:,} {cmdab:nodet:ails}
+{cmdab:ker:nel}({it:#}) {cmdab:c}({it:#}) {cmdab:note:st} {cmdab:p}({it:#})
+{cmdab:pairw:ise} {cmdab:minv:alue}({it:#}) {cmdab:nob:on} {cmdab:noadj:ust}]
+
+
+{p 8 14 2}{it:varlist} is a list of two existing dichotomous or polytomous variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:msp} selects scales of dichotomous or polytomous items with the Mokken Scale Procedure (MSP) defined by Mokken (1971) and by Hemker and al. (1995).
+
+{title:Options}
+
+{p 4 8 2}{cmd:nodetails} does not display informations during the algorithm of selection.
+
+{p 4 8 2}{cmd:kernel} defines a kernel for the first scale, defined as the first # items of {it:varlist}.
+
+{p 4 8 2}{cmd:c} defines the level of the threshold {it:c}. The level of {it:c} is fixed, by default, at 0.3.
+
+{p 4 8 2}{cmd:notest} selects the scales whithout tests among the Loevinger H coefficient (Hjk>0): the new item with the maximal value for Hj>c is always selected.
+
+{p 4 8 2}{cmd:p} defines the significance level for the tests. The level of {it:p} is fixed, by default, at 0.05.
+
+{p 4 8 2}{cmd:pairwise} does no more delete all the individuals who have one or more missing values among all the items of {it:varlist} but, only these ones who have, for each pair of items, one or more missing values to these two items.
+
+{p 4 8 2}{cmd:minvalue} defines the minimum value of the coefficient Hjk for a pair of item composing a scale. This minimal value is fixed by default to 0.
+
+{p 4 8 2}{cmd:nobon} does no more correct the significance level of the test by the Bonferroni correction.
+
+{p 4 8 2}{cmd:noadjust} approximates the tests statistics like the MSP program (Molenaar et al. (2000)).
+
+{title:Remarks}
+
+{p 4 8 2}For detailed informations on the Mokken scale procedure, see Mokken (1971), Hemker and al. (1995) or the manual of the MSP software (2000).
+
+{p 4 8 2}{cmd:msp} runs with dichotomous or polytomous items.
+
+{p 4 8 2}{cmd:msp} necessitates the program {help loevh} to compute.
+
+{title:Results}
+
+{p 4 8 2}{it:r(dim)} saves the number of built scales.
+
+{p 4 8 2}{it:r(selection)} saves a vector which contains, for each item, the scale where it is selected (0 if the item is unselected).
+
+{p 4 8 2}{it:r(H#)} saves the Loevinger's H coefficient of the #th scale.
+
+{p 4 8 2}{it:r(nbitems#)} saves the number of items selected in the #th scale.
+
+{p 4 8 2}{it:r(scale#)} saves the names of the items selected in the #th scale.
+
+{p 4 8 2}{it:r(scalenum#)} saves the numbers of the items selected in the #th scale.
+
+{title:Example}
+
+ {inp:. msp itemA1-itemA7}
+
+ {inp:. msp itemA* itemB* , nodetails kernel(2)}
+
+ {inp:. msp item* , c(0.2) nob pairwise}
+
+
+{title:References}
+
+{p 4 8 2}Hemker B. T., Sijtsma K. and Molenaar I. W., Selection of unidimensional scales from a multidimensional item bank in the polytomous Mokken IRT
+model, {it: Applied Psychological Measurement}, vol.19(4), 1995, pp. 337-352.
+
+{p 4 8 2}Mokken R. J., A theory and procedure of scale analysis. New-York/Berlin : De Guyter, 1971.
+
+{p 4 8 2}Molenaar I. W., Sijtsma K. and Boer P. User's manual of MSP5 for Windows. Groningen (The Netherlands): iec ProGAMMA, 2000.
+
+{title:Also see}
+
+{p 4 13 2} help for {help loevh} (if installed), help for {help mokken} (if installed)
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
diff --git a/Modules/ado/personal/m/msp66.ado b/Modules/ado/personal/m/msp66.ado
new file mode 100644
index 0000000..23cb1fc
--- /dev/null
+++ b/Modules/ado/personal/m/msp66.ado
@@ -0,0 +1,447 @@
+*! Version 6.6 16 Februar 2007
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : msp
+* Mokken Scale Procedure
+* Release 6.6: Februar 16, 2007 /*Tests of the loevinger H indices, adaptation for loevH 6.6, noadjust option, improvements*/
+*
+* Historic :
+* Version 1 - lose version (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (September 25, 2002) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 5.1 (May 1st, 2004) [Jean-Benoit Hardouin]
+* Version 6 : (July 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 : (September 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.2 : (January 22, 2006) [Jean-Benoit Hardouin] /*English improvements*/
+* Release 6.3 : (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@anaqol.org
+*
+* The Stata program loevH is needed. It can be downloaded on http://www.anaqol.org
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2007 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 msp , rclass
+version 7.0
+syntax varlist(min=2 numeric) [,c(real 0.3) noDETails KERnel(integer 0) noTEst p(real 0.05) PAIRWise MINValue(real 0) noBon noADJust]
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempfile mspfile
+qui save "`mspfile'"
+
+if "`pairwise'"=="" {
+ forvalues j=1/`nbitems' {
+ qui drop if ``j''==.
+ }
+}
+if "`test'"!="" {
+ local p=1
+ local minvalue=-99
+ local bon nobon
+}
+
+
+
+qui loevH `varlist',`pairwise' pair `adjust'
+tempname pvalHjk loevHjk loevHjks loevHj loevH Hjk stopscale stop dim plusitems Hjkmax Hjmax Hmax nbitemsel
+matrix `loevHjk'=r(loevHjk)
+matrix `loevHjks'=r(loevHjk)
+matrix `pvalHjk'=r(pvalHjk)
+matrix `loevHj'=r(loevHj)
+scalar `loevH'=r(loevH)
+matrix `Hjk'=`loevHjk'
+
+matrix define `dim'=J(1,`nbitems',0)
+
+global scale=0
+scalar `stopscale'=0
+
+while `stopscale'!=1 { /*WHILE IT IS POSSIBLE TO CONSTRUCT SCALES*/
+ global scale=$scale+1
+ local dimension=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp'
+ global `scaletmpnum'
+ if "`details'"=="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+
+
+/**********************************************************************************************************
+BEGINING OF THE INITIAL STEP
+**********************************************************************************************************/
+
+/****NONE KERNEL OR NOT THE FIRST SCALE****/
+ if $scale>1|`kernel'==0 {
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ local nbitemsbon=0
+ forvalues j1=1/`nbitems' {
+ if `dim'[1,`j1']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ if `nbitemsbon'<=1 {
+ local nbitemsbon=2
+ }
+ local kbon=`nbitemsbon'*(`nbitemsbon'-1)/2
+ if "`bon'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j1=1/`nbitems' { /*WE SEARCH THE BEST PAIR OF ITEMS*/
+ if `dim'[1,`j1']==0 {
+ scalar `plusitems'=1
+ forvalues j2=`=`j1'+1'/`nbitems' {
+ if `dim'[1,`j2']==0 {
+ if `Hjk'[`j1',`j2']>`Hjkmax'&`pvalHjk'[`j1',`j2']<=`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j1',`j2']
+ global j1max=`j1'
+ global j2max=`j2'
+ }
+ }
+ }
+ }
+ }
+
+ if `Hjkmax'==-99 { /*IF NONE PAIR OF ITEM VERIFY Hjk>0*/
+ if `plusitems'==0 {
+ if "`details'"=="" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ }
+ else {
+ if "`details'"=="" {
+ di as green "{p}None pair of items has a significantly positive Hjk coefficient.{p_end}"
+ }
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE PAIR OF ITEM VERIFY Hjk>c*/
+ if $scale==1 {
+ if "`details'"=="" {
+ di as green "{p}None pair of items verifies Hjk>`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ }
+ else {
+ if "`details'"=="" {
+ di as green "{p}None new scale can be constructed because none pair of items, among the remaining items, verifies Hjk>`c'{p_end}"
+ }
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /*IF THERE IS AT LEAST ONE PAIR OF ITEM WHO VERIFY Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j1max' `$j2max'"
+ global `scaletmpnum' "$j1max $j2max"
+ if "`details'"=="" {
+ di in green "{p}The two first items selected in the scale " in yellow "$scale " in green "are " in yellow "`$j1max' " in green "and " in yellow "`$j2max'" in green " (Hjk=" in yellow %6.4f `Hjkmax' in green "){p_end}"
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE TWO SELECTED ITEMS*/
+ if (`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>.05)&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ if (`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>.05)&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF ONE ITEM****/
+ if $scale==1&`kernel'==1 {
+ global j1max=1
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ if "`details'"=="" {
+ di in green "The item " in yellow "`1'" in green " is the kernel of the first scale"
+ }
+ local nbitemsbon=0
+ forvalues i=2/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE ITEM OF THE KERNEL*/
+ if (`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>.05)&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`nbitemsbon'
+ if "`bon'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=2/`nbitems' {/*WE SEARCH THE BEST ITEM TO SELECT WITH THE KERNEL*/
+ if `Hjk'[`j2',1]>`Hjkmax'&`pvalHjk'[`j2',1]<`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j2',1]
+ global j2max=`j2'
+ }
+ }
+
+ if `Hjkmax'==-99 {/*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk<*/
+ if "`details'"=="" {
+ di as green "{p}None item associated to the item " in yellow "$j1 " in green "allows obtaining a significantly positive value for the Hjk coefficient.{p_end}"
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /* IF AT LEAST ONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j2max' `$j1max'"
+ global `scaletmpnum' "$j2max $j1max"
+ if "`details'"=="" {
+ di in green "The second item selected in the first scale is " in yellow "`$j2max' " in green "(Hjk=" in yellow %6.4f `Hjkmax' in green")"
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE NEW SELECTED ITEM*/
+ if (`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>.05)&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF SEVERAL ITEMS****/
+ if $scale==1&`kernel'>=2 {
+ global scale1
+ local scalenum1
+ local kbon=1
+ local pbon=`p'
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=1/`kernel' {
+ global scale1 ``j2'' $scale1
+ global scalenum1 $scalenum1 `j2'
+ matrix `dim'[1,`j2']=1
+ }
+ if "`details'"=="" {
+ di in green "{p}The kernel of the first scale is composed of the items " in yellow "$scale1{p_end}"
+ }
+ scalar `nbitemsel'=`kernel'
+ forvalues j=1/`kernel' {
+ forvalues i=1/`nbitems' { /* WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE ITEMS OF THE KERNEL*/
+ if (`loevHjks'[`i',`j']<`minvalue'|`pvalHjk'[`i',`j']>.05)&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ local excluded `excluded' ``i''
+ matrix `dim'[1,`i']=-2
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ scalar `stop'=0
+
+/**********************************************************************************************************
+END OF THE INITIAL STEP
+**********************************************************************************************************/
+
+ while `stop'!=1 { /*WHILE THE PROCEDURE TO CONSTRUCT THE ACTUAL SCALE IS NOT STOPPED*/
+
+ scalar `Hjmax'=-99
+ scalar `Hmax'=-99
+ global jmax=0
+
+ global stopmax=0
+ local nbitemsbon=0
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`kbon'+`nbitemsbon'
+ if "`bon'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+
+
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {/*IF THE ITEM J0 IS UNSELECTED*/
+ global stopmax=1
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ qui loevH ``j0'' $`scaletmp' ,`pairwise' pair `adjust'
+ tempname pvalHj0
+ matrix `pvalHj0'=r(pvalHj)
+ scalar `pvalHj0'=`pvalHj0'[1,1]
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ local nbitsc : word count $`scaletmp'
+ local nbitsc=`nbitsc'+1
+ if `loevHj'[1,1]>`c'&`pvalHj0'<`pbon' {/*IF THE ITEM J0 CAN BE SELECTED*/
+ if `loevH'>`Hmax' {/*AND IF IT IS THE BEST ITEM (COMPARED TO THE PRECEEDING ITEMS)*/
+ scalar `Hjmax'=`loevHj'[1,1]
+ scalar `Hmax'=`loevH'
+ global j="``j0''"
+ global j0=`j0'
+ }
+ }
+ }
+ }
+
+ if $stopmax==1&`Hjmax'==-99 { /*IF THERE IS ITEMS REMAINING BUT NONE OF THEM CAN BE SELECTED*/
+
+ if "`details'"=="" {
+ di in green "{p}None new item can be selected in the scale $scale because all the Hj are lesser than `c' or none new item has all the related Hjk coefficients significantly greater than 0{p_end}."
+ }
+ scalar `stop'=1
+ continue,break
+ }
+ if $stopmax==0 { /*IF THERE IS NO MORE ITEM REMAINING*/
+ if "`details'"=="" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ scalar `stopscale'=1
+ scalar `stop'=1
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ scalar `stopscale'=0
+ }
+ }
+ *global scale=$scale-1
+ continue,break
+ }
+
+
+ if `stop'!=1 { /*IF THE PROCEDURE IS NOT STOPPED*/
+ matrix `dim'[1,$j0]=$scale
+ local `scaletmp'="scale$scale"
+ local `scaletmpnum'="scalenum$scale"
+ global `scaletmp' $j $`scaletmp'
+ global `scaletmpnum' $j0 $`scaletmpnum'
+ if "`details'"=="" {
+ di in green "The item " in yellow "`$j0' " in green "is selected in the scale " in yellow "$scale" _col(50) in green "Hj=" in yellow %6.4f `Hjmax' _col(65) in green "H=" in yellow %6.4f `Hmax' ""
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ matrix `dim'[1,`i']=-2
+ }
+ if `dim'[1,`i']==0 { /*WE EXCLUDE ITEMS WHO HAVE A NEGATIVE Hjk WITH THE NEW SELECTED ITEM*/
+ if `loevHjks'[`i',$j0]<`minvalue'|`pvalHjk'[`i',$j0]>.05 {
+ matrix `dim'[1,`i']=-1
+ local excluded `excluded' ``i''
+ }
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ }
+ }
+ di
+ local scaleencours="scale$scale"
+ local scalenumencours="scalenum$scale"
+ local nbitemscale : word count $`scaleencours'
+ return scalar nbitems`dimension'=`nbitemscale'
+ if `nbitemscale'>0 { /* IF AT LEAST TWO ITEMS HAVE BEEN SELECTED*/
+ if "`details'"!="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+ loevH $`scaleencours',`pairwise' `adjust'
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ return scalar H`dimension'=`loevH'
+ return local scale`dimension' $`scaleencours'
+ return local scalenum`dimension' $`scalenumencours'
+ local j=`nbitemscale'
+ di
+ }
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ matrix `dim'[1,`i']=0
+ }
+ }
+
+ local restnbitems=0
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {
+ local restnbitems=`restnbitems'+1
+ local restitem ``j0''
+ }
+ }
+
+ if `restnbitems'==1 { /*IF THERE IS ONLY ONE ITEM REMAINING*/
+ di
+ di in green "{p}There is only one item remaining (" in yellow "`restitem'" in green ").{p_end}"
+ local stopscale=1
+ return local lastitem "`restitem'"
+ }
+
+}
+
+return scalar dim=$scale
+matrix colnames `dim'=`varlist'
+return matrix selection=`dim'
+
+qui use "`mspfile'",clear
+end
diff --git a/Modules/ado/personal/m/msp66.hlp b/Modules/ado/personal/m/msp66.hlp
new file mode 100644
index 0000000..de2a171
--- /dev/null
+++ b/Modules/ado/personal/m/msp66.hlp
@@ -0,0 +1,91 @@
+{smcl}
+{* 22january2006}{...}
+{hline}
+help for {hi:msp}
+{hline}
+
+{title:Mokken Scale Procedure}
+
+{p 8 14 2}{cmd:msp} {it:varlist} [{cmd:,} {cmdab:nodet:ails}
+{cmdab:ker:nel}({it:#}) {cmdab:c}({it:#}) {cmdab:note:st} {cmdab:p}({it:#})
+{cmdab:pairw:ise} {cmdab:minv:alue}({it:#}) {cmdab:nob:on} {cmdab:noadj:ust}]
+
+
+{p 8 14 2}{it:varlist} is a list of two existing dichotomous or polytomous variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:msp} selects scales of dichotomous or polytomous items with the Mokken Scale Procedure (MSP) defined by Mokken (1971) and by Hemker and al. (1995).
+
+{title:Options}
+
+{p 4 8 2}{cmd:nodetails} does not display informations during the algorithm of selection.
+
+{p 4 8 2}{cmd:kernel} defines a kernel for the first scale, defined as the first # items of {it:varlist}.
+
+{p 4 8 2}{cmd:c} defines the level of the threshold {it:c}. The level of {it:c} is fixed, by default, at 0.3.
+
+{p 4 8 2}{cmd:notest} selects the scales whithout tests among the Loevinger H coefficient (Hjk>0): the new item with the maximal value for Hj>c is always selected.
+
+{p 4 8 2}{cmd:p} defines the significance level for the tests. The level of {it:p} is fixed, by default, at 0.05.
+
+{p 4 8 2}{cmd:pairwise} does no more delete all the individuals who have one or more missing values among all the items of {it:varlist} but, only these ones who have, for each pair of items, one or more missing values to these two items.
+
+{p 4 8 2}{cmd:minvalue} defines the minimum value of the coefficient Hjk for a pair of item composing a scale. This minimal value is fixed by default to 0.
+
+{p 4 8 2}{cmd:nobon} does no more correct the significance level of the test by the Bonferroni correction.
+
+{p 4 8 2}{cmd:noadjust} approximates the tests statistics like the MSP program (Molenaar et al. (2000)).
+
+{title:Remarks}
+
+{p 4 8 2}For detailed informations on the Mokken scale procedure, see Mokken (1971), Hemker and al. (1995) or the manual of the MSP software (2000).
+
+{p 4 8 2}{cmd:msp} runs with dichotomous or polytomous items.
+
+{p 4 8 2}{cmd:msp} necessitates the program {help loevH} to compute.
+
+{title:Results}
+
+{p 4 8 2}{it:r(dim)} saves the number of built scales.
+
+{p 4 8 2}{it:r(selection)} saves a vector which contains, for each item, the scale where it is selected (0 if the item is unselected).
+
+{p 4 8 2}{it:r(H#)} saves the Loevinger's H coefficient of the #th scale.
+
+{p 4 8 2}{it:r(nbitems#)} saves the number of items selected in the #th scale.
+
+{p 4 8 2}{it:r(scale#)} saves the names of the items selected in the #th scale.
+
+{p 4 8 2}{it:r(scalenum#)} saves the numbers of the items selected in the #th scale.
+
+{title:Example}
+
+ {inp:. msp itemA1-itemA7}
+
+ {inp:. msp itemA* itemB* , nodetails kernel(2)}
+
+ {inp:. msp item* , c(0.2) nob pairwise}
+
+
+{title:References}
+
+{p 4 8 2}Hemker B. T., Sijtsma K. and Molenaar I. W., Selection of unidimensional scales from a multidimensional item bank in the polytomous Mokken IRT
+model, {it: Applied Psychological Measurement}, vol.19(4), 1995, pp. 337-352.
+
+{p 4 8 2}Mokken R. J., A theory and procedure of scale analysis. New-York/Berlin : De Guyter, 1971.
+
+{p 4 8 2}Molenaar I. W., Sijtsma K. and Boer P. User's manual of MSP5 for Windows. Groningen (The Netherlands): iec ProGAMMA, 2000.
+
+{title:Also see}
+
+{p 4 13 2} help for {help loevh} (if installed), help for {help mokken} (if installed)
+
+{title:Author}
+
+{p 4 8 2} Jean-Benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences -
+Department of Biostatistics. 1, rue Gaston Veil - BP 53508 - 44035 Nantes Cedex 1 - FRANCE. You can contact the
+author at
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}
+and visit the websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
diff --git a/Modules/ado/personal/m/msp82.ado b/Modules/ado/personal/m/msp82.ado
new file mode 100644
index 0000000..fa76381
--- /dev/null
+++ b/Modules/ado/personal/m/msp82.ado
@@ -0,0 +1,516 @@
+*! Version 8.2 April 30, 2014
+*! Jean-Benoit Hardouin, Bastien Perrot
+************************************************************************************************************
+* Stata program : msp
+* Mokken Scale Procedure
+* Release 8.2: (April 30, 2014) [Jean-Benoit Hardouin, Bastien Perrot] /*HTML option, correction of a bug when kernel=1, IF option */
+*
+* Historic :
+* Version 1 - lose version (August 20, 2002) [Jean-Benoit Hardouin]
+* Version 2 (September 25, 2002) [Jean-Benoit Hardouin]
+* Version 3 (December 1, 2003) [Jean-Benoit Hardouin]
+* Version 4 (January 20, 2004) [Jean-Benoit Hardouin]
+* Version 5 (March 22, 2004) [Jean-Benoit Hardouin]
+* Version 5.1 (May 1st, 2004) [Jean-Benoit Hardouin]
+* Version 6 : (July 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.1 : (September 5, 2004) [Jean-Benoit Hardouin]
+* Version 6.2 : (January 22, 2006) [Jean-Benoit Hardouin] /*English improvements*/
+* Release 6.3 : (March 20, 2006) [Jean-Benoit Hardouin] /*A bug with temporary files */
+* Release 6.6: (Februar 16, 2007) [Jean-Benoit Hardouin] /*Tests of the loevinger H indices, adaptation for loevH 6.6, noadjust option, improvements*/
+* Release 8: (December 8, 2010) [Jean-Benoit Hardouin] /*Adaptation for loevh version 8*/
+* Release 8.1: (December 19, 2012) [Jean-Benoit Hardouin] /*correction of a bug with the notest option*/
+* Release 8.1.1: (September 26, 2013) [Jean-Benoit Hardouin] /*correction of a rare bug */
+* Release 8.2: (April 30, 2014) [Jean-Benoit Hardouin, Bastien Perrot] /*HTML option, correction of a bug when kernel=1, IF option */
+*
+* Jean-benoit Hardouin, University of Nantes - Faculty of Pharmaceutical Sciences
+* Department of Biostatistics - France
+* jean-benoit.hardouin@anaqol.org
+*
+* The Stata program loevh is needed. It can be downloaded on http://www.anaqol.org
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2002-2007, 2010, 2012 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 msp82 , rclass
+version 7.0
+syntax varlist(min=2 numeric) [if] [,c(real 0.3) noDETails KERnel(integer 0) noTEst p(real 0.05) PAIRWise MINValue(real 0) noBon noADJust HTML(string)]
+local nbitems : word count `varlist'
+tokenize `varlist'
+tempfile mspfile
+qui save "`mspfile'"
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`pairwise'"=="" {
+ forvalues j=1/`nbitems' {
+ qui drop if ``j''==.
+ }
+}
+if "`test'"!="" {
+ local p=1
+ local minvalue=-99
+ local bon nobon
+}
+
+if "`html'"!="" {
+ di ""
+ di ""
+}
+
+
+qui loevh `varlist',`pairwise' pair `adjust' html(`html')
+tempname pvalHjk loevHjk loevHjks loevHj loevH Hjk stopscale stop dim plusitems Hjkmax Hjmax Hmax nbitemsel
+matrix `loevHjk'=r(loevHjk)
+matrix `loevHjks'=r(loevHjk)
+matrix `pvalHjk'=r(pvalHjk)
+matrix `loevHj'=r(loevHj)
+scalar `loevH'=r(loevH)
+matrix `Hjk'=`loevHjk'
+
+matrix define `dim'=J(1,`nbitems',0)
+
+global scale=0
+scalar `stopscale'=0
+
+while `stopscale'!=1 { /*WHILE IT IS POSSIBLE TO CONSTRUCT SCALES*/
+ global scale=$scale+1
+ local dimension=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp'
+ global `scaletmpnum'
+ if "`details'"=="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+
+/**********************************************************************************************************
+BEGINING OF THE INITIAL STEP
+**********************************************************************************************************/
+
+/****NONE KERNEL OR NOT THE FIRST SCALE****/
+ if $scale>1|`kernel'==0 {
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ local nbitemsbon=0
+ forvalues j1=1/`nbitems' {
+ if `dim'[1,`j1']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ if `nbitemsbon'<=1 {
+ local nbitemsbon=2
+ }
+ local kbon=`nbitemsbon'*(`nbitemsbon'-1)/2
+ if "`bon'"==""&"`test'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`test'"!="" {
+ local pbon=1
+ local p=1
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j1=1/`nbitems' { /*WE SEARCH THE BEST PAIR OF ITEMS*/
+ if `dim'[1,`j1']==0 {
+ scalar `plusitems'=1
+ forvalues j2=`=`j1'+1'/`nbitems' {
+ if `dim'[1,`j2']==0 {
+ if `Hjk'[`j1',`j2']>`Hjkmax'&`pvalHjk'[`j1',`j2']<=`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j1',`j2']
+ global j1max=`j1'
+ global j2max=`j2'
+ }
+ }
+ }
+ }
+ }
+
+ if `Hjkmax'==-99 { /*IF NONE PAIR OF ITEM VERIFY Hjk>0*/
+ if `plusitems'==0 {
+ if "`details'"=="" {
+ if "`html" == "" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ else {
+ di in green "There is no more items remaining."
+ }
+ }
+ }
+ else {
+ if "`details'"=="" {
+ if "`html" == "" {
+ di as green "{p}None pair of items has a significantly positive Hjk coefficient.{p_end}"
+ }
+ else {
+ di as green "None pair of items has a significantly positive Hjk coefficient."
+ }
+ }
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE PAIR OF ITEM VERIFY Hjk>c*/
+ if $scale==1 {
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di as green "{p}None pair of items verifies Hjk>`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ else {
+ di as green "None pair of items verifies Hjk>`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed."
+ }
+ }
+ }
+ else {
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di as green "{p}None new scale can be constructed because none pair of items, among the remaining items, verifies Hjk>`c'{p_end}"
+ }
+ else {
+ di as green "None new scale can be constructed because none pair of items, among the remaining items, verifies Hjk>`c'"
+ }
+ }
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /*IF THERE IS AT LEAST ONE PAIR OF ITEM WHO VERIFY Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j1max' `$j2max'"
+ global `scaletmpnum' "$j1max $j2max"
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di in green "{p}The two first items selected in the scale " in yellow "$scale " in green "are " in yellow "`$j1max' " in green "and " in yellow "`$j2max'" in green " (Hjk=" in yellow %6.4f `Hjkmax' in green "){p_end}"
+ }
+ else {
+ di in green "The two first items selected in the scale " in yellow "$scale " in green "are " in yellow "`$j1max' " in green "and " in yellow "`$j2max'" in green " (Hjk=" in yellow %6.4f `Hjkmax' in green ")"
+ }
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE TWO SELECTED ITEMS*/
+ if ((`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ if ((`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF ONE ITEM****/
+ if $scale==1&`kernel'==1 {
+ global j1max=1
+ scalar `plusitems'=0
+ scalar `Hjkmax'=-99
+ if "`details'"=="" {
+ di in green "The item " in yellow "`1'" in green " is the kernel of the first scale"
+ }
+ local nbitemsbon=0
+ forvalues i=2/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE ITEM OF THE KERNEL*/
+ if ((`loevHjks'[`i',$j1max]<`minvalue'|`pvalHjk'[`i',$j1max]>`p')&`dim'[1,`i']==0) {
+ matrix `dim'[1,`i']=-1
+ }
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`nbitemsbon'
+ if "`bon'"==""&"`test'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=2/`nbitems' {/*WE SEARCH THE BEST ITEM TO SELECT WITH THE KERNEL*/
+ if `Hjk'[`j2',1]>`Hjkmax'&`pvalHjk'[`j2',1]<`pbon' {
+ scalar `Hjkmax'=`Hjk'[`j2',1]
+ global j2max=`j2'
+ }
+ }
+
+ if `Hjkmax'==-99 {/*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk<*/
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di as green "{p}None item associated to the item " in yellow "$j1 " in green "allows obtaining a significantly positive value for the Hjk coefficient.{p_end}"
+ }
+ else {
+ di as green "None item associated to the item " in yellow "$j1 " in green "allows obtaining a significantly positive value for the Hjk coefficient."
+ }
+ }
+ continue, break
+ }
+
+ if `Hjkmax'<=`c' { /*IF NONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk`c', the maximum value of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed.{p_end}"
+ }
+ else {
+ di "None index Hjk associated to the item " in yellow "$j1 " in green "verifies Hjk>`c', the maximum value"
+ di "of these coefficients is " %6.4f `Hjkmax' ". None scale can be constructed."
+ }
+ }
+ scalar `stop'=1
+ scalar `stopscale'=1
+ continue, break
+ }
+ else { /* IF AT LEAST ONE ITEM CAN BE SELECTED WITH THE KERNEL Hjk>c*/
+ matrix `dim'[1,$j1max]=$scale
+ matrix `dim'[1,$j2max]=$scale
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ global `scaletmp' "`$j2max' `$j1max'"
+ global `scaletmpnum' "$j2max $j1max"
+ if "`details'"=="" {
+ di in green "The second item selected in the first scale is " in yellow "`$j2max' " in green "(Hjk=" in yellow %6.4f `Hjkmax' in green")"
+ }
+ scalar `nbitemsel'=2
+ }
+ forvalues i=1/`nbitems' { /*WE EXCLUDE THE ITEM WHICH VERIFY Hjk<0 WITH THE NEW SELECTED ITEM*/
+ if (`loevHjks'[`i',$j2max]<`minvalue'|`pvalHjk'[`i',$j2max]>`p')&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+/****FIRST SCALE, KERNEL OF SEVERAL ITEMS****/
+ if $scale==1&`kernel'>=2 {
+ global scale1
+ local scalenum1
+ local kbon=1
+ local pbon=`p'
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+ forvalues j2=1/`kernel' {
+ global scale1 ``j2'' $scale1
+ global scalenum1 $scalenum1 `j2'
+ matrix `dim'[1,`j2']=1
+ }
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di in green "{p}The kernel of the first scale is composed of the items " in yellow "$scale1{p_end}"
+ }
+ else {
+ di in green "The kernel of the first scale is composed of the items " in yellow "$scale1"
+ }
+ }
+ scalar `nbitemsel'=`kernel'
+ forvalues j=1/`kernel' {
+ forvalues i=1/`nbitems' { /* WE EXCLUDE THE ITEMS WHICH VERIFY Hjk<0 WITH THE ITEMS OF THE KERNEL*/
+ if (`loevHjks'[`i',`j']<`minvalue'|`pvalHjk'[`i',`j']>`p')&`dim'[1,`i']==0 {
+ matrix `dim'[1,`i']=-1
+ }
+ }
+ }
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ local excluded `excluded' ``i''
+ matrix `dim'[1,`i']=-2
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ scalar `stop'=0
+
+/**********************************************************************************************************
+END OF THE INITIAL STEP
+**********************************************************************************************************/
+
+ while `stop'!=1 { /*WHILE THE PROCEDURE TO CONSTRUCT THE ACTUAL SCALE IS NOT STOPPED*/
+
+ scalar `Hjmax'=-99
+ scalar `Hmax'=-99
+ global jmax=0
+
+ global stopmax=0
+ local nbitemsbon=0
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==0 {
+ local nbitemsbon=`nbitemsbon'+1
+ }
+ }
+ local kbon=`kbon'+`nbitemsbon'
+ if "`bon'"=="" {
+ local pbon=`p'/`kbon'
+ }
+ else {
+ local pbon=`p'
+ }
+ if "`details'"==""&"`test'"=="" {
+ di in green "Significance level: " in yellow %8.6f `pbon'
+ }
+
+
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {/*IF THE ITEM J0 IS UNSELECTED*/
+ global stopmax=1
+ local scaletmp="scale$scale"
+ local scaletmpnum="scalenum$scale"
+ qui loevh ``j0'' $`scaletmp' ,`pairwise' pair `adjust' html(`html')
+ tempname pvalHj0
+ matrix `pvalHj0'=r(pvalHj)
+ scalar `pvalHj0'=`pvalHj0'[1,1]
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ local nbitsc : word count $`scaletmp'
+ local nbitsc=`nbitsc'+1
+ if `loevHj'[1,1]>`c'&`pvalHj0'<`pbon' {/*IF THE ITEM J0 CAN BE SELECTED*/
+ if `loevH'>`Hmax' {/*AND IF IT IS THE BEST ITEM (COMPARED TO THE PRECEEDING ITEMS)*/
+ scalar `Hjmax'=`loevHj'[1,1]
+ scalar `Hmax'=`loevH'
+ global j="``j0''"
+ global j0=`j0'
+ }
+ }
+ }
+ }
+
+ if $stopmax==1&`Hjmax'==-99 { /*IF THERE IS ITEMS REMAINING BUT NONE OF THEM CAN BE SELECTED*/
+
+ if "`details'"=="" {
+ if "`html'" == "" {
+ di in green "{p}None new item can be selected in the scale $scale because all the Hj are less than `c' or none new item has all the related Hjk coefficients significantly greater than 0{p_end}."
+ }
+ else {
+ di "None new item can be selected in the scale $scale because all the Hj are less than `c' or none new item"
+ di "has all the related Hjk coefficients significantly greater than 0."
+ }
+ }
+ scalar `stop'=1
+ continue,break
+ }
+ if $stopmax==0 { /*IF THERE IS NO MORE ITEM REMAINING*/
+ if "`details'"=="" {
+ di in green "{p}There is no more items remaining.{p_end}"
+ }
+ scalar `stopscale'=1
+ scalar `stop'=1
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ scalar `stopscale'=0
+ }
+ }
+ *global scale=$scale-1
+ continue,break
+ }
+
+
+ if `stop'!=1 { /*IF THE PROCEDURE IS NOT STOPPED*/
+ matrix `dim'[1,$j0]=$scale
+ local `scaletmp'="scale$scale"
+ local `scaletmpnum'="scalenum$scale"
+ global `scaletmp' $j $`scaletmp'
+ global `scaletmpnum' $j0 $`scaletmpnum'
+ if "`details'"=="" {
+ di in green "The item " in yellow "`$j0' " in green "is selected in the scale " in yellow "$scale" _col(50) in green "Hj=" in yellow %6.4f `Hjmax' _col(65) in green "H=" in yellow %6.4f `Hmax' ""
+ }
+ local excluded
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']==-1 {
+ matrix `dim'[1,`i']=-2
+ }
+ if `dim'[1,`i']==0 { /*WE EXCLUDE ITEMS WHO HAVE A NEGATIVE Hjk WITH THE NEW SELECTED ITEM*/
+ if `loevHjks'[`i',$j0]<`minvalue'|`pvalHjk'[`i',$j0]>`p' {
+ matrix `dim'[1,`i']=-1
+ local excluded `excluded' ``i''
+ }
+ }
+ }
+ if "`excluded'"!=""&"`details'"=="" {
+ di in green "The following items are excluded at this step: " in yellow "`excluded'"
+ }
+ }
+ }
+ di
+ local scaleencours="scale$scale"
+ local scalenumencours="scalenum$scale"
+ local nbitemscale : word count $`scaleencours'
+ return scalar nbitems`dimension'=`nbitemscale'
+ if `nbitemscale'>0 { /* IF AT LEAST TWO ITEMS HAVE BEEN SELECTED*/
+ if "`details'"!="" {
+ di
+ di in yellow "Scale: $scale"
+ di "{hline 10}"
+ }
+
+ loevh $`scaleencours',`pairwise' `adjust' html(`html')
+ matrix `loevHjk'=r(loevHjk)
+ matrix `loevHj'=r(loevHj)
+ scalar `loevH'=r(loevH)
+
+ return scalar H`dimension'=`loevH'
+ return local scale`dimension' $`scaleencours'
+ return local scalenum`dimension' $`scalenumencours'
+ local j=`nbitemscale'
+ di
+ }
+ forvalues i=1/`nbitems' {
+ if `dim'[1,`i']<0 {
+ matrix `dim'[1,`i']=0
+ }
+ }
+
+ local restnbitems=0
+ forvalues j0=1/`nbitems' {
+ if `dim'[1,`j0']==0 {
+ local restnbitems=`restnbitems'+1
+ local restitem ``j0''
+ }
+ }
+
+ if `restnbitems'==1 { /*IF THERE IS ONLY ONE ITEM REMAINING*/
+ di
+ if "`html'" == ""{
+ di in green "{p}There is only one item remaining (" in yellow "`restitem'" in green ").{p_end}"
+ }
+ else {
+ di in green "There is only one item remaining (" in yellow "`restitem'" in green ")."
+ }
+ local stopscale=1
+ return local lastitem "`restitem'"
+ }
+
+}
+
+return scalar dim=$scale
+matrix colnames `dim'=`varlist'
+return matrix selection=`dim'
+
+qui use "`mspfile'",clear
+end
diff --git a/Modules/ado/personal/n/nbmiss.ado b/Modules/ado/personal/n/nbmiss.ado
new file mode 100644
index 0000000..6e52e41
--- /dev/null
+++ b/Modules/ado/personal/n/nbmiss.ado
@@ -0,0 +1,18 @@
+program define nbmiss
+version 8.0
+syntax varlist(min=1) [, nbmiss(string)]
+
+if "`nbmiss'"=="" {
+local nbmiss nbmiss
+}
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+qui gen `nbmiss'=0
+
+forvalues i=1/`nbitems' {
+qui replace `nbmiss'=`nbmiss'+1 if ``i''==.
+}
+end
+
diff --git a/Modules/ado/personal/n/nbvalues.ado b/Modules/ado/personal/n/nbvalues.ado
new file mode 100644
index 0000000..0e44651
--- /dev/null
+++ b/Modules/ado/personal/n/nbvalues.ado
@@ -0,0 +1,15 @@
+/*version au 17 juillet 2015 : ajout de if*/
+
+capture program drop nbvalues
+program define nbvalues,rclass
+version 7.0
+syntax varlist(min=1 max=1) [if]
+
+qui tabulate `varlist' `if',matrow(nbvalues)
+
+local nrow=rowsof(nbvalues)
+
+di "la variable `varlist' contient `nrow' valeurs differentes"
+return scalar nrow=`nrow'
+end
+
diff --git a/Modules/ado/personal/n/nopalera.ado b/Modules/ado/personal/n/nopalera.ado
new file mode 100644
index 0000000..9a241d8
--- /dev/null
+++ b/Modules/ado/personal/n/nopalera.ado
@@ -0,0 +1,703 @@
+*! Version 3.2 15January2020
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* nopalera : NOPALERA algorithm
+*
+* Historic:
+* Version 1 (2015-07-20): Jean-Benoit Hardouin /*ICC; rsbynpirt module*/
+* Version 1.1 (2015-10-24): Jean-Benoit Hardouin /*NOPALERA module, ISOQOL 2015*/
+* Version 2 (2015-10-24): Jean-Benoit Hardouin /*NOPALERA module, ISOQOL 2015*/
+* Version 2.1 (2017-12-13): Jean-Benoit Hardouin /*Improvement*/
+* Version 3 (2018-07-11): Jean-Benoit Hardouin /*Improvement for paper*/
+* Version 3.1 (2019-07-24): Jean-Benoit Hardouin /*Improvement*/
+* Version 3.2 (2020-01-10): Jean-Benoit Hardouin /*outputs for simulations*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE
+* MethodS in Patients-centered outcomes and HEalth ResEarches
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program: http://www.anaqol.org
+*
+* Copyright 2015,2017-2020 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 nopalera, rclass
+version 8.0
+syntax varlist(numeric min=4) [, nobsauc nobsaabc noGraph corr(numlist) NBAUCbs(int 10) NBAABCbs(int 20) noRESTscore GRAPHBYGroup ] /*corr est la correction Ă appliquer pour corriger le RS unif*/
+
+set more off
+tempfile file1 file2 file3
+qui save `file1', replace
+preserve
+local nbitems : word count `varlist'
+qui count
+local nind=r(N)
+tokenize `varlist'
+if mod(`nbitems',2)!=0 {
+ di in red "You must indicate an even number of items"
+ exit
+}
+else {
+ local nbitems=`nbitems'/2
+}
+if "`corr'"=="" {
+ forvalues i=1/`nbitems'{
+ local corr "`corr' 0"
+ }
+}
+local listofitems1
+local listofitems2
+forvalues i=1/`nbitems' {
+ local listofitems1 `listofitems1' ``i''
+ local listofitems2 `listofitems2' ``=`i'+`nbitems'''
+}
+tempname matnopalera matAUC matAABC
+matrix `matnopalera'=J(`nbitems',3,0)
+matrix `matAUC'=J(`nbitems',4,0)
+matrix `matAABC'=J(`nbitems',4,0)
+
+
+di "NOPALERA: an algorithm to detect Response-shift at items level using non parametric IRT"
+di "Number of individuals: `nind'"
+di "Number of items: `nbitems'"
+di "Number of Boostrap replications for AUC: `nbaucbs'"
+di "Number of Boostrap replications for AABC: `nbaabcbs'"
+
+/*******************************************************************************
+Une boucle pour calculer le score, définir le score maximum par item et global
+*******************************************************************************/
+
+tempvar varscore1 varscore2
+qui gen `varscore1'=0
+qui gen `varscore2'=0
+label variable `varscore1' "Total score time 1"
+label variable `varscore2' "Total score time 2"
+local scoremax=0
+local flag=0
+
+
+local modamax=0
+
+forvalues i=1/`nbitems' {
+ local corr`i': word `i' of `corr'
+ qui replace ``=`i'+`nbitems'''=``=`i'+`nbitems'''+`corr`i''
+ qui replace `varscore1'=`varscore1'+``i''
+ qui replace `varscore2'=`varscore2'+``=`i'+`nbitems'''
+ local list1 `list1' ``i''
+ local list2 `list2' ``=`i'+`nbitems'''
+
+ qui su ``i''
+ local modamax`i'=r(max)
+ qui su ``=`i'+`nbitems'''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+}
+
+/*******************************************************************************
+On va calculer maintenant les rest-score de chaque item Ă chaque temps
+*******************************************************************************/
+
+forvalues i=1/`nbitems'{
+ tempvar rscore1``i'' rscore2``i'' vargroup1``i'' vargroup2``i'' vargroup2b``i''
+ if "`restscore'"=="" {
+ qui gen `rscore1``i'''=`varscore1'-``i''
+ qui gen `rscore2``i'''=`varscore2'-``=`i'+`nbitems'''
+ }
+ else {
+ qui gen `rscore1``i'''=`varscore1'
+ qui gen `rscore2``i'''=`varscore2'
+ }
+ qui gengroup `rscore1``i''' , new(`vargroup1``i''') det
+ local seuil1=r(list)
+ *di "rscore1 et group1 item ``i''"
+ *tab `rscore1``i''' `vargroup1``i'''
+ local seuil1 "`seuil1' max"
+ local nbseuil1: word count `seuil1'
+ qui gen `vargroup2b``i'''=`rscore2``i'''
+ local t
+ forvalues j=1/`nbseuil1' {
+ if `j'==1 {
+ local seuilmin=0
+ }
+ else {
+ local seuilmin : word `=`j'-1' of `seuil1'
+ local seuilmin=`seuilmin'+1
+ local seuilmin=`seuilmax'+1
+ }
+
+ local seuilmax : word `j' of `seuil1'
+ if "`seuilmax'"!="max" {
+ if `seuilmax'<`seuilmin' {
+ local seuilmax `seuilmin'
+ }
+ }
+ local t `t' (`seuilmin'/`seuilmax'=`j')
+ }
+ di "recode vargroup2b``i'' `t'"
+ qui recode `vargroup2b``i''' `t'
+ *di "rscore2 et group2 item ``i'' avant regroupage"
+ *tab `rscore2``i''' `vargroup2b``i'''
+ qui gengroup `vargroup2b``i''',new(`vargroup2``i''') det replace
+ local seuil2=r(list)
+ *di "rscore2 et group2 item ``i'' aprĂšs regroupage"
+ *tab `rscore2``i''' `vargroup2``i'''
+ local seuil2 "`seuil2' max"
+ *di "``i'' seuil2 : `seuil2'"
+ local nbseuil2: word count `seuil2'
+ local t
+ forvalues j=1/`nbseuil2' {
+ if `j'==1 {
+ local seuilmin=1
+ }
+ else {
+ local seuilmin : word `=`j'-1' of `seuil2'
+ local seuilmin=`seuilmin'+1
+ local seuilmin=`seuilmax'+1
+ }
+ local seuilmax : word `j' of `seuil1'
+ if "`seuilmax'"!="max" {
+ if `seuilmax'<`seuilmin' {
+ local seuilmax `seuilmin'
+ }
+ }
+ local t `t' (`seuilmin'/`seuilmax'=`j')
+ }
+ *di "recode vargroup1``i'' `t'"
+ qui recode `vargroup1``i''' `t'
+ *di "rscore1 et group1 item ``i'' aprĂšs regroupage"
+ *tab `rscore1``i''' `vargroup1``i'''
+
+}
+*tab `vargroup1itemA1' `vargroup2itemA1'
+*exit
+qui save `file3', replace
+
+*exit
+/*******************************************************************************
+Quelques tests de conformité
+*******************************************************************************/
+
+qui su `varscore1'
+local maxscore=r(max)
+qui su `varscore2'
+if `r(max)'>`maxscore' {
+ local maxscore=r(max)
+}
+forvalues i=1/`nbitems' {
+ qui su `vargroup1``i'''
+ local maxgroup``i''=r(max)
+}
+
+
+/* sauvegarde des données */
+tempfile rsbynpirtfile rsbynpirtfile1 rsbynpirtfile2
+tempvar score
+qui save `rsbynpirtfile', replace
+
+/*******************************************************************************
+Représentation graphique des tracelines
+*******************************************************************************/
+
+
+forvalues i=1/`nbitems' {
+ tempfile file4
+ tempname mat``i''
+ matrix `mat``i'''=J(`=`maxgroup``i'''+2',9,0)
+ forvalues j=1/`maxgroup``i''' {
+ local k=`j'+1
+ matrix `mat``i'''[`k',1]=`j'
+ *tab `vargroup1``i
+ qui count if `vargroup1``i'''==`j'
+ if `r(N)'==0 {
+ local bsauc nobsauc
+ local bsaabc nobsaabc
+ matrix `mat``i'''[`k',2]=.
+ matrix `mat``i'''[`k',4]=.
+ matrix `mat``i'''[`k',6]=.
+ }
+ else {
+ qui su ``i'' if `vargroup1``i'''==`j'
+ matrix `mat``i'''[`k',2]=`r(mean)'
+ matrix `mat``i'''[`k',4]=`r(N)'
+ qui su `rscore1``i''' if `vargroup1``i'''==`j'
+ matrix `mat``i'''[`k',6]=`r(mean)'
+ }
+ local temp=`i'+`nbitems'
+ qui count if `vargroup2``i'''==`j'
+ if `r(N)'==0 {
+ local bsauc nobsauc
+ local bsaabc nobsaabc
+ matrix `mat``i'''[`k',3]=.
+ matrix `mat``i'''[`k',5]=.
+ matrix `mat``i'''[`k',7]=.
+ }
+ else {
+ qui su ``temp'' if `vargroup2``i'''==`j'
+ matrix `mat``i'''[`k',3]=`r(mean)'
+ matrix `mat``i'''[`k',5]=`r(N)'
+ qui su `rscore2``i''' if `vargroup2``i'''==`j'
+ matrix `mat``i'''[`k',7]=`r(mean)'
+ }
+ }
+ local j=`maxgroup``i'''+2
+ matrix `mat``i'''[`j',1]=`maxgroup``i'''+1 /*numero du group*/
+ matrix `mat``i'''[`j',2]=`modamax`i'' /*mean item 1*/
+ matrix `mat``i'''[`j',3]=`modamax`i'' /*mean item 2*/
+ matrix `mat``i'''[`j',4]=0 /*frequency 1*/
+ matrix `mat``i'''[`j',5]=0 /*frequency 2*/
+ if "`restscore'"=="" {
+ local maxi=`scoremax'-`modamax`i''
+ }
+ else {
+ local maxi=`scoremax'
+ }
+ matrix `mat``i'''[`j',6]=`maxi' /*mean rest-score 1*/
+ matrix `mat``i'''[`j',7]=`maxi' /*mean rest-score 2*/
+ label values `vargroup1``i''' lblvarscore``i''
+ qui sort `vargroup1``i''' `vargroup2``i'''
+ qui save `file4',replace
+ forvalues j=1/`maxgroup``i''' {
+ qui count if `vargroup1``i'''==`j'
+ local n1=r(N)
+ qui su `rscore1``i''' if `vargroup1``i'''==`j'
+ local min1=r(min)
+ local max1=r(max)
+ qui count if `vargroup2``i'''==`j'
+ local n2=r(N)
+ qui su `rscore2``i''' if `vargroup2``i'''==`j'
+ local min2=r(min)
+ local max2=r(max)
+ local min=min(`min1',`min2')
+ local max=max(`max1',`max2')
+ label define lblvarscore``i'' `j' `""Scores `min'/`max'" "(n1=`n1';n2=`n2')""', add
+ }
+
+ label define lblvarscore``i'' 0 "Min", add
+ label define lblvarscore``i'' `=`maxgroup``i'''+1' "Max", add
+ qui drop _all
+ qui svmat `mat``i'''
+ qui rename `mat``i'''1 group
+ qui rename `mat``i'''2 e1
+ qui rename `mat``i'''3 e2
+ qui rename `mat``i'''6 rs1
+ qui rename `mat``i'''7 rs2
+ qui sort group
+ label values group lblvarscore``i''
+ label variable group "Groups of scores"
+ if "`graph'"=="" {
+ if "`graphbygroup'"!="" {
+ graph twoway (line e1 group ) (line e2 group ), title("Traceline of item ``i''") xtitle("") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`=`maxgroup``i'''+1',valuelabel labsize(small) /*alternate*/) name("``i''", replace) legend(off)
+ }
+ else {
+ if "`restscore'"=="" {
+ local xtitle="Rest-score"
+ qui su rs1
+ local max=r(max)
+ qui su rs2
+ if `r(max)'>`max' {
+ local max=r(max)
+ }
+
+ }
+ else {
+ local xtitle="Score"
+ local max `maxscore'
+ }
+ graph twoway (line e1 rs1 ) (line e2 rs2 ), title("Traceline of item ``i''") xtitle("`xtitle'") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`max',valuelabel labsize(small) /*alternate*/) name("auc``i''", replace) legend(off)
+ }
+ }
+ qui use `file4', replace
+}
+
+/*******************************************************************************
+Calcul des AUC
+*******************************************************************************/
+
+local tests
+forvalues i=1/`nbitems' {
+ local auc1`i'=0
+ local auc2`i'=0
+ forvalues g=1/`=`maxgroup``i'''+1' {
+ local k=`g'+1
+ local auc=(`mat``i'''[`g',2]+`mat``i'''[`k',2])/2*(`mat``i'''[`k',6]-`mat``i'''[`g',6])
+ local auc1`i'=`auc1`i''+`auc'
+ matrix `mat``i'''[`k',8]= `auc'
+ local auc=(`mat``i'''[`g',3]+`mat``i'''[`k',3])/2*(`mat``i'''[`k',7]-`mat``i'''[`g',7])
+ local auc2`i'=`auc2`i''+`auc'
+ matrix `mat``i'''[`k',9]= `auc'
+ }
+ local AUC``i''=`auc1`i''
+ local AUC``=`i'+`nbitems'''=`auc2`i''
+ local diffAUC``i''=`=`AUC``i'''-`AUC``=`i'+`nbitems'''''
+ return scalar AUC``i''=`auc1`i''
+ return scalar AUC``=`i'+`nbitems'''=`auc2`i''
+ matrix `matAUC'[`i',1]=`AUC``i'''
+ matrix `matAUC'[`i',2]=`AUC``=`i'+`nbitems''''
+ matrix `matAUC'[`i',3]=`diffAUC``i'''
+
+ local tests `tests' b``i''=(r(AUC``=`i'+`nbitems''')-r(AUC``i''))
+}
+
+/*******************************************************************************
+Calcul des standard errors des AUC par bootstrap
+*******************************************************************************/
+
+*local abc=0
+if "`bsauc'"=="" {
+ *di "on lance le bootstrap sur les AUC"
+ *set trace on
+ tempfile file2
+ qui save `file2', replace
+ qui use `file1', clear
+ capture qui bootstrap `tests' , rep(`nbaucbs') nol noh nodots : nopalera `varlist', nograph `restscore' nobsaabc nobsauc
+ local n=1
+ while (_rc!=0&`n'<10) {
+ di "`n'. The boostrap to obtain IC of the AUC has not been correctly performed, it is run again"
+ local ++n
+ capture qui bootstrap `tests' , rep(`nbaucbs') nol noh nodots : nopalera `varlist', nograph `restscore' nobsaabc nobsauc
+ }
+ tempname mbootstrap
+ matrix `mbootstrap'=r(table)
+ qui use `file2', clear
+
+ /*Création de la matrice p qui va permettre de décaler les ICC*/
+ tempname p
+ matrix `p'=J(`=(`scoremax'+1)*(`nbitems'+1)',`=`nbitems'*3+1',.)
+ forvalues s=0/`scoremax' {
+ matrix `p'[`=`s'+1',1]=`s'
+ forvalues i=1/`nbitems' {
+ matrix `p'[`=`s'+1',`=3*`i'-1']=`s'
+ }
+ }
+ forvalues i=1/`nbitems' {
+ forvalues s=0/`scoremax' {
+ qui su ``i'' if `varscore1'==`s'
+ matrix `p'[`=`s'+1',`=3*`i'']=r(mean)
+ }
+ forvalues s=0/`scoremax' {
+ qui su ``=`i'+`nbitems''' if `varscore2'==`s'
+ if `mbootstrap'[4,`i']>=0.05 {
+ matrix `p'[`=`s'+1',`=3*`i'+1']=r(mean)
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ if `nind'/`scoremax'>20 {
+ local prec=0.5
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'-1']=round(`s'+`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'+1']=r(mean)
+ }
+ }
+ }
+ di
+ di "Research of uniform recalibration at item-level"
+ di
+ di "{hline 105}"
+ di _col(45) "Bootstrap" _col(78) " Normal-based"
+ di "Items" _col(18) "AUC t1" _col(28) "AUC t2" _col(38) "VarAUC" _col(45) "Std. Err." _col(63) "z" _col(70) "P>|z|" _col(78) "[95% Conf. Int.]" _col(96) "Correction"
+ di "{hline 105}"
+ forvalues i=1/`nbitems' {
+ local corr``i''=round(`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ di "``i''/``=`i'+`nbitems'''" _col(19) %5.2f `AUC``i''' _col(29) %5.2f `AUC``=`i'+`nbitems'''' _col(39) %5.2f `diffAUC``i''' _col(49) %5.2f `mbootstrap'[2,`i'] _col(59) %5.2f `mbootstrap'[3,`i'] _col(69) %5.4f `mbootstrap'[4,`i'] _col(79) %5.2f `mbootstrap'[5,`i'] _col(89) %5.2f `mbootstrap'[6,`i'] _col(100) %6.2f `corr``i'''
+ matrix `matAUC'[`i',4]=`mbootstrap'[2,`i']
+ }
+ di "{hline 105}"
+ local abc=1
+}
+else {
+ *di "pas de bootstrap AUC"
+ di
+ di "Research of uniform recalibration at item-level"
+ di
+ di "{hline 105}"
+ di "Items" _col(48) "AUC t1" _col(58) "AUC t2"
+ di "{hline 105}"
+ forvalues i=1/`nbitems' {
+* local corr``i''=round(`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ di "``i''/``=`i'+`nbitems'''" _col(49) %5.2f `AUC``i''' _col(59) %5.2f `AUC``=`i'+`nbitems''''
+ }
+ di "{hline 105}"
+ local abc=1
+}
+
+*di "abc:`abc' bsAUC : `bsauc'"
+*return matrix AUC=`matAUC'
+
+/*******************************************************************************
+Calcul des AABC et de leurs intervalles de confiance par boostrap
+*******************************************************************************/
+*set trace on
+if `abc'==1 {
+ *di "on lance les AABC"
+ local testsb
+ forvalues i=1/`nbitems' {
+ if "`bsauc'"!="" { /*si pas de bootstrap pour AUC*/
+ *di "m1"
+ local sigAUC``i''=0
+ local rdiffAUC``i''=0
+ }
+ else if `mbootstrap'[4,`i']<0.05 { /* si bootstrap et significatif*/
+ *di "m2"
+ local sigAUC``i''=1
+ local rdiffAUC``i''=-`corr``i'''
+ di "The item ``i'' traceline is corrected of `corr``i'''"
+ }
+ else { /* si bootstrap et NS*/
+ *di "m3"
+ local sigAUC``i''=0
+ local rdiffAUC``i''=0
+ }
+ tempname mat2``i''
+ local nbl=`=`maxgroup``i'''*4+7'
+ matrix `mat2``i'''=J(`nbl',4,.)
+ matrix `mat2``i'''[1,2]=0
+ matrix `mat2``i'''[1,3]=0
+ matrix `mat2``i'''[`nbl',2]=`modamax`i''
+ matrix `mat2``i'''[`nbl',3]=`modamax`i''
+ local col1=1
+ local col2=1
+ local line=1
+ while (`line'<=`=`maxgroup``i'''*4+7') {
+ local t1=`mat``i'''[`col1',6]
+ local t2=`mat``i'''[`col2',7]-`rdiffAUC``i'''
+ local m2=`mat``i'''[`col1',2]
+ local m3=`mat``i'''[`col2',3]
+ if (`t1'<`t2'|(`t1'==`t2'&`m2'<`m3')) {
+ *di "m2 car `m2'<`m3'"
+ matrix `mat2``i'''[`line',1]=`t1'
+ matrix `mat2``i'''[`line',2]=`mat``i'''[`col1',2]
+ local ++col1
+ }
+ else {
+ *di "m3 car `m2'>`m3'"
+ matrix `mat2``i'''[`line',1]=`t2'
+ matrix `mat2``i'''[`line',3]=`mat``i'''[`col2',3]
+ local ++col2
+ }
+ local line=`line'+2
+ }
+ *matrix list `mat2``i'''
+ local j=1
+ while (`j'<=`nbl') {
+ foreach c in 2 3 {
+ if `mat2``i'''[`j',`c']==. {
+ local prec=`j'-2
+ local m=`mat2``i'''[`prec',`c']
+ while (`m'==.&`prec'>=0) {
+ local prec=`prec'-2
+ local m=`mat2``i'''[`prec',`c']
+ *di "prec:`prec' m: `m'"
+ }
+ local suiv=`j'+2
+ local m=`mat2``i'''[`suiv',`c']
+ while (`m'==.&`suiv'<=`nbl') {
+ local suiv=`suiv'+2
+ local m=`mat2``i'''[`suiv',`c']
+ *di "suiv:`suiv' m: `m'"
+ }
+ local yprec=`mat2``i'''[`prec',`c']
+ local ysuiv=`mat2``i'''[`suiv',`c']
+ local xprec=`mat2``i'''[`prec',1]
+ local xsuiv=`mat2``i'''[`suiv',1]
+ local x=`mat2``i'''[`j',1]
+ if (`xsuiv'!=`xprec') {
+ *di "matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')"
+ matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')
+ }
+ else {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ }
+ }
+ local j=`j'+2
+ }
+ local j=2
+ *matrix list `mat2``i'''
+ while (`j'<`nbl') {
+ local prec=`j'-1
+ local suiv=`j'+1
+ local sign=(`mat2``i'''[`prec',2]-`mat2``i'''[`prec',3])*(`mat2``i'''[`suiv',2]-`mat2``i'''[`suiv',3])
+ *di "item ``i'', ligne `j', sign `sign'"
+ if (`sign'<0&`sign'!=.) {
+ local p1=(`mat2``i'''[`suiv',2]-`mat2``i'''[`prec',2])/(`mat2``i'''[`suiv',1]-`mat2``i'''[`prec',1])
+ local p2=(`mat2``i'''[`suiv',3]-`mat2``i'''[`prec',3])/(`mat2``i'''[`suiv',1]-`mat2``i'''[`prec',1])
+ if (`p1'==`p2') {
+ local cint=`mat2``i'''[`prec',1]
+ }
+ else {
+ local cint=`mat2``i'''[`prec',1]+(`mat2``i'''[`prec',3]-`mat2``i'''[`prec',2])/(`p1'-`p2')
+ }
+ matrix `mat2``i'''[`j',1]=`cint'
+ foreach c in 2 3 {
+ local yprec=`mat2``i'''[`prec',`c']
+ local ysuiv=`mat2``i'''[`suiv',`c']
+ local xprec=`mat2``i'''[`prec',1]
+ local xsuiv=`mat2``i'''[`suiv',1]
+ local x=`cint'
+ if (`xsuiv'==`xprec') {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ else {
+ *di "matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')"
+ matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')
+ }
+ }
+ }
+ else {
+ local prec=`j'-1
+ forvalues c=1/3 {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ }
+ local j=`j'+2
+ }
+ *matrix list `mat2``i'''
+ local aabc``i''=0
+ *set trace on
+ forvalues j=2/`nbl' {
+ local prec=`j'-1
+ local x=`mat2``i'''[`j',1]
+ local xprec=`mat2``i'''[`prec',1]
+ local y2=`mat2``i'''[`j',2]
+ local y3=`mat2``i'''[`j',3]
+ local yprec2=`mat2``i'''[`prec',2]
+ local yprec3=`mat2``i'''[`prec',3]
+ local aabc=(abs(`y2'-`y3')+abs(`yprec2'-`yprec3'))/2*abs(`x'-`xprec')
+ matrix `mat2``i'''[`j',4]=`aabc'
+ local aabc``i''=`aabc``i'''+`aabc'
+ }
+ return scalar AABC``i''=`aabc``i'''
+ matrix `matAABC'[`i',1]=`aabc``i'''
+ *set trace off
+
+ local testsb `testsb' c``i''=r(AABC``i'')
+ *matrix list `mat2``i'''
+ *di "return scalar AABC``i''=`aabc``i'''"
+ *matrix list `mat2``i'''
+ }
+ *set trace on
+ if "`bsaabc'"=="" {
+ *di "on lance le bootstrap AABC"
+ tempfile file3
+ qui save `file3', replace
+ qui use `file1', clear
+ *di "bootstrap `testsb' , rep(`nbbootstrap') nol noh nodots saving(C:\Users\jean-\Documents\tmp\essai.dta, replace) : nopalera `varlist', fin nograph `restscore' nobsauc nobsaabc "
+ *set trace on
+ *set tracedepth 2
+ tempfile filebsaabc
+ *di "hello c'est l'heure du BS"
+ *qui bootstrap `testsb' , rep(`nbaabcbs') nol noh nodots saving("`filebsaabc'", replace) trace : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ capture qui bootstrap `testsb' , rep(`nbaabcbs') saving("`filebsaabc'", replace) : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ local n=1
+ while (_rc!=0&`n'<50) {
+ di "`n'. The boostrap to obtain IC of the AABC has not been correctly performed, it is run again"
+ local ++n
+ capture qui bootstrap `testsb' , rep(`nbaabcbs') saving("`filebsaabc'", replace) : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ }
+ *return list
+ tempname mbootstrapb
+ matrix `mbootstrapb'=r(table)
+ *di "MATRIX mbootstrapb `mbootstrapb'"
+ *matrix list `mbootstrapb'
+ qui use "`filebsaabc'", replace
+ *su
+ local thres=`nbaabcbs'-ceil(`nbaabcbs'/20)
+ forvalues i=1/`nbitems' {
+ sort c``i''
+ qui su c``i'' in `thres'
+ local upper``i''=r(mean)
+ *di "Upper ``i'' : `upper``i'''"
+ }
+ di
+ di "Research of non-uniform recalibration at item-level"
+ di
+ di "{hline 103}"
+ di _col(36) "Bootstrap" _col(56) "Uniform" _col(72) "Non-uniform"
+ di "Items" _col(23) "AABC" _col(29) "[95% Conf. Int.]" _col(50) "Recalibration" _col(70) "Recalibration" _col(88) "Reprioritization"
+ di "{hline 103}"
+ forvalues i=1/`nbitems' {
+ local xur=""
+ local xnur=""
+ local xrep=""
+ if `mbootstrap'[4,`i']<=0.05 {
+ local xur="X"
+ matrix `matnopalera'[`i',1]=1
+ }
+ if (`aabc``i'''>`upper``i'''&"`xur'"=="X") {
+ local xnur="X"
+ matrix `matnopalera'[`i',2]=1
+ }
+ if (`aabc``i'''>`upper``i'''&"`xur'"=="") {
+ local xrep="X"
+ matrix `matnopalera'[`i',3]=1
+ }
+ matrix `matAABC'[`i',2]=`upper``i'''
+
+ di "``i''/``=`i'+`nbitems'''" _col(23) %5.2f `aabc``i''' _col(36) "[" %1.0f 0 "-" %5.2f `upper``i''' "]" _col(62) "`xur'" _col(82) "`xnur'" _col(102) "`xrep'"
+ }
+ di "{hline 103}"
+ local abc=1
+ }
+ if "`graph'"=="" {
+ forvalues i=1/`nbitems' {
+ qui drop _all
+ qui svmat `mat2``i'''
+ qui rename `mat2``i'''1 score
+ qui rename `mat2``i'''2 t1
+ qui rename `mat2``i'''3 at2
+ qui sort score
+ if "`restscore'"=="" {
+ local xtitle="Rest-score"
+ qui su score
+ local max=r(max)
+ }
+ else {
+ local xtitle="Score"
+ local max `maxscore'
+ }
+ list *
+ graph twoway (line t1 score ) (line at2 score ) if score>0&score<=`maxscore', title("Traceline of item ``i''") xtitle("`xtitle'") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`max',valuelabel labsize(small) /*alternate*/) name("aabc``i''", replace) legend(off)
+ }
+ }
+}
+return matrix matnopalera=`matnopalera'
+return matrix AUC=`matAUC'
+return matrix AABC=`matAABC'
+qui restore , preserve
+end
+
+
diff --git a/Modules/ado/personal/n/nopalerav2.1.ado b/Modules/ado/personal/n/nopalerav2.1.ado
new file mode 100644
index 0000000..9685a39
--- /dev/null
+++ b/Modules/ado/personal/n/nopalerav2.1.ado
@@ -0,0 +1,322 @@
+*! Version 2.1 13December2017
+************************************************************************************************************
+* nopalera : NOPALERA algorithm
+* Version 2: October 24, 2015
+*
+* Historic:
+* Version 1 (2015-07-20): Jean-Benoit Hardouin /*ICC; rsbynpirt module*/
+* Version 1.1 (2015-10-24): Jean-Benoit Hardouin /*NOPALERA module, ISOQOL 2015*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE
+* MethodS in Patients-centered outcomes and HEalth ResEarches
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program: http://www.anaqol.org
+*
+* Copyright 2015,2017 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 nopalera, rclass
+version 8.0
+syntax varlist(numeric min=4) [, noGraph noBootstrap corr(numlist) NBBootstrap(int 10)]
+
+set more off
+tempfile file1 file3
+qui save `file1', replace
+preserve
+local nbitems : word count `varlist'
+qui count
+local nind=r(N)
+tokenize `varlist'
+if mod(`nbitems',2)!=0 {
+ di in red "You must indicate an even number of items"
+ exit
+}
+else {
+ local nbitems=`nbitems'/2
+}
+if "`corr'"=="" {
+ forvalues i=1/`nbitems'{
+ local corr "`corr' 0"
+ }
+}
+local listofitems1
+local listofitems2
+forvalues i=1/`nbitems' {
+ local listofitems1 `listofitems1' ``i''
+ local listofitems2 `listofitems2' ``=`i'+`nbitems'''
+}
+
+di "NOPALERA: an algorithm to detect Response-shift at items level using non parametric IRT"
+di "Number of individuals: `nind'"
+di "Number of items: `nbitems'"
+di "Number of Boostrap replications: `nbbootstrap'"
+
+/*******************************************************************************
+Une boucle pour calculer le score, définir le score maximum par item et global
+*******************************************************************************/
+tempvar varscore1 varscore2
+qui gen `varscore1'=0
+qui gen `varscore2'=0
+label variable `varscore1' "Total score time 1"
+label variable `varscore2' "Total score time 2"
+local scoremax=0
+local flag=0
+
+
+local modamax=0
+forvalues i=1/`nbitems' {
+ local corr`i': word `i' of `corr'
+ qui replace ``=`i'+`nbitems'''=``=`i'+`nbitems'''+`corr`i''
+ qui replace `varscore1'=`varscore1'+``i''
+ qui replace `varscore2'=`varscore2'+``=`i'+`nbitems'''
+ qui su ``i''
+ local modamax`i'=r(max)
+ qui su ``=`i'+`nbitems'''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+}
+qui save `file3', replace
+
+/*******************************************************************************
+Quelques tests de conformité
+*******************************************************************************/
+if `flag'==1 {
+ *di as error "The lower answer category of each item must be 0"
+ *exit
+}
+
+qui su `varscore1'
+local maxscore=r(max)
+qui su `varscore1'
+if `r(max)'>`maxscore' {
+ local maxscore=r(max)
+}
+
+/* sauvegarde des données */
+tempfile rsbynpirtfile rsbynpirtfile1 rsbynpirtfile2
+tempvar score
+qui save `rsbynpirtfile', replace
+
+/*On récupÚre les données des ICC au temps 1 puis au temps 2*/
+qui traces `listofitems1', nograph icc saveicc
+qui drop _all
+tempname mat1
+qui matrix `mat1'=r(matscore)
+qui svmat `mat1', names(t1item)
+forvalues i=1/`nbitems' {
+ local j: word `i' of `listofitems1'
+ qui rename t1item`i' `j'
+}
+qui rename t1item`=`nbitems'+1' `score'
+qui contract `score' `listofitems1'
+qui sort `score'
+qui save `rsbynpirtfile1', replace
+
+qui use `rsbynpirtfile', clear
+qui traces `listofitems2', nograph icc saveicc
+qui drop _all
+tempname mat2
+qui matrix `mat2'=r(matscore)
+qui svmat `mat2', names(t2item)
+
+/*puis on fait un seul fichier avec les deux jeux de données*/
+forvalues i=1/`nbitems' {
+ local j: word `i' of `listofitems2'
+ qui rename t2item`i' `j'
+}
+qui rename t2item`=`nbitems'+1' `score'
+qui contract `score' `listofitems2'
+qui sort `score'
+qui merge 1:1 `score' using `rsbynpirtfile1'
+
+/*représentation simultanée des ICC aux deux temps pour chaque item*/
+if "`graph'"=="" {
+ forvalues i=1/`nbitems' {
+ twoway (line ``i'' `score') (line ``=`i'+`nbitems''' `score'), name(``i'',replace)
+ }
+}
+qui drop if `score'==0|`score'==`scoremax'
+
+/*calcul des deux AUC pour chaque item*/
+local tests
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ local AUC``i''=r(mean)
+ local AUC``i''=(`AUC``i'''*`scoremax')
+ qui su ``=`i'+`nbitems'''
+ local AUC`=`i'+`nbitems''=r(mean)
+ local AUC`=`i'+`nbitems''=(`AUC`=`i'+`nbitems'''*`scoremax')
+ tempname diff``i''
+ gen `diff``i'''=abs(``i''-``=`i'+`nbitems''')
+ qui su `diff``i'''
+ local d``i''=`r(sum)'/(`scoremax'*`modamax`i'')*100
+ local var``i''=`r(sd)'*100
+ return scalar AUC``i''=`AUC``i'''
+ return scalar AUC``=`i'+`nbitems'''=`AUC`=`i'+`nbitems'''
+ local tests `tests' b``i''=(r(AUC``=`i'+`nbitems''')-r(AUC``i''))
+}
+
+local abc=0
+
+
+/* 10 bootstrap pour estimer les intervalles de confiance des différences entre les deux AUC*/
+if "`bootstrap'"=="" {
+ tempfile file2
+ qui save `file2', replace
+ qui use `file1', clear
+ qui bootstrap `tests' , rep(`nbbootstrap') nol noh nodots : nopalera `varlist', nograph nobootstrap
+ tempname mbootstrap
+ matrix `mbootstrap'=r(table)
+ *matrix list `mbootstrap'
+ qui use `file3', clear
+ *set trace on
+ set tracedepth 1
+
+ /*Création de la matrice p qui va permettre de décaler les ICC*/
+ tempname p
+ matrix `p'=J(`=(`scoremax'+1)*(`nbitems'+1)',`=`nbitems'*3+1',.)
+ forvalues s=0/`scoremax' {
+ matrix `p'[`=`s'+1',1]=`s'
+ forvalues i=1/`nbitems' {
+ matrix `p'[`=`s'+1',`=3*`i'-1']=`s'
+ }
+ }
+ forvalues i=1/`nbitems' {
+ forvalues s=0/`scoremax' {
+ qui su ``i'' if `varscore1'==`s'
+ matrix `p'[`=`s'+1',`=3*`i'']=r(mean)
+ }
+ forvalues s=0/`scoremax' {
+ qui su ``=`i'+`nbitems''' if `varscore2'==`s'
+ *di "qui su ``=`i'+`nbitems''' if `varscore2'==`s'"
+ if `mbootstrap'[4,`i']>=0.05 {
+ matrix `p'[`=`s'+1',`=3*`i'+1']=r(mean)
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ if `nind'/`scoremax'>20 {
+ local prec=0.5
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'-1']=round(`s'+`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'+1']=r(mean)
+ }
+ }
+ }
+ *matrix list `p'
+ *matrix list `p'
+ di
+ di "Research of uniform recalibration at item-level"
+ di
+ di "{hline 105}"
+ di _col(45) "Bootstrap" _col(78) " Normal-based"
+ di "Items" _col(18) "AUC t1" _col(28) "AUC t2" _col(38) "VarAUC" _col(45) "Std. Err." _col(63) "z" _col(70) "P>|z|" _col(78) "[95% Conf. Int.]" _col(96) "Correction"
+ di "{hline 105}"
+ forvalues i=1/`nbitems' {
+ di "``i''/``=`i'+`nbitems'''" _col(19) %5.2f `AUC``i''' _col(29) %5.2f `AUC`=`i'+`nbitems''' _col(39) %5.2f `=`AUC``i'''-`AUC`=`i'+`nbitems'''' _col(49) %5.2f `mbootstrap'[2,`i'] _col(59) %5.2f `mbootstrap'[3,`i'] _col(69) %5.4f `mbootstrap'[4,`i'] _col(79) %5.2f `mbootstrap'[5,`i'] _col(89) %5.2f `mbootstrap'[6,`i'] _col(100) %6.2f round(`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ }
+ di "{hline 105}"
+ local abc=1
+}
+if `abc'==1 {
+ drop _all
+ qui svmat `p'
+ qui rename `p'1 score
+ local testsb
+ forvalues i=1/`nbitems' {
+ qui rename `p'`=`i'*3-1' score``i''
+ qui rename `p'`=`i'*3' t1``i''
+ qui rename `p'`=`i'*3+1' t2``i''
+ /*interpolation linéaire et nouvelles ICC corrigées*/
+ qui ipolate t2``i'' score``i'' , generate(t2adj``i'')
+ forvalues j=0/`=floor(round(`mbootstrap'[1,`i']/(`modamax`i''),`prec'))' {
+ qui replace t2adj``i''=0 if score``i''==`j'&t2adj``i''==.
+ }
+ forvalues j=`=`scoremax'+floor(round(`mbootstrap'[1,`i']/(`modamax`i''),`prec'))'/`scoremax' {
+ qui replace t2adj``i''=1 if score``i''==`j'&t2adj``i''==.
+ }
+ qui gen diff``i''=abs(t2adj``i''-t1``i'')
+ qui su diff``i''
+ local ABC``i''=`r(mean)'*`scoremax'
+ return scalar ABC``i''=`ABC``i'''
+ if "`graph'"=="" {
+ qui sort score``i''
+ qui gen scoreunadj``i''=score``i''-round(`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ *twoway (line t1``i'' score``i'')(line t2``i'' score``i'')(line t2adj``i'' score``i'') ,name(``i''c,replace)
+ twoway (line t1``i'' score``i'')(line t2``i'' scoreunadj``i'')(line t2adj``i'' score``i'') ,name(``i''c,replace)
+ *di "twoway (line t1``i'' score``i'')(line t2``i'' score``i'')(line t2adj``i'' score``i'') ,name(``i''c,replace)"
+ *su
+ }
+ local testsb `testsb' c``i''=(r(ABC``i''))
+
+ }
+
+ /* 10 bootstrap pour estimer les intervalles de confiance des ABC*/
+ if "`bootstrap'"=="" {
+ tempfile file3
+ qui save `file3', replace
+ qui use `file1', clear
+ qui bootstrap `tests' , rep(`nbbootstrap') nol noh nodots : nopalera `varlist', nograph nobootstrap
+ tempname mbootstrapb
+ matrix `mbootstrapb'=r(table)
+ *matrix list `mbootstrapb'
+ di
+ di "Research of non-uniform recalibration at item-level"
+ di
+ di "{hline 77}"
+ di _col(29) "Bootstrap" _col(62) " Normal-based"
+ di "Items" _col(24) "ABC" _col(29) "Std. Err." _col(47) "z" _col(54) "P>|z|" _col(62) "[95% Conf. Int.]"
+ di "{hline 77}"
+ forvalues i=1/`nbitems' {
+ local z`i'=`ABC``i'''/`mbootstrapb'[2,`i']
+ local p`i'=2*(1-normal(abs(`z`i'')))
+ di "``i''/``=`i'+`nbitems'''" _col(23) %5.2f `ABC``i''' _col(33) %5.2f `mbootstrapb'[2,`i'] _col(43) %5.2f `z`i'' _col(53) %5.4f `p`i'' _col(63) %5.2f `=`ABC``i'''-1.96*`mbootstrapb'[2,`i']' _col(73) %5.2f `=`ABC``i'''+1.96*`mbootstrapb'[2,`i']'
+ }
+ di "{hline 77}"
+ local abc=1
+ }
+
+
+}
+
+if "`bootstrap'"=="" {
+ return matrix p=`p'
+}
+qui restore , preserve
+end
+
+
diff --git a/Modules/ado/personal/n/nopalerav3.ado b/Modules/ado/personal/n/nopalerav3.ado
new file mode 100644
index 0000000..2e5b9d2
--- /dev/null
+++ b/Modules/ado/personal/n/nopalerav3.ado
@@ -0,0 +1,653 @@
+*! Version 3 11July2018
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* nopalera : NOPALERA algorithm
+*
+* Historic:
+* Version 1 (2015-07-20): Jean-Benoit Hardouin /*ICC; rsbynpirt module*/
+* Version 1.1 (2015-10-24): Jean-Benoit Hardouin /*NOPALERA module, ISOQOL 2015*/
+* Version 2 (2015-10-24): Jean-Benoit Hardouin /*NOPALERA module, ISOQOL 2015*/
+* Version 2.1 (2017-12-13): Jean-Benoit Hardouin /*Improvement*/
+* Version 3 (2018-07-11): Jean-Benoit Hardouin /*Improvement for paper*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE
+* MethodS in Patients-centered outcomes and HEalth ResEarches
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program: http://www.anaqol.org
+*
+* Copyright 2015,2017,2018 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 nopalera, rclass
+version 8.0
+syntax varlist(numeric min=4) [, nobsauc nobsaabc noGraph corr(numlist) NBAUCbs(int 10) NBAABCbs(int 20) noRESTscore GRAPHBYGroup ] /*corr est la correction Ă appliquer pour corriger le RS unif*/
+
+set more off
+tempfile file1 file2 file3
+qui save `file1', replace
+preserve
+local nbitems : word count `varlist'
+qui count
+local nind=r(N)
+tokenize `varlist'
+if mod(`nbitems',2)!=0 {
+ di in red "You must indicate an even number of items"
+ exit
+}
+else {
+ local nbitems=`nbitems'/2
+}
+if "`corr'"=="" {
+ forvalues i=1/`nbitems'{
+ local corr "`corr' 0"
+ }
+}
+local listofitems1
+local listofitems2
+forvalues i=1/`nbitems' {
+ local listofitems1 `listofitems1' ``i''
+ local listofitems2 `listofitems2' ``=`i'+`nbitems'''
+}
+
+di "NOPALERA: an algorithm to detect Response-shift at items level using non parametric IRT"
+di "Number of individuals: `nind'"
+di "Number of items: `nbitems'"
+di "Number of Boostrap replications for AUC: `nbaucbs'"
+di "Number of Boostrap replications for AABC: `nbaabcbs'"
+
+/*******************************************************************************
+Une boucle pour calculer le score, définir le score maximum par item et global
+*******************************************************************************/
+
+tempvar varscore1 varscore2
+qui gen `varscore1'=0
+qui gen `varscore2'=0
+label variable `varscore1' "Total score time 1"
+label variable `varscore2' "Total score time 2"
+local scoremax=0
+local flag=0
+
+
+local modamax=0
+
+forvalues i=1/`nbitems' {
+ local corr`i': word `i' of `corr'
+ qui replace ``=`i'+`nbitems'''=``=`i'+`nbitems'''+`corr`i''
+ qui replace `varscore1'=`varscore1'+``i''
+ qui replace `varscore2'=`varscore2'+``=`i'+`nbitems'''
+ local list1 `list1' ``i''
+ local list2 `list2' ``=`i'+`nbitems'''
+
+ qui su ``i''
+ local modamax`i'=r(max)
+ qui su ``=`i'+`nbitems'''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+}
+
+/*******************************************************************************
+On va calculer maintenant les rest-score de chaque item Ă chaque temps
+*******************************************************************************/
+
+forvalues i=1/`nbitems'{
+ tempvar rscore1``i'' rscore2``i'' vargroup1``i'' vargroup2``i'' vargroup2b``i''
+ if "`restscore'"=="" {
+ qui gen `rscore1``i'''=`varscore1'-``i''
+ qui gen `rscore2``i'''=`varscore2'-``=`i'+`nbitems'''
+ }
+ else {
+ qui gen `rscore1``i'''=`varscore1'
+ qui gen `rscore2``i'''=`varscore2'
+ }
+ qui gengroup `rscore1``i''' , new(`vargroup1``i''') det
+ local seuil1=r(list)
+ *di "rscore1 et group1 item ``i''"
+ *tab `rscore1``i''' `vargroup1``i'''
+ local seuil1 "`seuil1' max"
+ local nbseuil1: word count `seuil1'
+ qui gen `vargroup2b``i'''=`rscore2``i'''
+ local t
+ forvalues j=1/`nbseuil1' {
+ if `j'==1 {
+ local seuilmin=0
+ }
+ else {
+ local seuilmin : word `=`j'-1' of `seuil1'
+ local seuilmin=`seuilmin'+1
+ local seuilmin=`seuilmax'+1
+ }
+
+ local seuilmax : word `j' of `seuil1'
+ if "`seuilmax'"!="max" {
+ if `seuilmax'<`seuilmin' {
+ local seuilmax `seuilmin'
+ }
+ }
+ local t `t' (`seuilmin'/`seuilmax'=`j')
+ }
+ *di "recode vargroup2b``i'' `t'"
+ qui recode `vargroup2b``i''' `t'
+ *di "rscore2 et group2 item ``i'' avant regroupage"
+ *tab `rscore2``i''' `vargroup2b``i'''
+ qui gengroup `vargroup2b``i''',new(`vargroup2``i''') det replace
+ local seuil2=r(list)
+ *di "rscore2 et group2 item ``i'' aprĂšs regroupage"
+ *tab `rscore2``i''' `vargroup2``i'''
+ local seuil2 "`seuil2' max"
+ *di "``i'' seuil2 : `seuil2'"
+ local nbseuil2: word count `seuil2'
+ local t
+ forvalues j=1/`nbseuil2' {
+ if `j'==1 {
+ local seuilmin=1
+ }
+ else {
+ local seuilmin : word `=`j'-1' of `seuil2'
+ local seuilmin=`seuilmin'+1
+ local seuilmin=`seuilmax'+1
+ }
+ local seuilmax : word `j' of `seuil1'
+ if "`seuilmax'"!="max" {
+ if `seuilmax'<`seuilmin' {
+ local seuilmax `seuilmin'
+ }
+ }
+ local t `t' (`seuilmin'/`seuilmax'=`j')
+ }
+ *di "recode vargroup1``i'' `t'"
+ qui recode `vargroup1``i''' `t'
+ *di "rscore1 et group1 item ``i'' aprĂšs regroupage"
+ *tab `rscore1``i''' `vargroup1``i'''
+
+}
+*tab `vargroup1itemA1' `vargroup2itemA1'
+*exit
+qui save `file3', replace
+
+*exit
+/*******************************************************************************
+Quelques tests de conformité
+*******************************************************************************/
+
+qui su `varscore1'
+local maxscore=r(max)
+qui su `varscore2'
+if `r(max)'>`maxscore' {
+ local maxscore=r(max)
+}
+forvalues i=1/`nbitems' {
+ qui su `vargroup1``i'''
+ local maxgroup``i''=r(max)
+}
+
+
+/* sauvegarde des données */
+tempfile rsbynpirtfile rsbynpirtfile1 rsbynpirtfile2
+tempvar score
+qui save `rsbynpirtfile', replace
+
+/*******************************************************************************
+Représentation graphique des tracelines
+*******************************************************************************/
+
+
+forvalues i=1/`nbitems' {
+ tempfile file4
+ tempname mat``i''
+ matrix `mat``i'''=J(`=`maxgroup``i'''+2',9,0)
+ forvalues j=1/`maxgroup``i''' {
+ local k=`j'+1
+ matrix `mat``i'''[`k',1]=`j'
+ *tab `vargroup1``i'''
+ qui su ``i'' if `vargroup1``i'''==`j'
+ matrix `mat``i'''[`k',2]=`r(mean)'
+ matrix `mat``i'''[`k',4]=`r(N)'
+ local temp=`i'+`nbitems'
+ *tab `vargroup2``i''' `vargroup1``i'''
+ tab ``temp'' if `vargroup2``i'''==`j',m
+ qui su ``temp'' if `vargroup2``i'''==`j'
+ matrix `mat``i'''[`k',3]=`r(mean)'
+ matrix `mat``i'''[`k',5]=`r(N)'
+ qui su `rscore1``i''' if `vargroup1``i'''==`j'
+ matrix `mat``i'''[`k',6]=`r(mean)'
+ qui su `rscore2``i''' if `vargroup2``i'''==`j'
+ matrix `mat``i'''[`k',7]=`r(mean)'
+ }
+ local j=`maxgroup``i'''+2
+ matrix `mat``i'''[`j',1]=`maxgroup``i'''+1 /*numero du group*/
+ matrix `mat``i'''[`j',2]=`modamax`i'' /*mean item 1*/
+ matrix `mat``i'''[`j',3]=`modamax`i'' /*mean item 2*/
+ matrix `mat``i'''[`j',4]=0 /*frequency 1*/
+ matrix `mat``i'''[`j',5]=0 /*frequency 2*/
+ if "`restscore'"=="" {
+ local maxi=`scoremax'-`modamax`i''
+ }
+ else {
+ local maxi=`scoremax'
+ }
+ matrix `mat``i'''[`j',6]=`maxi' /*mean rest-score 1*/
+ matrix `mat``i'''[`j',7]=`maxi' /*mean rest-score 2*/
+ label values `vargroup1``i''' lblvarscore``i''
+ qui sort `vargroup1``i''' `vargroup2``i'''
+ qui save `file4',replace
+ forvalues j=1/`maxgroup``i''' {
+ qui count if `vargroup1``i'''==`j'
+ local n1=r(N)
+ qui su `rscore1``i''' if `vargroup1``i'''==`j'
+ local min1=r(min)
+ local max1=r(max)
+ qui count if `vargroup2``i'''==`j'
+ local n2=r(N)
+ qui su `rscore2``i''' if `vargroup2``i'''==`j'
+ local min2=r(min)
+ local max2=r(max)
+ local min=min(`min1',`min2')
+ local max=max(`max1',`max2')
+ label define lblvarscore``i'' `j' `""Scores `min'/`max'" "(n1=`n1';n2=`n2')""', add
+ }
+
+ label define lblvarscore``i'' 0 "Min", add
+ label define lblvarscore``i'' `=`maxgroup``i'''+1' "Max", add
+ qui drop _all
+ qui svmat `mat``i'''
+ qui rename `mat``i'''1 group
+ qui rename `mat``i'''2 e1
+ qui rename `mat``i'''3 e2
+ qui rename `mat``i'''6 rs1
+ qui rename `mat``i'''7 rs2
+ qui sort group
+ label values group lblvarscore``i''
+ label variable group "Groups of scores"
+ if "`graph'"=="" {
+ if "`graphbygroup'"!="" {
+ graph twoway (line e1 group ) (line e2 group ), title("Traceline of item ``i''") xtitle("") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`=`maxgroup``i'''+1',valuelabel labsize(small) /*alternate*/) name("``i''", replace) legend(off)
+ }
+ else {
+ if "`restscore'"=="" {
+ local xtitle="Rest-score"
+ qui su rs1
+ local max=r(max)
+ qui su rs2
+ if `r(max)'>`max' {
+ local max=r(max)
+ }
+
+ }
+ else {
+ local xtitle="Score"
+ local max `maxscore'
+ }
+ graph twoway (line e1 rs1 ) (line e2 rs2 ), title("Traceline of item ``i''") xtitle("`xtitle'") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`max',valuelabel labsize(small) /*alternate*/) name("auc``i''", replace) legend(off)
+ }
+ }
+ qui use `file4', replace
+}
+
+/*******************************************************************************
+Calcul des AUC
+*******************************************************************************/
+
+local tests
+forvalues i=1/`nbitems' {
+ local auc1`i'=0
+ local auc2`i'=0
+ forvalues g=1/`=`maxgroup``i'''+1' {
+ local k=`g'+1
+ local auc=(`mat``i'''[`g',2]+`mat``i'''[`k',2])/2*(`mat``i'''[`k',6]-`mat``i'''[`g',6])
+ local auc1`i'=`auc1`i''+`auc'
+ matrix `mat``i'''[`k',8]= `auc'
+ local auc=(`mat``i'''[`g',3]+`mat``i'''[`k',3])/2*(`mat``i'''[`k',7]-`mat``i'''[`g',7])
+ local auc2`i'=`auc2`i''+`auc'
+ matrix `mat``i'''[`k',9]= `auc'
+ }
+ local AUC``i''=`auc1`i''
+ local AUC``=`i'+`nbitems'''=`auc2`i''
+ local diffAUC``i''=`=`AUC``i'''-`AUC``=`i'+`nbitems'''''
+ return scalar AUC``i''=`auc1`i''
+ return scalar AUC``=`i'+`nbitems'''=`auc2`i''
+ local tests `tests' b``i''=(r(AUC``=`i'+`nbitems''')-r(AUC``i''))
+}
+
+/*******************************************************************************
+Calcul des standard errors des AUC par bootstrap
+*******************************************************************************/
+
+*local abc=0
+if "`bsauc'"=="" {
+ *di "on lance le bootstrap sur les AUC"
+ *set trace on
+ tempfile file2
+ qui save `file2', replace
+ qui use `file1', clear
+ capture qui bootstrap `tests' , rep(`nbaucbs') nol noh nodots : nopalera `varlist', nograph `restscore' nobsaabc nobsauc
+ local n=1
+ while (_rc!=0) {
+ di "`n'. The boostrap to obtain IC of the AUC has not been correctly performed, it is run again"
+ local ++n
+ capture qui bootstrap `tests' , rep(`nbaucbs') nol noh nodots : nopalera `varlist', nograph `restscore' nobsaabc nobsauc
+ }
+ tempname mbootstrap
+ matrix `mbootstrap'=r(table)
+ qui use `file2', clear
+
+ /*Création de la matrice p qui va permettre de décaler les ICC*/
+ tempname p
+ matrix `p'=J(`=(`scoremax'+1)*(`nbitems'+1)',`=`nbitems'*3+1',.)
+ forvalues s=0/`scoremax' {
+ matrix `p'[`=`s'+1',1]=`s'
+ forvalues i=1/`nbitems' {
+ matrix `p'[`=`s'+1',`=3*`i'-1']=`s'
+ }
+ }
+ forvalues i=1/`nbitems' {
+ forvalues s=0/`scoremax' {
+ qui su ``i'' if `varscore1'==`s'
+ matrix `p'[`=`s'+1',`=3*`i'']=r(mean)
+ }
+ forvalues s=0/`scoremax' {
+ qui su ``=`i'+`nbitems''' if `varscore2'==`s'
+ if `mbootstrap'[4,`i']>=0.05 {
+ matrix `p'[`=`s'+1',`=3*`i'+1']=r(mean)
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ if `nind'/`scoremax'>20 {
+ local prec=0.5
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ else {
+ local prec=1
+ local prec=0.01 /*pas d'arrondi*/
+ }
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'-1']=round(`s'+`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ matrix `p'[`=`i'*(`scoremax'+1)+`s'+1',`=3*`i'+1']=r(mean)
+ }
+ }
+ }
+ di
+ di "Research of uniform recalibration at item-level"
+ di
+ di "{hline 105}"
+ di _col(45) "Bootstrap" _col(78) " Normal-based"
+ di "Items" _col(18) "AUC t1" _col(28) "AUC t2" _col(38) "VarAUC" _col(45) "Std. Err." _col(63) "z" _col(70) "P>|z|" _col(78) "[95% Conf. Int.]" _col(96) "Correction"
+ di "{hline 105}"
+ forvalues i=1/`nbitems' {
+ local corr``i''=round(`mbootstrap'[1,`i']/(`modamax`i''),`prec')
+ di "``i''/``=`i'+`nbitems'''" _col(19) %5.2f `AUC``i''' _col(29) %5.2f `AUC``=`i'+`nbitems'''' _col(39) %5.2f `diffAUC``i''' _col(49) %5.2f `mbootstrap'[2,`i'] _col(59) %5.2f `mbootstrap'[3,`i'] _col(69) %5.4f `mbootstrap'[4,`i'] _col(79) %5.2f `mbootstrap'[5,`i'] _col(89) %5.2f `mbootstrap'[6,`i'] _col(100) %6.2f `corr``i'''
+ }
+ di "{hline 105}"
+ local abc=1
+}
+else {
+ *di "pas de bootstrap AUC"
+ local abc=1
+}
+
+*di "abc:`abc' bsAUC : `bsauc'"
+
+/*******************************************************************************
+Calcul des AABC et de leurs intervalles de confiance par boostrap
+*******************************************************************************/
+*set trace on
+if `abc'==1 {
+ *di "on lance les AABC"
+ local testsb
+ forvalues i=1/`nbitems' {
+ if "`bsauc'"!="" { /*si pas de bootstrap pour AUC*/
+ *di "m1"
+ local sigAUC``i''=0
+ local rdiffAUC``i''=0
+ }
+ else if `mbootstrap'[4,`i']<0.05 { /* si bootstrap et significatif*/
+ *di "m2"
+ local sigAUC``i''=1
+ local rdiffAUC``i''=-`corr``i'''
+ di "The item ``i'' traceline is corrected of `corr``i'''"
+ }
+ else { /* si bootstrap et NS*/
+ *di "m3"
+ local sigAUC``i''=0
+ local rdiffAUC``i''=0
+ }
+ tempname mat2``i''
+ local nbl=`=`maxgroup``i'''*4+7'
+ matrix `mat2``i'''=J(`nbl',4,.)
+ matrix `mat2``i'''[1,2]=0
+ matrix `mat2``i'''[1,3]=0
+ matrix `mat2``i'''[`nbl',2]=`modamax`i''
+ matrix `mat2``i'''[`nbl',3]=`modamax`i''
+ local col1=1
+ local col2=1
+ local line=1
+ while (`line'<=`=`maxgroup``i'''*4+7') {
+ local t1=`mat``i'''[`col1',6]
+ local t2=`mat``i'''[`col2',7]-`rdiffAUC``i'''
+ local m2=`mat``i'''[`col1',2]
+ local m3=`mat``i'''[`col2',3]
+ if (`t1'<`t2'|(`t1'==`t2'&`m2'<`m3')) {
+ *di "m2 car `m2'<`m3'"
+ matrix `mat2``i'''[`line',1]=`t1'
+ matrix `mat2``i'''[`line',2]=`mat``i'''[`col1',2]
+ local ++col1
+ }
+ else {
+ *di "m3 car `m2'>`m3'"
+ matrix `mat2``i'''[`line',1]=`t2'
+ matrix `mat2``i'''[`line',3]=`mat``i'''[`col2',3]
+ local ++col2
+ }
+ local line=`line'+2
+ }
+ *matrix list `mat2``i'''
+ local j=1
+ while (`j'<=`nbl') {
+ foreach c in 2 3 {
+ if `mat2``i'''[`j',`c']==. {
+ local prec=`j'-2
+ local m=`mat2``i'''[`prec',`c']
+ while (`m'==.&`prec'>=0) {
+ local prec=`prec'-2
+ local m=`mat2``i'''[`prec',`c']
+ *di "prec:`prec' m: `m'"
+ }
+ local suiv=`j'+2
+ local m=`mat2``i'''[`suiv',`c']
+ while (`m'==.&`suiv'<=`nbl') {
+ local suiv=`suiv'+2
+ local m=`mat2``i'''[`suiv',`c']
+ *di "suiv:`suiv' m: `m'"
+ }
+ local yprec=`mat2``i'''[`prec',`c']
+ local ysuiv=`mat2``i'''[`suiv',`c']
+ local xprec=`mat2``i'''[`prec',1]
+ local xsuiv=`mat2``i'''[`suiv',1]
+ local x=`mat2``i'''[`j',1]
+ if (`xsuiv'!=`xprec') {
+ *di "matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')"
+ matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')
+ }
+ else {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ }
+ }
+ local j=`j'+2
+ }
+ local j=2
+ *matrix list `mat2``i'''
+ while (`j'<`nbl') {
+ local prec=`j'-1
+ local suiv=`j'+1
+ local sign=(`mat2``i'''[`prec',2]-`mat2``i'''[`prec',3])*(`mat2``i'''[`suiv',2]-`mat2``i'''[`suiv',3])
+ *di "item ``i'', ligne `j', sign `sign'"
+ if (`sign'<0&`sign'!=.) {
+ local p1=(`mat2``i'''[`suiv',2]-`mat2``i'''[`prec',2])/(`mat2``i'''[`suiv',1]-`mat2``i'''[`prec',1])
+ local p2=(`mat2``i'''[`suiv',3]-`mat2``i'''[`prec',3])/(`mat2``i'''[`suiv',1]-`mat2``i'''[`prec',1])
+ if (`p1'==`p2') {
+ local cint=`mat2``i'''[`prec',1]
+ }
+ else {
+ local cint=`mat2``i'''[`prec',1]+(`mat2``i'''[`prec',3]-`mat2``i'''[`prec',2])/(`p1'-`p2')
+ }
+ matrix `mat2``i'''[`j',1]=`cint'
+ foreach c in 2 3 {
+ local yprec=`mat2``i'''[`prec',`c']
+ local ysuiv=`mat2``i'''[`suiv',`c']
+ local xprec=`mat2``i'''[`prec',1]
+ local xsuiv=`mat2``i'''[`suiv',1]
+ local x=`cint'
+ if (`xsuiv'==`xprec') {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ else {
+ *di "matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')"
+ matrix `mat2``i'''[`j',`c']=`yprec'+(`x'-`xprec')/(`xsuiv'-`xprec')*(`ysuiv'-`yprec')
+ }
+ }
+ }
+ else {
+ local prec=`j'-1
+ forvalues c=1/3 {
+ matrix `mat2``i'''[`j',`c']=`mat2``i'''[`prec',`c']
+ }
+ }
+ local j=`j'+2
+ }
+ *matrix list `mat2``i'''
+ local aabc``i''=0
+ *set trace on
+ forvalues j=2/`nbl' {
+ local prec=`j'-1
+ local x=`mat2``i'''[`j',1]
+ local xprec=`mat2``i'''[`prec',1]
+ local y2=`mat2``i'''[`j',2]
+ local y3=`mat2``i'''[`j',3]
+ local yprec2=`mat2``i'''[`prec',2]
+ local yprec3=`mat2``i'''[`prec',3]
+ local aabc=(abs(`y2'-`y3')+abs(`yprec2'-`yprec3'))/2*abs(`x'-`xprec')
+ matrix `mat2``i'''[`j',4]=`aabc'
+ local aabc``i''=`aabc``i'''+`aabc'
+ }
+ return scalar AABC``i''=`aabc``i'''
+ *set trace off
+
+ local testsb `testsb' c``i''=r(AABC``i'')
+ *matrix list `mat2``i'''
+ *di "return scalar AABC``i''=`aabc``i'''"
+ *matrix list `mat2``i'''
+ }
+ *set trace on
+ if "`bsaabc'"=="" {
+ *di "on lance le bootstrap AABC"
+ tempfile file3
+ qui save `file3', replace
+ qui use `file1', clear
+ *di "bootstrap `testsb' , rep(`nbbootstrap') nol noh nodots saving(C:\Users\jean-\Documents\tmp\essai.dta, replace) : nopalera `varlist', fin nograph `restscore' nobsauc nobsaabc "
+ *set trace on
+ *set tracedepth 2
+ tempfile filebsaabc
+ *di "hello c'est l'heure du BS"
+ *qui bootstrap `testsb' , rep(`nbaabcbs') nol noh nodots saving("`filebsaabc'", replace) trace : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ capture qui bootstrap `testsb' , rep(`nbaabcbs') saving("`filebsaabc'", replace) : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ local n=1
+ while (_rc!=0) {
+ di "`n'. The boostrap to obtain IC of the AABC has not been correctly performed, it is run again"
+ local ++n
+ capture qui bootstrap `testsb' , rep(`nbaabcbs') saving("`filebsaabc'", replace) : nopalera `varlist', nograph `restscore' nobsauc nobsaabc
+ }
+ *return list
+ tempname mbootstrapb
+ matrix `mbootstrapb'=r(table)
+ *di "MATRIX mbootstrapb `mbootstrapb'"
+ *matrix list `mbootstrapb'
+ qui use "`filebsaabc'", replace
+ *su
+ local thres=`nbaabcbs'-ceil(`nbaabcbs'/20)
+ forvalues i=1/`nbitems' {
+ sort c``i''
+ qui su c``i'' in `thres'
+ local upper``i''=r(mean)
+ *di "Upper ``i'' : `upper``i'''"
+ }
+ di
+ di "Research of non-uniform recalibration at item-level"
+ di
+ di "{hline 103}"
+ di _col(36) "Bootstrap" _col(56) "Uniform" _col(72) "Non-uniform"
+ di "Items" _col(23) "AABC" _col(29) "[95% Conf. Int.]" _col(50) "Recalibration" _col(70) "Recalibration" _col(88) "Reprioritization"
+ di "{hline 103}"
+ forvalues i=1/`nbitems' {
+ local xur=""
+ local xnur=""
+ local xrep=""
+ if `mbootstrap'[4,`i']<=0.05 {
+ local xur="X"
+ }
+ if (`aabc``i'''>`upper``i'''&"`xur'"=="X") {
+ local xnur="X"
+ }
+ if (`aabc``i'''>`upper``i'''&"`xur'"=="") {
+ local xrep="X"
+ }
+
+ di "``i''/``=`i'+`nbitems'''" _col(23) %5.2f `aabc``i''' _col(36) "[" %1.0f 0 "-" %5.2f `upper``i''' "]" _col(62) "`xur'" _col(82) "`xnur'" _col(102) "`xrep'"
+ }
+ di "{hline 103}"
+ local abc=1
+ }
+ if "`graph'"=="" {
+ forvalues i=1/`nbitems' {
+ qui drop _all
+ qui svmat `mat2``i'''
+ qui rename `mat2``i'''1 score
+ qui rename `mat2``i'''2 t1
+ qui rename `mat2``i'''3 at2
+ qui sort score
+ if "`restscore'"=="" {
+ local xtitle="Rest-score"
+ qui su score
+ local max=r(max)
+ }
+ else {
+ local xtitle="Score"
+ local max `maxscore'
+ }
+ list *
+ graph twoway (line t1 score ) (line at2 score ) if score>0&score<=`maxscore', title("Traceline of item ``i''") xtitle("`xtitle'") ytitle("Expected value of item ``i''", size(small)) ylabel(0(1)`modamax') xlabel(0(1)`max',valuelabel labsize(small) /*alternate*/) name("aabc``i''", replace) legend(off)
+ }
+ }
+}
+qui restore , preserve
+end
+
+
diff --git a/Modules/ado/personal/p/pcm - Copie.ado b/Modules/ado/personal/p/pcm - Copie.ado
new file mode 100644
index 0000000..14de336
--- /dev/null
+++ b/Modules/ado/personal/p/pcm - Copie.ado
@@ -0,0 +1,2115 @@
+*! Version 5.2 16July2023
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+* Version 5.2: July 16th, 2023 [Jean-Benoit Hardouin] : Add of new graphs for Equating
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [if] [in] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) eqset1name(string) eqset2name(string) EQGraph eqaddset1(real 0) eqaddset2(real 0) eqmultset1(real 1) eqmultset2(real 1) eqwithic eqgenscore(string) DIMname(string) minsize(int 30)]
+
+preserve
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count if `touse'
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ *di "i: `i' ``i''"
+ qui su ``i'' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count if `touse'
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist' if `touse'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist' if `touse', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' if `touse' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'* if `touse',latent se(`selatent'*)
+*di "latent=`latent' "
+*su
+*set trace on
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'1 if `touse'
+ qui gen `genlt'_se=`selatent'1 if `touse'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t' if `touse'
+ qui gen `genlt'`t'_se=`selatent'`t' if `touse'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t' if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit' if `touse',score(`score'`t')
+ qui gengroup `latent'`t' if `touse',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'1+invnorm(uniform())*`selatent'1 if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit' if `touse',score(`score')
+ qui gengroup `latent'1 if `touse',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'&`touse'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit' if `touse'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+6',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.&`touse'
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*) if `touse'
+qui count if `miss'==0&`touse'
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(58) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'1 if `touse'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent'1)^2 if `touse'
+ qui su `se2latent' if `touse'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0 if `touse'
+ qui gen `TInf'=0 if `touse'
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0 if `touse'
+ qui gen `cum_old``i'''=0 if `touse'
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'1-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d') if `touse'
+ qui gen `c_old0_``i'''=1/(`d_old') if `touse'
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'1-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k' if `touse'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k' if `touse'
+ }
+ qui gen `Inf``i'''=0 if `touse'
+ qui gen `Inf_old``i'''=0 if `touse'
+ qui gen `C``i'''=0 if `touse'
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i''' if `touse'
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i''' if `touse'
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i''' if `touse'
+ }
+ qui count if ``i''!=.&`touse'
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2) if `touse'
+ qui su `C2``i''' if `touse'
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2 if `touse'
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i''' if `touse'
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i''' if `touse'
+ qui replace `TInf'=`TInf'+`Inf``i''' if `touse'
+ qui gen `y``i'''=``i''-`cum``i''' if `touse'
+ qui gen `y_old``i'''=``i''-`cum_old``i''' if `touse'
+ qui gen `y2``i'''=(`y``i''')^2 if `touse'
+ qui gen `y2_old``i'''=(`y_old``i''')^2 if `touse'
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i''')) if `touse'
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'&`touse'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'&`touse'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'&`touse'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'&`touse'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'&`touse'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'&`touse'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent'1 "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ tempvar id``i''
+ qui gen `id``i'''=_n if abs(`z``i''')>2.57*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `z``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-2*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=2*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent' if `touse', yscale(range(`min'(1)`max')) yline(`=-2.57*sqrt(`covariates'[1,1])' `=2.57*sqrt(`covariates'[1,1])',lcolor(blue)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2 if `touse'
+ qui su `z2``i''' if `touse'
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.&`touse'
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i''' if `touse'
+ qui su `i``i''' if ``i''!=.&`touse'
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di "``i''" _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)"
+ di as text "**: As suggested by Bond and Fox (2007)"
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf' if `touse'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Iteration `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1') if `touse'
+ `qui' pcm `varlist' [iweight=`sinf'] if `touse',diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1') if `touse'
+ qui su `ecart_`it'' if `touse'
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED VALUES OF THE LT ESTIMATORS (values of lt that explained the best the score)
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ *set trace on
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues l=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`l''
+ }
+ qui gen ecart=.
+ forvalues l=0/`scoremax' {
+ if `l'==0 {
+ local j=0.25
+ }
+ else if `l'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`l'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`l'=`r(mean)'
+ *qui su TInf if round(ecart, 0.01)==round(`tmp',0.01)
+ *local setlt`l'=sqrt(1/`r(mean)')
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt matgroupscorelt
+ *di "qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)"
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ qui matrix `matgroupscorelt'=J(`=`nbitems'*`modamax'+1'+2*`nbgroups'',7,.)
+ qui matrix colnames `matgroupscorelt'="Group" "Score" "Frequency" "Estimation of latent trait" "s.e. of latent trait" "Expected score" "Corrected latent trait"
+
+ local row=1
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.&`touse'
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'&`touse'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local eff=r(N)
+ local effscore`s'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local mean=r(mean)
+ *di "local ltscore`s'=`=ceil(`r(mean)'*100)/100'"
+ local ltscore`s'=`=ceil(`r(mean)'*100)/100'
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s'' `setlt`s''
+ }
+ *set trace on
+ *matrix list `matscorelt'
+ qui matrix `matscorelt'[`=`s'+1',1]=`eff'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ *set trace off
+ }
+
+ }
+ *set trace on
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local eff=r(N)
+ local eff_md_`g'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local mean=r(mean)
+ local lt_md_`g'=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local exp=r(mean)
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) /*%5.2f `exp'*/
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ *qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ }
+ *set trace off
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`effcompleted`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ if "`scoremin`g''"=="" {
+ local scoremin`g' "."
+ }
+ if "`scoremax`g''"=="" {
+ local scoremax`g' "."
+ }
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+ qui matrix `matgroupscorelt'=`matgroupscorelt'[1..`nbrowmat',1..7]
+ *matrix list `matscorelt'
+}
+
+*set trace on
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ qui graph twoway line cum``i'' u, name(ICCc``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi'
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ *tab Tcum
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+ qui graph twoway line Tcum u , name(TCCceo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo'
+ }
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!=""|"eqset1"!="" {
+ gen eff=0
+ gen eff_md=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ /*le bloc suivant Ă©tait pour avoir des batons par groupe*/
+ /*forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }*/
+ /*le bloc suivant est pour avoir des batons par score*/
+ qui gen uceil=ceil(u*100)/100
+ forvalues s=0/`scoremax' {
+ if `effscore`s''>`effmax' {
+ local effmax=`effscore`s''
+ }
+ *di "`s' qui replace eff=`effscore`s'' if ceil(u*100)/100==`=round(`ltscore`s'',0.01)'"
+ qui replace eff=`effscore`s'' if round(u,0.01)==round(`ltscore`s'',0.01)
+ }
+ forvalues g=1/`nbgroups' {
+ *di "if `eff_md_`g''>`effmax' { (`lt_md_`g'')"
+ if `eff_md_`g''>`effmax' {
+ local effmax=`eff_md_`g''
+ }
+ qui replace eff_md=`eff_md_`g'' if round(u,0.01)==round(`lt_md_`g'',0.01)
+ }
+
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0|eff_md!=0
+ *set trace on
+ *set tracedepth 1
+ *if eff!=0|eff_md!=0 {
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ *}
+ *else {
+ * local floor=-10
+ * local ceil=10
+ *}
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ local legend `"3 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'+1' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local ylbl `ylbl' `=-`i'*`unit'' "``i''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su eff_md
+ local maxe_md=ceil(`=(floor(`r(max)'/10)+1)*10')
+ local maxe=max(`maxe',`maxe_md')
+ qui su TInf
+ local maxi=1.2*ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ if "`eqset1'"==""&"`graphs'"!="" {
+ *list eff u uceil if eff!=0&eff!=.
+ *save tmp, replace
+ qui graph twoway (bar eff u, barwidth(.1) yaxis(1) xlabel(`floor'(1)`ceil') color(erose) ) (line TInf u,yaxis(2) lwidth(medthick)) (line density u,yaxis(3) lwidth(medthick) lcolo(green) ) (bar eff_md u, barwidth(.05) yaxis(1) xlabel(`floor'(1)`ceil') color(stred) ) `scatterj' , xline(0, lcolor(black)) legend(on position(6) cols(`modamax') rows(1) order(`"`legend'"') subtitle(Threshold parameters) size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(medium) lpattern(solid) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait - * : dysfunctioning items") xtitle("Latent trait") `fsm'
+ }
+ else if "`eqset1'"!="" {
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+
+ qui tempfile equating
+ qui save `equating', replace
+ }
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di "``i''" _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+if "`eqset1'"!="" {
+ if "`eqgenscore'"!="" {
+ local tmp1 `=ustrlen("`eqgenscore'`eqset1name'")'
+ local tmp2 `=ustrlen("`eqgenscore'`eqset2name'")'
+ local mlength=max(`tmp1',`tmp2')
+ if `mlength'>27 {
+ di as error "The number of characters containing in the strings eqgenscore+eqset1name or eqgenscore+eqset2name must be lesser than 27"
+ di as error "eqgenscore+eqset1name : `tmp1' characters"
+ di as error "eqgenscore+eqset2name : `tmp2' characters"
+ error 130
+ *exit
+ }
+ }
+ if "`eqset1name'"=="" {
+ local eqset1name="Set 1"
+ }
+ if "`eqset2name'"=="" {
+ local eqset2name="Set 2"
+ }
+ local eqset1name `=regexreplaceall("`eqset1name'"," ","_",.)'
+ local eqset2name `=regexreplaceall("`eqset2name'"," ","_",.)'
+ *di "set1:`eqset1name' set2:`eqset2name'"
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ }
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ local pciset1
+ local pciset2
+ *set trace on
+ local minimini=0
+ local maximaxi=0
+ forvalues t=1/2 {
+ qui gen adjscore`t'=(score`t'+`eqaddset`t'')*`eqmultset`t''
+ qui gen adjscore`=3-`t''=(score`=3-`t''+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ *set trace on
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ if `ceil'==0 {
+ local ceil=1
+ }
+ if "`eqwithic'"=="" {
+ local pciset`t' `pciset`t'' scatteri `=-`ceil'/5*`t'' `r(mean)' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)||
+ }
+ local mean=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ local moins=r(mean)
+ if `moins'<`minimini' {
+ *di "local minimini=floor(`moins')"
+ local minimini=floor(`moins')
+ }
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ local plus=r(mean)
+ if `plus'>`maximaxi' {
+ *di "local maximaxi=ceil(`plus')"
+ local maximaxi=ceil(`plus')
+ }
+
+ if "`eqwithic'"!="" {
+ local y=-`ceil'/5*((2.5*`t'-2)+2*(`s'/`scoremaxset`t''))
+ *local pciset`t' `pciset`t'' scatteri `y' `mean' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ local pciset`t' `pciset`t'' scatteri `y' `mean' , mlabsize(tiny) mcolor(black) mlabcolor(black)|| scatteri `y' `moins' (9) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , msize(0) mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ }
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ di as text
+ di as text "{hline 78}"
+ di as text "EQUATING `eqset`t'name' TO `eqset`=3-`t''name'"
+ di as text "{hline 78}"
+ di "`eqset`t'name' : `eqset`t''"
+ di "`eqset`=3-`t''name' : `eqset`=3-`t'''"
+ local eqset`t'namea=abbrev("`eqset`t'name'",18)
+ local eqset`=3-`t''namea=abbrev("`eqset`=3-`t''name'",12)
+ di "{hline 78}"
+ di "Score" _col(20) "<----- Latent trait ----->" _col(52) "<- Score `eqset`=3-`t''namea'" _col(77) "->"
+ di "`eqset`t'namea'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+
+ di %4.0f `=(`matscore`t''[`=`s'+1',1]+`eqaddset`t'')*`eqmultset`t''' _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' _col(66) "[" %5.2f `min' ";" %5.2f `max' "]"
+ }
+ di "{hline 78}"
+ if "`eqgraph'"!="" {
+ *set trace on
+ if `eqmultset`=3-`t'''>0 {
+ local xlabel "`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''(`=ceil((`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''"
+ }
+ else {
+ local xlabel "`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''(`=ceil((-`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''"
+ }
+ if `eqmultset`t''>0 {
+ local ylabel "`=`eqaddset`t''*`eqmultset`t'''(`=ceil((`scoremaxset`t''*`eqmultset`t'')/20)')`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''"
+ }
+ else {
+ local ylabel "`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''(`=ceil((-`scoremaxset`t''*`eqmultset`t'')/20)')`=`eqaddset`t''*`eqmultset`t'''"
+ }
+ *set trace off
+ *di "xlabel : `xlabel'"
+ *di "subtitle=`subtitle'"
+ twoway (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''!=.,lcolor(black) lpattern(solid) lwidth(thick)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''m!=.,lcolor(black) lpattern(dash) lwidth(thin)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''p!=.,lcolor(black) lpattern(dash) lwidth(thin)), title("Equating score of `eqset`=3-`t''name' to `eqset`t'name' ") ytitle("Score `eqset`t'name'") xtitle("Score `eqset`=3-`t''name'") ylabel(`ylabel') xlabel(`xlabel') name(eq`t'to`=3-`t'') legend(order(1 2) label(1 "Estimated") label(2 "95%IC") position(6)) subtitle("`dimname'")
+ }
+ qui drop adjscore`t' adjscore`=3-`t''
+ }
+
+ if "`eqgraph'"!="" {
+ qui use "`equating'",clear
+ qui su u
+ local flooru=floor(`r(min)')
+ local ceilu=ceil(`r(max)')
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+ if `ceil'==0 {
+ local ceil=1
+ }
+
+ local title "Equating"
+ if "`eqset1name'"!=""&"`eqset2name'"!=""{
+ local title "Equating between `eqset1name' and `eqset2name'"
+ }
+ if "`eqwithic'"=="" {
+ local ylabel1=-`ceil'/5
+ local ylabel2=-2*`ceil'/5
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ else {
+ local ylabel1=-0.5*`ceil'/5
+ local ylabel2=-3*`ceil'/5
+ local flooru=min(`flooru',`minimini')
+ local ceilu=max(`ceilu',`maximaxi')
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(1)`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle( Frequencies) ylabel(`=-`ceil'/5*2' `eqset1name' `=-`ceil'/5' `eqset2name' 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title(Equating) xsize(12) ysize(9) xtitle(Latent trait) "
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(`gapu')`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle(" Frequencies") /*ylabel(`ylbl', grid angle(0) axis(1))*/ ylabel(`ylabel1' "`eqset1name'" `ylabel2' "`eqset2name'" 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title("`title'") subtitle("`dimname'") xsize(12) ysize(9) xtitle("Latent trait")
+ }
+ qui use `fileeq',clear
+ *set trace on
+ tempname scoreset1 scoreset2
+ forvalues t=1/2 {
+ qui genscore `eqset`t'' if `touse',score(`scoreset`t'')
+ qui su `scoreset`t'' if `touse'
+ local maxscoreset=r(max)
+ *qui matrix list `matscore`t''
+ if "`eqgenscore'"!="" {
+ local eqgenscore `=regexreplaceall("`eqgenscore'"," ","_")'
+ *di "eqgenscore : `eqgenscore'"
+ foreach k in mean min max alea {
+ capture confirm variable `eqgenscore'_`k'_`eqset`=3-`t''name'
+ if _rc==0&"`replace'"!="" {
+ qui replace `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ else if _rc==0&"`replace'"!="" {
+ di as error "The variable `eqgenscore'_`k'_`eqset`=3-`t''name' already exists"
+ error 198
+ }
+ else {
+ qui gen `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ }
+ *tab `scoreset`t''
+ forvalues s=0/`maxscoreset' {
+ *di "qui replace `eqgenscore'_`eqset`=3-`t''name'=`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' if `scoreset`t''==`s'"
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ qui replace `eqgenscore'_mean_`eqset`=3-`t''name'=round(`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_min_`eqset`=3-`t''name'=round(`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_max_`eqset`=3-`t''name'=round(`max',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_alea_`eqset`=3-`t''name'=round(uniform()*(`max'-`min')+`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ }
+ }
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ }
+
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+*set trace on
+if "`visit'"!="" {
+ tempfile sauv
+ *set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_opt
+ capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=. if `touse'
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr=`estlt`s'' if `score'==`s'&`touse'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr=`clt`g'' if `group'==`g'&`genlt'_corr==.&`touse'
+ }
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=. if `touse'
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'&`touse'
+ }
+ }
+ *su
+ qui egen `genlt'_opt=rowmean(`tmpitem'_*) if `touse'
+ qui egen `genlt'_opt_se=rowsd(`tmpitem'_*) if `touse'
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*) if `touse'
+ qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss') if `touse'
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin, footer(fall_report)
+ putdocx table hdr = (1, 3), border(all, nil) tofooter(fall_report)
+ if "`rsm'"=="" {
+ putdocx table hdr(1, 1) = ("Partial Credit Model")
+ }
+ else {
+ putdocx table hdr(1, 1) = ("Rating Scale Model")
+ }
+ putdocx table hdr(1, 2) = ("`dimname'"), halign(center)
+ putdocx table hdr(1, 3) = ("Page "), pagenumber
+ putdocx table hdr(1, 3) = ("/"), totalpages append
+ putdocx table hdr(1, 3), halign(right)
+ putdocx paragraph ,style(Title)
+ putdocx text ("General informations") ,
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("Names of the dimension: `dimname'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph, style(Title)
+ putdocx text ("Estimation of the parameters") ,
+ local paramname
+ forvalues j=1/`nbitems' {
+ forvalues k=1/`modamax' {
+ if `k'<=`modamax`j'' {
+ local paramname `paramname' "``j''_`k'"
+ }
+ }
+ }
+ *di "matrix colnames `diff'=`paramname'"
+ matrix rownames `diff'=`paramname'
+ putdocx table table1 = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1) halign(center)
+ putdocx table table1(.,1), halign(left)
+ putdocx table table1(.,2/7), halign(right)
+ putdocx table table1(1,.), halign(right) border(top) border(bottom)
+
+
+ qui putdocx table table2 = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table2(.,1), halign(left)
+ putdocx table table2(.,2/7), halign(right)
+ putdocx table table2(1,.), halign(right) border(top) border(bottom)
+
+
+
+
+ putdocx paragraph,style(Title)
+ putdocx text ("Fit indexes for items") , /*bold underline font(,14) smallcaps*/
+ qui putdocx table table3 = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table3(.,1), halign(left)
+ putdocx table table3(.,2/5), halign(right)
+ putdocx table table3(1,.), halign(right) border(top) border(bottom)
+
+
+
+ putdocx paragraph, style(Title)
+ putdocx text ("Estimation per group/score")
+ *putdocx text ("Estimation per group/score") , bold underline font(,14) smallcaps
+ *set trace on
+ putdocx table tbl = (`=`nbrowmat'+1',7), border(all,nil) width(7) halign(center) note(EAP: Expected A Posteriori ; BE: Best Estimates) headerrow(1)
+ putdocx table tbl(1,.), halign(right) border(top) border(bottom)
+ putdocx table tbl(1,1) = ("Group"), halign(right)
+ putdocx table tbl(1,2) = ("score"), halign(right)
+ putdocx table tbl(1,3) = ("Frequency"), halign(right)
+ putdocx table tbl(1,4) = ("EAP Mean"), halign(right)
+ putdocx table tbl(1,5) = ("EAP s.e."), halign(right)
+ putdocx table tbl(1,6) = ("Exp score"), halign(right)
+ putdocx table tbl(1,7) = ("BE Mean"), halign(right)
+ local fin=1
+ forvalues row=1/`nbrowmat' {
+ local row2=`row'+1
+ local g: di %9.0f `matgroupscorelt'[`row',1]
+ local gh=`matgroupscorelt'[`row',1]
+ if `fin'==1 {
+ putdocx table tbl(`row2',1) = ("`g'"), halign(right)
+ }
+ if `matgroupscorelt'[`row',2]!=.|`matgroupscorelt'[`row',7]==. {
+ local s: di %9.0f `matgroupscorelt'[`row',2]
+ local fin=0
+ }
+ else {
+ local s "`scoremin`gh''/`scoremax`gh''"
+ local fin=1
+ *local fin "border(top) border(bottom)"
+ *di "c'est la fin"
+ putdocx table tbl(`row2',.), border(bottom) border(top, dashed)
+ putdocx table tbl(`row2',1), border(top, nil)
+ }
+ local eff: di %9.0f `matgroupscorelt'[`row',3]
+ local lt: di %9.3f `matgroupscorelt'[`row',4]
+ local se: di %9.3f `matgroupscorelt'[`row',5]
+ local exp: di %9.2f `matgroupscorelt'[`row',6]
+ local clt: di %9.3f `matgroupscorelt'[`row',7]
+ *putdocx table tbl(`row',.), addrows(7)
+ putdocx table tbl(`row2',2) = ("`s'"), halign(right)
+ putdocx table tbl(`row2',3) = ("`eff'"), halign(right)
+ putdocx table tbl(`row2',4) = ("`lt'"), halign(right)
+ putdocx table tbl(`row2',5) = ("`se'"), halign(right)
+ putdocx table tbl(`row2',6) = ("`exp'"), halign(right)
+ putdocx table tbl(`row2',7) = ("`clt'"), halign(right)
+
+ }
+
+/*
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+
+
+local row 1
+local vari 1
+foreach x in gear_ratio turn foreign _cons {
+putdocx table tbl5(`row',.), addrows(2)
+local b: display %9.3f rtable[`vari',1]
+local se: display %9.3f rtable[`vari',2]
+local ++vari
+local ++row
+putdocx table tbl5(`row',1) = ("`x'"), halign(right)
+putdocx table tbl5(`row',2) = ("`b'"), halign(right)
+local ++row
+local se = strtrim("`se'")
+putdocx table tbl5(`row',2) = ("(`se')"), halign(right)
+}*/
+
+ *qui putdocx table tablename = matrix(`matgroupscorelt') , nformat(%9.3f) /*rownames*/ colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+*set trace on
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix matgroupscorelt=`matgroupscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 3.4.ado b/Modules/ado/personal/p/pcm 3.4.ado
new file mode 100644
index 0000000..f6b1bd3
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 3.4.ado
@@ -0,0 +1,986 @@
+*! Version 3.4 23August2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+*
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(name) GENINF(name) postpce]
+
+qui count
+local nbobs=r(N)
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+local modcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local modcont (`modcont'->T)
+}
+
+local modcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local modcat (`modcat'->T)
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0 {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ local modamax``i''=r(max)
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax``i'''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax``i''' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local code `code' `code`k''
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ local t=1
+ local constraints
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax``i''' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ constraint `t' [`k'.``i'']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+
+if "`rsm'"!="" {
+ local t=1
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ constraint `t' [`=`k'-1'.``i'']_cons-[`k'.``i'']_cons+[1.``i'']_cons=[`=`k'-1'.`1']_cons-[`k'.`1']_cons+[1.`1']_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')"
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent',latent se(`selatent')
+if "`genlt'"!="" {
+ gen `genlt'=`latent'
+ gen se`genlt'=`selatent'
+}
+set seed 123456
+qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+qui genscore `varlist',score(`score')
+qui gengroup `latent',newvariable(`group') continuous
+qui levelsof `group'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'==`g'
+ qui count if ``i''!=.&`group'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i'' if `group'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent' if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+qui count if `score'!=.
+local nbobsssmd=r(N)
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i'':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i'':_cons]
+ qui lincom -_b[1.``i'':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i'':_cons]^2
+ local rn `rn' 1.``i''
+ local ++t
+ local sum _b[1.``i'':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax``i''' {
+ local sum "_b[`k'.``i'':_cons]-(`sum')"
+ di "``i'' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i'':_cons]-_b[`k'.``i'':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1':_cons]-_b[`k'.`1':_cons]+_b[1.`1':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES ET LA VARIANCE
+*************************************************************************************************************/
+
+tempname covariates
+qui matrix `covariates'=J(`=`nbpar'+1',6,.)
+
+*set trace on
+if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T)]
+}
+else {
+ qui lincom _b[/var(T)]
+}
+qui matrix `covariates'[1,1]=`r(estimate)'
+qui matrix `covariates'[1,2]=`r(se)'
+qui matrix `covariates'[1,3]=`r(z)'
+qui matrix `covariates'[1,4]=`r(p)'
+qui matrix `covariates'[1,5]=`r(lb)'
+qui matrix `covariates'[1,6]=`r(ub)'
+
+local t=2
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+* matrix list `covariates'
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax``i''' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local n: word count Variance `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of Variance `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ local ++t
+ }
+ di as text "{hline 73}"
+ di
+ qui su `latent'
+ qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])^2)
+ di as text "PSI:" as result %4.2f `PSI'
+ di
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+tempname fit
+qui matrix `fit'=J(`nbitems',4,.)
+matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+matrix rownames `fit'=`varlist'
+*matrix list `fit'
+
+tempvar Tcum TInf cum
+qui gen `Tcum'=0
+qui gen `TInf'=0
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+}
+*set trace on
+local chi2=0
+local chi2_old=0
+forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+}
+forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+}
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+}
+if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+}
+
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+
+if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+*set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+
+di
+di as text "{hline 57}"
+di _col(31) "Latent Variable" _col(50) "Expected"
+di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+di as text "{hline 57}"
+*set trace on
+forvalues g=1/`nbgroups' {
+ qui count if `group'==`g'
+ local eff`g'=r(N)
+ qui count if `score'!=.&`group'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score' if `group'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'==`g'&`score'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'==`g'&`score'==.
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+}
+
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 4.0.ado b/Modules/ado/personal/p/pcm 4.0.ado
new file mode 100644
index 0000000..67b6376
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 4.0.ado
@@ -0,0 +1,1196 @@
+*! Version 4 13September2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(name) GENINF(name) postpce visit(name) id(name)]
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui tab `visit'
+ if r(r)>4{
+ di as error "You must use a discrete time variable with less than 5 time points"
+ error 198
+ }
+ local timemax=r(r)
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ qui reshape wide `varlist', i(`id') j(`visit')
+}
+else {
+ local timemax=1
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0 {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ if `timemax'==1{
+ qui rename ``i'' ``i''1
+ }
+ local t=1
+ foreach l in `levelsofv' {
+ qui rename ``i''`l' ``i''`t'
+ local ++t
+ }
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ constraint `t' [`k'.``i''`j']_cons=[`k'.``i''1]_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ constraint `t' [`k'.``i''1]_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ constraint `t' [`=`k'-1'.``i''1]_cons-[`k'.``i''1]_cons+[1.``i''1]_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+if `timemax'==1{
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist')
+}
+else{
+*di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+matrix esti_B = e(b)
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ tokenize `genlt'
+ forvalues i=1/`timemax'{
+ gen ``i''=`latent'`i'
+ gen se``i''=`selatent'`i'
+ }
+ tokenize `varlist'
+}
+
+set seed 123456
+forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous
+}
+
+/*time 1 only*/
+qui levelsof `group'1
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'1==`g'
+ qui count if ``i''1!=.&`group'1==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''1 if `group'1==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'1==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'1==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''1:_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''1:_cons]
+ qui lincom -_b[1.``i''1:_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i''1:_cons]^2
+ local rn `rn' 1.``i''1
+ local ++t
+ local sum _b[1.``i''1:_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''1:_cons]-(`sum')"
+ di "``i''1 `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''1:_cons]-_b[`k'.``i''1:_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''1
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1':_cons]-_b[`k'.`1':_cons]+_b[1.`1':_cons] *``i'' instead of `i'?
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ local ++t
+ }
+ di as text "{hline 73}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])^2)
+ di as text "PSI:" as result %4.2f `PSI'
+ di
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+if "`visit'"==""{
+ if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+ }
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+ di
+ di as text "{hline 57}"
+ di _col(31) "Latent Variable" _col(50) "Expected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+ di as text "{hline 57}"
+ *set trace on
+ forvalues g=1/`nbgroups' {
+ qui count if `group'1==`g'
+ local eff`g'=r(N)
+ qui count if `score'1!=.&`group'1==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'1 if `group'1==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'1==`g'&`score'1==`s'
+ local eff=r(N)
+ qui su `latent' if `group'1==`g'&`score'1==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'1==`g'&`score'1==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'1==`g'&`score'1==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'1==`g'&`score'1==.
+ local eff=r(N)
+ qui su `latent' if `group'1==`g'&`score'1==.
+ local mean=r(mean)
+ qui su `selatent' if `group'1==`g'&`score'1==.
+ local se=r(mean)
+ qui su `Tcum' if `group'1==`g'&`score'1==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+ }
+}
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 4.1.ado b/Modules/ado/personal/p/pcm 4.1.ado
new file mode 100644
index 0000000..fd5c7e5
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 4.1.ado
@@ -0,0 +1,1208 @@
+*! Version 4.1 15September2019
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(name) GENINF(name) postpce visit(name) id(name)]
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui tab `visit'
+ if r(r)>4{
+ di as error "You must use a discrete time variable with less than 5 time points"
+ error 198
+ }
+ local timemax=r(r)
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ qui reshape wide `varlist', i(`id') j(`visit')
+}
+else {
+ local timemax=1
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0 {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ if `timemax'==1{
+ qui rename ``i'' ``i''1
+ }
+ local t=1
+ foreach l in `levelsofv' {
+ qui rename ``i''`l' ``i''`t'
+ local ++t
+ }
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''1]_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''1]_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''1]_cons-[`k'.``i''1]_cons+[1.``i''1]_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+if `timemax'==1{
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist')
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ tokenize `genlt'
+ forvalues i=1/`timemax'{
+ gen ``i''=`latent'`i'
+ gen se``i''=`selatent'`i'
+ }
+ tokenize `varlist'
+}
+
+set seed 123456
+forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous
+}
+
+/*time 1 only*/
+qui levelsof `group'1
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'1==`g'
+ qui count if ``i''1!=.&`group'1==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''1 if `group'1==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'1==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'1==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''1:_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''1:_cons]
+ qui lincom -_b[1.``i''1:_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i''1:_cons]^2
+ local rn `rn' 1.``i''1
+ local ++t
+ local sum _b[1.``i''1:_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''1:_cons]-(`sum')"
+ *di "``i''1 `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''1:_cons]-_b[`k'.``i''1:_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''1
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'1:_cons]-_b[`k'.`1'1:_cons]+_b[1.`1'1:_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 73}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `=(`r(mean)')'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`r(mean)'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`r(mean)'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+if "`visit'"==""{
+ if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+ }
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+ di
+ di as text "{hline 57}"
+ di _col(31) "Latent Variable" _col(50) "Expected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+ di as text "{hline 57}"
+ *set trace on
+ forvalues g=1/`nbgroups' {
+ qui count if `group'1==`g'
+ local eff`g'=r(N)
+ qui count if `score'1!=.&`group'1==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'1 if `group'1==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'1==`g'&`score'1==`s'
+ local eff=r(N)
+ qui su `latent' if `group'1==`g'&`score'1==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'1==`g'&`score'1==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'1==`g'&`score'1==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'1==`g'&`score'1==.
+ local eff=r(N)
+ qui su `latent' if `group'1==`g'&`score'1==.
+ local mean=r(mean)
+ qui su `selatent' if `group'1==`g'&`score'1==.
+ local se=r(mean)
+ qui su `Tcum' if `group'1==`g'&`score'1==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+ }
+}
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 4.2 sauv le 8nov2019.ado b/Modules/ado/personal/p/pcm 4.2 sauv le 8nov2019.ado
new file mode 100644
index 0000000..94b9b15
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 4.2 sauv le 8nov2019.ado
@@ -0,0 +1,1504 @@
+*! Version 4.2 21September2019
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin]
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) EQGraph minsize(int 30)]
+
+preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui drop `genlt' se`genlt' `geninf'
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivist=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar'
+}
+else{
+ di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'`i'
+ qui gen se`genlt'=`selatent'`i'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t'
+ qui gen se`genlt'`t'=`selatent'`t'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit',score(`score')
+ qui gengroup `latent',newvariable(`group') continuous minsize(`minsize')
+}
+
+/*time 1 only*/
+qui levelsof `group'`multivisit'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 73}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `=(`r(mean)')'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`r(mean)'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`r(mean)'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+if "`visit'"==""{
+ if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui use `savefile', clear
+
+ }
+}
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+ *set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 57}"
+ di _col(31) "Latent Variable" _col(50) "Expected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+ di as text "{hline 57}"
+ forvalues g=1/`nbgroups' {
+ qui count if `group'`multivisit'==`g'
+ local eff`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+ }
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+ }
+ *matrix list `matscorelt'
+}
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+*set trace on
+if "`eqset1'"!="" {
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ *di "set1 (`nbset1') : `eq1_`i''"
+ }
+ *di "`eqset1'"
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ *di "`eqset2'"
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ *di "set2 (`nbset2') : `eq2_`i''"
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ *di "`eq`t'_`i''"
+ *local tmp=""
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ *set trace on
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ *matrix list `diffmat'
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ *matrix list `diffset1'
+ *matrix list `diffset2'
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ *qui gen selt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ *di "matscorelt`t':"
+ *matrix list `matscorelt`t''
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ *qui replace selt=`matscorelt`t''[`=`i'+1',3] if scoreset`t'==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ *list
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ forvalues t=1/2 {
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ *matrix list `matscore`t''
+ di
+ di "{hline 78}"
+ di "EQUATING SET`t' TO SET`=3-`t''"
+ di "{hline 78}"
+ di "Set`t' : `eqset`t''"
+ di "Set`=3-`t'' : `eqset`=3-`t'''"
+ di "{hline 78}"
+ di _col(20) "<----- Latent trait ----->" _col(52) "<------- Score `=3-`t'' --------->"
+ di "Score`t'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ di %4.0f `matscore`t''[`=`s'+1',1] _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `matscore`t''[`=`s'+1',5] _col(66) "[" %5.2f `matscore`t''[`=`s'+1',6] ";" %5.2f `matscore`t''[`=`s'+1',7] "]"
+ }
+ di "{hline 78}"
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ if "`eqgraph'"!="" {
+ *twoway (line lt scoreset1) (line lt scoreset2), name(eq1)
+ *twoway (line scoreset1 scoreset2 lt) , name(eq2)
+ *twoway (line score1 scoreset1m scoreset1p score2), name(eq3)
+ *twoway (line score2 scoreset2m scoreset2p score1), name(eq4)
+ twoway (line score`t' score`=3-`t'' if scoreset`=3-`t''!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''m!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''p!=.), title("Equating score of the Set `t' from the Set `=3-`t''") ytitle("Score `t'") xtitle("Score `=3-`t''") ylabel(0(1)`scoremaxset`t'') xlabel(0(1)`scoremaxset`=3-`t''') name(eq`t'to`=3-`t'')
+ *twoway (line score2 score1 if scoreset1!=.) (line score2 score1 if scoreset1m!=.) (line score2 score1 if scoreset1p!=.), name(eq6)
+ }
+ }
+ *save prout, replace
+ *clear
+
+ qui use `fileeq',clear
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ *su
+ if "`replace'"!=""&("`genlt'"!=""|"`genfit'"!="") {
+ capture drop `genlt' se`genlt' `geninf'
+ }
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 4.2.ado b/Modules/ado/personal/p/pcm 4.2.ado
new file mode 100644
index 0000000..94b9b15
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 4.2.ado
@@ -0,0 +1,1504 @@
+*! Version 4.2 21September2019
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin]
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) EQGraph minsize(int 30)]
+
+preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui drop `genlt' se`genlt' `geninf'
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivist=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar'
+}
+else{
+ di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'`i'
+ qui gen se`genlt'=`selatent'`i'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t'
+ qui gen se`genlt'`t'=`selatent'`t'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit',score(`score')
+ qui gengroup `latent',newvariable(`group') continuous minsize(`minsize')
+}
+
+/*time 1 only*/
+qui levelsof `group'`multivisit'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 73}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `=(`r(mean)')'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`r(mean)'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`r(mean)'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+if "`visit'"==""{
+ if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui use `savefile', clear
+
+ }
+}
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+ *set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 57}"
+ di _col(31) "Latent Variable" _col(50) "Expected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+ di as text "{hline 57}"
+ forvalues g=1/`nbgroups' {
+ qui count if `group'`multivisit'==`g'
+ local eff`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+ }
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+ }
+ *matrix list `matscorelt'
+}
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+*set trace on
+if "`eqset1'"!="" {
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ *di "set1 (`nbset1') : `eq1_`i''"
+ }
+ *di "`eqset1'"
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ *di "`eqset2'"
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ *di "set2 (`nbset2') : `eq2_`i''"
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ *di "`eq`t'_`i''"
+ *local tmp=""
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ *set trace on
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ *matrix list `diffmat'
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ *matrix list `diffset1'
+ *matrix list `diffset2'
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ *qui gen selt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ *di "matscorelt`t':"
+ *matrix list `matscorelt`t''
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ *qui replace selt=`matscorelt`t''[`=`i'+1',3] if scoreset`t'==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ *list
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ forvalues t=1/2 {
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ *matrix list `matscore`t''
+ di
+ di "{hline 78}"
+ di "EQUATING SET`t' TO SET`=3-`t''"
+ di "{hline 78}"
+ di "Set`t' : `eqset`t''"
+ di "Set`=3-`t'' : `eqset`=3-`t'''"
+ di "{hline 78}"
+ di _col(20) "<----- Latent trait ----->" _col(52) "<------- Score `=3-`t'' --------->"
+ di "Score`t'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ di %4.0f `matscore`t''[`=`s'+1',1] _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `matscore`t''[`=`s'+1',5] _col(66) "[" %5.2f `matscore`t''[`=`s'+1',6] ";" %5.2f `matscore`t''[`=`s'+1',7] "]"
+ }
+ di "{hline 78}"
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ if "`eqgraph'"!="" {
+ *twoway (line lt scoreset1) (line lt scoreset2), name(eq1)
+ *twoway (line scoreset1 scoreset2 lt) , name(eq2)
+ *twoway (line score1 scoreset1m scoreset1p score2), name(eq3)
+ *twoway (line score2 scoreset2m scoreset2p score1), name(eq4)
+ twoway (line score`t' score`=3-`t'' if scoreset`=3-`t''!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''m!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''p!=.), title("Equating score of the Set `t' from the Set `=3-`t''") ytitle("Score `t'") xtitle("Score `=3-`t''") ylabel(0(1)`scoremaxset`t'') xlabel(0(1)`scoremaxset`=3-`t''') name(eq`t'to`=3-`t'')
+ *twoway (line score2 score1 if scoreset1!=.) (line score2 score1 if scoreset1m!=.) (line score2 score1 if scoreset1p!=.), name(eq6)
+ }
+ }
+ *save prout, replace
+ *clear
+
+ qui use `fileeq',clear
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ *su
+ if "`replace'"!=""&("`genlt'"!=""|"`genfit'"!="") {
+ capture drop `genlt' se`genlt' `geninf'
+ }
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 5.1.ado b/Modules/ado/personal/p/pcm 5.1.ado
new file mode 100644
index 0000000..ede39c9
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 5.1.ado
@@ -0,0 +1,1791 @@
+*! Version 5 2August2022
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) EQGraph minsize(int 30)]
+
+preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivist=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'`i'
+ qui gen `genlt'_se=`selatent'`i'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t'
+ qui gen `genlt'`t'_se=`selatent'`t'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit',score(`score')
+ qui gengroup `latent',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+6',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(58) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ tempvar id``i''
+ qui gen `id``i'''=_n if abs(`z``i''')>2*sqrt(`covariates'[1,1])
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."
+ qui su `z``i'''
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-2*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=2*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent', yscale(range(`min'(1)`max')) yline(`=-2*sqrt(`covariates'[1,1])' `=2*sqrt(`covariates'[1,1])',lcolor(blue)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di "``i''" _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local eff=r(N)
+ if `eff'!=0 {
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local mean=r(mean)
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s''
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+
+ }
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local eff=r(N)
+
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local mean=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local exp=r(mean)
+
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`eff`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ }
+ *matrix list `matscorelt'
+}
+
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ qui graph twoway line cum``i'' u, name(ICCc``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi'
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ *tab Tcum
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+ qui graph twoway line Tcum u , name(TCCceo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo'
+ }
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!="" {
+ gen eff=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0
+ *set trace on
+ *set tracedepth 1
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ local legend `" 2 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local ylbl `ylbl' `=-`i'*`unit'' "``i''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`floor'(1)`ceil') color(erose)) (line TInf u,yaxis(2) lwidth(medthick)) (line density u,yaxis(3) lwidth(medthick) ) `scatterj' , xline(0, lcolor(black)) legend(on position(6) order(`"`legend'"') rows(1) subtitle(Threshold parameters) size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(thick) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait - * : dysfunctioning items") xtitle("Latent trait") `fsm'
+*qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`floor'(1)`ceil') color(erose)), name(jbh,replace)
+ *histogram u, name(map,replace)
+ *graph use "map.gph", name(map, replace)
+ *graph combine TIC IIC, xcombine col(1)
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di "``i''" _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+*set trace on
+if "`eqset1'"!="" {
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ *di "set1 (`nbset1') : `eq1_`i''"
+ }
+ *di "`eqset1'"
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ *di "`eqset2'"
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ *di "set2 (`nbset2') : `eq2_`i''"
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ *di "`eq`t'_`i''"
+ *local tmp=""
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ *set trace on
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ *matrix list `diffmat'
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ *matrix list `diffset1'
+ *matrix list `diffset2'
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ *qui gen selt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ *di "matscorelt`t':"
+ *matrix list `matscorelt`t''
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ *qui replace selt=`matscorelt`t''[`=`i'+1',3] if scoreset`t'==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ *list
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ forvalues t=1/2 {
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ *matrix list `matscore`t''
+ di
+ di "{hline 78}"
+ di "EQUATING SET`t' TO SET`=3-`t''"
+ di "{hline 78}"
+ di "Set`t' : `eqset`t''"
+ di "Set`=3-`t'' : `eqset`=3-`t'''"
+ di "{hline 78}"
+ di _col(20) "<----- Latent trait ----->" _col(52) "<------- Score `=3-`t'' --------->"
+ di "Score`t'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ di %4.0f `matscore`t''[`=`s'+1',1] _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `matscore`t''[`=`s'+1',5] _col(66) "[" %5.2f `matscore`t''[`=`s'+1',6] ";" %5.2f `matscore`t''[`=`s'+1',7] "]"
+ }
+ di "{hline 78}"
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ if "`eqgraph'"!="" {
+ *twoway (line lt scoreset1) (line lt scoreset2), name(eq1)
+ *twoway (line scoreset1 scoreset2 lt) , name(eq2)
+ *twoway (line score1 scoreset1m scoreset1p score2), name(eq3)
+ *twoway (line score2 scoreset2m scoreset2p score1), name(eq4)
+ twoway (line score`t' score`=3-`t'' if scoreset`=3-`t''!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''m!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''p!=.), title("Equating score of the Set `t' from the Set `=3-`t''") ytitle("Score `t'") xtitle("Score `=3-`t''") ylabel(0(1)`scoremaxset`t'') xlabel(0(1)`scoremaxset`=3-`t''') name(eq`t'to`=3-`t'')
+ *twoway (line score2 score1 if scoreset1!=.) (line score2 score1 if scoreset1m!=.) (line score2 score1 if scoreset1p!=.), name(eq6)
+ }
+ }
+ *save prout, replace
+ *clear
+
+ qui use `fileeq',clear
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_opt
+ capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=.
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr=`estlt`s'' if `score'==`s'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr=`clt`g'' if `group'==`g'&`genlt'_corr==.
+ }
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=.
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'
+ }
+ }
+ *su
+ qui egen `genlt'_opt=rowmean(`tmpitem'_*)
+ qui egen `genlt'_opt_se=rowsd(`tmpitem'_*)
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*)
+ qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss')
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 5.2.ado b/Modules/ado/personal/p/pcm 5.2.ado
new file mode 100644
index 0000000..2bac1f8
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 5.2.ado
@@ -0,0 +1,1958 @@
+*! Version 5.2 16July2023
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+* Version 5.2: July 16th, 2023 [Jean-Benoit Hardouin] : Add of new graphs for Equating
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [if] [in] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) eqset1name(string) eqset2name(string) EQGraph eqaddset1(real 0) eqaddset2(real 0) eqmultset1(real 1) eqmultset2(real 1) eqwithic eqgenscore(string) subtitle(string) minsize(int 30)]
+
+preserve
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count if `touse'
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ *di "i: `i' ``i''"
+ qui su ``i'' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count if `touse'
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist' if `touse'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist' if `touse', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' if `touse' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'* if `touse',latent se(`selatent'*)
+*di "latent=`latent' "
+*su
+*set trace on
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'1 if `touse'
+ qui gen `genlt'_se=`selatent'1 if `touse'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t' if `touse'
+ qui gen `genlt'`t'_se=`selatent'`t' if `touse'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t' if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit' if `touse',score(`score'`t')
+ qui gengroup `latent'`t' if `touse',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'1+invnorm(uniform())*`selatent'1 if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit' if `touse',score(`score')
+ qui gengroup `latent'1 if `touse',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'&`touse'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit' if `touse'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+6',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.&`touse'
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*) if `touse'
+qui count if `miss'==0&`touse'
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(58) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'1 if `touse'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent'1)^2 if `touse'
+ qui su `se2latent' if `touse'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0 if `touse'
+ qui gen `TInf'=0 if `touse'
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0 if `touse'
+ qui gen `cum_old``i'''=0 if `touse'
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'1-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d') if `touse'
+ qui gen `c_old0_``i'''=1/(`d_old') if `touse'
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'1-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k' if `touse'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k' if `touse'
+ }
+ qui gen `Inf``i'''=0 if `touse'
+ qui gen `Inf_old``i'''=0 if `touse'
+ qui gen `C``i'''=0 if `touse'
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i''' if `touse'
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i''' if `touse'
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i''' if `touse'
+ }
+ qui count if ``i''!=.&`touse'
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2) if `touse'
+ qui su `C2``i''' if `touse'
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2 if `touse'
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i''' if `touse'
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i''' if `touse'
+ qui replace `TInf'=`TInf'+`Inf``i''' if `touse'
+ qui gen `y``i'''=``i''-`cum``i''' if `touse'
+ qui gen `y_old``i'''=``i''-`cum_old``i''' if `touse'
+ qui gen `y2``i'''=(`y``i''')^2 if `touse'
+ qui gen `y2_old``i'''=(`y_old``i''')^2 if `touse'
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i''')) if `touse'
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'&`touse'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'&`touse'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'&`touse'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'&`touse'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'&`touse'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'&`touse'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent'1 "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ tempvar id``i''
+ qui gen `id``i'''=_n if abs(`z``i''')>2*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `z``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-2*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=2*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent' if `touse', yscale(range(`min'(1)`max')) yline(`=-2*sqrt(`covariates'[1,1])' `=2*sqrt(`covariates'[1,1])',lcolor(blue)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2 if `touse'
+ qui su `z2``i''' if `touse'
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.&`touse'
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i''' if `touse'
+ qui su `i``i''' if ``i''!=.&`touse'
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di "``i''" _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)"
+ di as text "**: As suggested by Bond and Fox (2007)"
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf' if `touse'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Iteration `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1') if `touse'
+ `qui' pcm `varlist' [iweight=`sinf'] if `touse',diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1') if `touse'
+ qui su `ecart_`it'' if `touse'
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.&`touse'
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'&`touse'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local eff=r(N)
+ local effscore`s'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local mean=r(mean)
+ *di "local ltscore`s'=`=ceil(`r(mean)'*100)/100'"
+ local ltscore`s'=`=ceil(`r(mean)'*100)/100'
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s''
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+
+ }
+ *set trace on
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local eff=r(N)
+ local eff_md_`g'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local mean=r(mean)
+ local lt_md_`g'=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local exp=r(mean)
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ *set trace off
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`effcompleted`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ if "`scoremin`g''"=="" {
+ local scoremin`g' "."
+ }
+ if "`scoremax`g''"=="" {
+ local scoremax`g' "."
+ }
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ }
+ *matrix list `matscorelt'
+}
+
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ qui graph twoway line cum``i'' u, name(ICCc``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi'
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ *tab Tcum
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+ qui graph twoway line Tcum u , name(TCCceo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo'
+ }
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!=""|"eqset1"!="" {
+ gen eff=0
+ gen eff_md=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ /*le bloc suivant Ă©tait pour avoir des batons par groupe*/
+ /*forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }*/
+ /*le bloc suivant est pour avoir des batons par score*/
+ qui gen uceil=ceil(u*100)/100
+ forvalues s=0/`scoremax' {
+ if `effscore`s''>`effmax' {
+ local effmax=`effscore`s''
+ }
+ *di "`s' qui replace eff=`effscore`s'' if ceil(u*100)/100==`=round(`ltscore`s'',0.01)'"
+ qui replace eff=`effscore`s'' if round(u,0.01)==round(`ltscore`s'',0.01)
+ }
+ forvalues g=1/`nbgroups' {
+ *di "if `eff_md_`g''>`effmax' { (`lt_md_`g'')"
+ if `eff_md_`g''>`effmax' {
+ local effmax=`eff_md_`g''
+ }
+ qui replace eff_md=`eff_md_`g'' if round(u,0.01)==round(`lt_md_`g'',0.01)
+ }
+
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0|eff_md!=0
+ *set trace on
+ *set tracedepth 1
+ *if eff!=0|eff_md!=0 {
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ *}
+ *else {
+ * local floor=-10
+ * local ceil=10
+ *}
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ local legend `"3 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'+1' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local ylbl `ylbl' `=-`i'*`unit'' "``i''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su eff_md
+ local maxe_md=ceil(`=(floor(`r(max)'/10)+1)*10')
+ local maxe=max(`maxe',`maxe_md')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ if "`eqset1'"==""&"`graphs'"!="" {
+ *list eff u uceil if eff!=0&eff!=.
+ *save tmp, replace
+ qui graph twoway (bar eff u, barwidth(.1) yaxis(1) xlabel(`floor'(1)`ceil') color(erose) ) (line TInf u,yaxis(2) lwidth(medthick)) (line density u,yaxis(3) lwidth(medthick) lcolo(green) ) (bar eff_md u, barwidth(.05) yaxis(1) xlabel(`floor'(1)`ceil') color(stred) ) `scatterj' , xline(0, lcolor(black)) legend(on position(6) cols(`modamax') rows(1) order(`"`legend'"') subtitle(Threshold parameters) size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(medium) lpattern(solid) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait - * : dysfunctioning items") xtitle("Latent trait") `fsm'
+ }
+ else if "`eqset1'"!="" {
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+
+ qui tempfile equating
+ qui save `equating', replace
+ }
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di "``i''" _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+if "`eqset1'"!="" {
+ if "`eqgenscore'"!="" {
+ local tmp1 `=ustrlen("`eqgenscore'`eqset1name'")'
+ local tmp2 `=ustrlen("`eqgenscore'`eqset2name'")'
+ local mlength=max(`tmp1',`tmp2')
+ if `mlength'>27 {
+ di as error "The number of characters containing in the strings eqgenscore+eqset1name or eqgenscore+eqset2name must be lesser than 27"
+ di as error "eqgenscore+eqset1name : `tmp1' characters"
+ di as error "eqgenscore+eqset2name : `tmp2' characters"
+ error 130
+ *exit
+ }
+ }
+ if "`eqset1name'"=="" {
+ local eqset1name="Set 1"
+ }
+ if "`eqset2name'"=="" {
+ local eqset2name="Set 2"
+ }
+ local eqset1name `=regexreplaceall("`eqset1name'"," ","_",.)'
+ local eqset2name `=regexreplaceall("`eqset2name'"," ","_",.)'
+ *di "set1:`eqset1name' set2:`eqset2name'"
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ }
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ local pciset1
+ local pciset2
+ *set trace on
+ local minimini=0
+ local maximaxi=0
+ forvalues t=1/2 {
+ qui gen adjscore`t'=(score`t'+`eqaddset`t'')*`eqmultset`t''
+ qui gen adjscore`=3-`t''=(score`=3-`t''+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ *set trace on
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ if `ceil'==0 {
+ local ceil=1
+ }
+ if "`eqwithic'"=="" {
+ local pciset`t' `pciset`t'' scatteri `=-`ceil'/5*`t'' `r(mean)' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)||
+ }
+ local mean=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ local moins=r(mean)
+ if `moins'<`minimini' {
+ *di "local minimini=floor(`moins')"
+ local minimini=floor(`moins')
+ }
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ local plus=r(mean)
+ if `plus'>`maximaxi' {
+ *di "local maximaxi=ceil(`plus')"
+ local maximaxi=ceil(`plus')
+ }
+
+ if "`eqwithic'"!="" {
+ local y=-`ceil'/5*((2.5*`t'-2)+2*(`s'/`scoremaxset`t''))
+ *local pciset`t' `pciset`t'' scatteri `y' `mean' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ local pciset`t' `pciset`t'' scatteri `y' `mean' , mlabsize(tiny) mcolor(black) mlabcolor(black)|| scatteri `y' `moins' (9) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , msize(0) mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ }
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ di as text
+ di as text "{hline 78}"
+ di as text "EQUATING `eqset`t'name' TO `eqset`=3-`t''name'"
+ di as text "{hline 78}"
+ di "`eqset`t'name' : `eqset`t''"
+ di "`eqset`=3-`t''name' : `eqset`=3-`t'''"
+ local eqset`t'namea=abbrev("`eqset`t'name'",18)
+ local eqset`=3-`t''namea=abbrev("`eqset`=3-`t''name'",12)
+ di "{hline 78}"
+ di "Score" _col(20) "<----- Latent trait ----->" _col(52) "<- Score `eqset`=3-`t''namea'" _col(77) "->"
+ di "`eqset`t'namea'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+
+ di %4.0f `=(`matscore`t''[`=`s'+1',1]+`eqaddset`t'')*`eqmultset`t''' _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' _col(66) "[" %5.2f `min' ";" %5.2f `max' "]"
+ }
+ di "{hline 78}"
+ if "`eqgraph'"!="" {
+ *set trace on
+ if `eqmultset`=3-`t'''>0 {
+ local xlabel "`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''(`=ceil((`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''"
+ }
+ else {
+ local xlabel "`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''(`=ceil((-`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''"
+ }
+ if `eqmultset`t''>0 {
+ local ylabel "`=`eqaddset`t''*`eqmultset`t'''(`=ceil((`scoremaxset`t''*`eqmultset`t'')/20)')`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''"
+ }
+ else {
+ local ylabel "`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''(`=ceil((-`scoremaxset`t''*`eqmultset`t'')/20)')`=`eqaddset`t''*`eqmultset`t'''"
+ }
+ *set trace off
+ *di "xlabel : `xlabel'"
+ *di "subtitle=`subtitle'"
+ twoway (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''!=.,lcolor(black) lpattern(solid) lwidth(thick)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''m!=.,lcolor(black) lpattern(dash) lwidth(thin)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''p!=.,lcolor(black) lpattern(dash) lwidth(thin)), title("Equating score of `eqset`=3-`t''name' to `eqset`t'name' ") ytitle("Score `eqset`t'name'") xtitle("Score `eqset`=3-`t''name'") ylabel(`ylabel') xlabel(`xlabel') name(eq`t'to`=3-`t'') legend(order(1 2) label(1 "Estimated") label(2 "95%IC") position(6)) subtitle("`subtitle'")
+ }
+ qui drop adjscore`t' adjscore`=3-`t''
+ }
+
+ if "`eqgraph'"!="" {
+ qui use "`equating'",clear
+ qui su u
+ local flooru=floor(`r(min)')
+ local ceilu=ceil(`r(max)')
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+ if `ceil'==0 {
+ local ceil=1
+ }
+
+ local title "Equating"
+ if "`eqset1name'"!=""&"`eqset2name'"!=""{
+ local title "Equating between `eqset1name' and `eqset2name'"
+ }
+ if "`eqwithic'"=="" {
+ local ylabel1=-`ceil'/5
+ local ylabel2=-2*`ceil'/5
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ else {
+ local ylabel1=-0.5*`ceil'/5
+ local ylabel2=-3*`ceil'/5
+ local flooru=min(`flooru',`minimini')
+ local ceilu=max(`ceilu',`maximaxi')
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(1)`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle( Frequencies) ylabel(`=-`ceil'/5*2' `eqset1name' `=-`ceil'/5' `eqset2name' 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title(Equating) xsize(12) ysize(9) xtitle(Latent trait) "
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(`gapu')`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle(" Frequencies") /*ylabel(`ylbl', grid angle(0) axis(1))*/ ylabel(`ylabel1' "`eqset1name'" `ylabel2' "`eqset2name'" 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title("`title'") subtitle("`subtitle'") xsize(12) ysize(9) xtitle("Latent trait")
+ }
+ qui use `fileeq',clear
+ *set trace on
+ tempname scoreset1 scoreset2
+ forvalues t=1/2 {
+ qui genscore `eqset`t'' if `touse',score(`scoreset`t'')
+ qui su `scoreset`t'' if `touse'
+ local maxscoreset=r(max)
+ *qui matrix list `matscore`t''
+ if "`eqgenscore'"!="" {
+ local eqgenscore `=regexreplaceall("`eqgenscore'"," ","_")'
+ *di "eqgenscore : `eqgenscore'"
+ foreach k in mean min max alea {
+ capture confirm variable `eqgenscore'_`k'_`eqset`=3-`t''name'
+ if _rc==0&"`replace'"!="" {
+ qui replace `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ else if _rc==0&"`replace'"!="" {
+ di as error "The variable `eqgenscore'_`k'_`eqset`=3-`t''name' already exists"
+ error 198
+ }
+ else {
+ qui gen `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ }
+ *tab `scoreset`t''
+ forvalues s=0/`maxscoreset' {
+ *di "qui replace `eqgenscore'_`eqset`=3-`t''name'=`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' if `scoreset`t''==`s'"
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ qui replace `eqgenscore'_mean_`eqset`=3-`t''name'=round(`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_min_`eqset`=3-`t''name'=round(`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_max_`eqset`=3-`t''name'=round(`max',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_alea_`eqset`=3-`t''name'=round(uniform()*(`max'-`min')+`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ }
+ }
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ }
+
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ *set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_opt
+ capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=. if `touse'
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr=`estlt`s'' if `score'==`s'&`touse'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr=`clt`g'' if `group'==`g'&`genlt'_corr==.&`touse'
+ }
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=. if `touse'
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'&`touse'
+ }
+ }
+ *su
+ qui egen `genlt'_opt=rowmean(`tmpitem'_*) if `touse'
+ qui egen `genlt'_opt_se=rowsd(`tmpitem'_*) if `touse'
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*) if `touse'
+ qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss') if `touse'
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 5.3.ado b/Modules/ado/personal/p/pcm 5.3.ado
new file mode 100644
index 0000000..ae440ec
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 5.3.ado
@@ -0,0 +1,2218 @@
+*! Version 5.3 21July2023
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+* Version 5.2: July 16th, 2023 [Jean-Benoit Hardouin] : Add of new graphs for Equating
+* Version 5.3: July 21th, 2023 [Jean-Benoit Hardouin] : Improvement for the docx option
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [if] [in] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems noCORRected filesave dirsave(string) docx(string) extension(string) alpha(real 0.01) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) eqset1name(string) eqset2name(string) EQGraph eqaddset1(real 0) eqaddset2(real 0) eqmultset1(real 1) eqmultset2(real 1) eqwithic eqgenscore(string) DIMname(string) minsize(int 30) vardif(varname) itemsdif(varlist)]
+
+version 14
+preserve
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+if "`corrected'"!="" {
+ local xtitle "Latent trait"
+}
+else {
+ local xtitle "Corrected latent trait"
+}
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count if `touse'
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ *di "i: `i' ``i''"
+ qui su ``i'' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count if `touse'
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist' if `touse'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist' if `touse', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' if `touse' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'* if `touse',latent se(`selatent'*)
+*di "latent=`latent' "
+*su
+*set trace on
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'1 if `touse'
+ qui gen `genlt'_se=`selatent'1 if `touse'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t' if `touse'
+ qui gen `genlt'`t'_se=`selatent'`t' if `touse'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t' if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit' if `touse',score(`score'`t')
+ qui gengroup `latent'`t' if `touse',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'1+invnorm(uniform())*`selatent'1 if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit' if `touse',score(`score')
+ qui gengroup `latent'1 if `touse',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'&`touse'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit' if `touse'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+6',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.&`touse'
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*) if `touse'
+qui count if `miss'==0&`touse'
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(58) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'1 if `touse'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent'1)^2 if `touse'
+ qui su `se2latent' if `touse'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED VALUES OF THE LT ESTIMATORS (values of lt that explained the best the score)
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ *set trace on
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues l=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`l''
+ }
+ qui gen ecart=.
+ forvalues l=0/`scoremax' {
+ if `l'==0 {
+ local j=0.25
+ }
+ else if `l'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`l'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`l'=`r(mean)'
+ *qui su TInf if round(ecart, 0.01)==round(`tmp',0.01)
+ *local setlt`l'=sqrt(1/`r(mean)')
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+*set trace on
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+/*Quelques explications
+latent : estimation EAP du trait latent
+latent2 : estimation Plausible Value Ă partir de l'estimation EAP
+corrlatent : estimation corrigée cherchant la meilleur valeur du trait latent qui explique le score, interpolation à partir de l'EAP pour les individus avec des données manquantes
+*/
+
+
+if "`visit'"==""{
+ tempvar corrlatent corrlatenttmp
+ qui gen `corrlatenttmp'=.
+ forvalues s=0/`scoremax' {
+ qui replace `corrlatenttmp'=`estlt`s'' if `score'==`s'
+ }
+ qui ipolate `corrlatenttmp' `latent'1 , generate(`corrlatent') epolate
+ *list `corrlatenttmp' `latent2' `corrlatent'
+ qui replace `corrlatent'=`corrlatenttmp' if `corrlatenttmp'!=.
+ *su `corrlatenttmp' `latent2' `corrlatent'
+ *twoway (scatter `corrlatent' `score') (scatter `latent2' `score')
+
+ tempname fit
+ qui matrix `fit'=J(`nbitems',6,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT" "corrOUTFIT" "corrINFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0 if `touse'
+ qui gen `TInf'=0 if `touse'
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+ tempvar corrcum``i'' corrc0_``i'' corrInf``i'' corry``i'' corrz``i'' corrz2``i'' corri``i''
+
+ local d=1
+ local corrd=1
+ local d_old=1
+ qui gen `corrcum``i'''=0 if `touse'
+ qui gen `cum``i'''=0 if `touse'
+ qui gen `cum_old``i'''=0 if `touse'
+ forvalues k=1/`mm' {
+ local corrd `corrd'+exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'1-`diffmat2'[`i',`k'])
+ }
+ qui gen `corrc0_``i'''=1/(`corrd') if `touse'
+ qui gen `c0_``i'''=1/(`d') if `touse'
+ qui gen `c_old0_``i'''=1/(`d_old') if `touse'
+ forvalues k=1/`mm' {
+ tempvar corrc`k'_``i'' c`k'_``i'' c_old`k'_``i''
+ qui gen `corrc`k'_``i'''=exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])/(`corrd') if `touse'
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'1-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui replace `corrcum``i'''=`corrcum``i'''+`corrc`k'_``i'''*`k' if `touse'
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k' if `touse'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k' if `touse'
+ }
+ qui gen `corrInf``i'''=0 if `touse'
+ qui gen `Inf``i'''=0 if `touse'
+ qui gen `Inf_old``i'''=0 if `touse'
+ qui gen `C``i'''=0 if `touse'
+ forvalues k=0/`mm' {
+ qui replace `corrInf``i'''=`corrInf``i'''+(`k'-`corrcum``i''')^2*`corrc`k'_``i''' if `touse'
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i''' if `touse'
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i''' if `touse'
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i''' if `touse'
+ }
+ qui count if ``i''!=.&`touse'
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2) if `touse'
+ qui su `C2``i''' if `touse'
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2 if `touse'
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i''' if `touse'
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i''' if `touse'
+ qui replace `TInf'=`TInf'+`Inf``i''' if `touse'
+ qui gen `corry``i'''=``i''-`corrcum``i''' if `touse'
+ qui gen `y``i'''=``i''-`cum``i''' if `touse'
+ qui gen `y_old``i'''=``i''-`cum_old``i''' if `touse'
+ qui gen `y2``i'''=(`y``i''')^2 if `touse'
+ qui gen `y2_old``i'''=(`y_old``i''')^2 if `touse'
+ qui gen `corrz``i'''=(`corry``i'''/sqrt(`corrInf``i''')) if `touse'
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i''')) if `touse'
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'&`touse'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'&`touse'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'&`touse'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'&`touse'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'&`touse'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'&`touse'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `corrz``i''' "Corrected standardized residuals associated to ``i''"
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent'1 "Latent trait"
+ label variable `corrlatent' "Corrected latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ *set trace on
+ *set tracedepth 1
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ local thr=abs(invnorm(`alpha'/2))
+ tempvar id``i''
+ if "`corrected'"!="" {
+ qui gen `id``i'''=_n if abs(`z``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `z``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent' if `touse', ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])',lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ else {
+ *set trace on
+ qui gen `id``i'''=_n if abs(`corrz``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `corrz``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+ qui graph twoway scatter `corrz``i''' `corrlatent' if `touse', ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])',lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs' /*colorvar(`group') colordiscrete*/
+ }
+ *set trace off
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2 if `touse'
+ qui su `z2``i''' if `touse'
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.&`touse'
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i''' if `touse'
+ qui su `i``i''' if ``i''!=.&`touse'
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+
+ /*corrected*/
+ qui gen `corrz2``i'''=(`corrz``i''')^2 if `touse'
+ qui su `corrz2``i''' if `touse'
+ local corrOUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',5]=`corrOUTFIT``i'''
+ *local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ *qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `corrInf``i''' if ``i''!=.&`touse'
+ local corrsumw``i''=r(sum)
+ qui gen `corri``i'''=`corrInf``i'''*`corrz2``i''' if `touse'
+ qui su `corri``i''' if ``i''!=.&`touse'
+ local corrINFIT``i'' = `=`r(sum)'/`corrsumw``i''''
+ qui matrix `fit'[`i',6]=`corrINFIT``i'''
+ *local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ *qui matrix `fit'[`i',4]=`INFITs``i'''
+
+
+ if "`postpce'"=="" {
+ di "``i''" _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i''' /*_col(94) %5.3f `corrOUTFIT``i''' _col(109) %5.3f `corrINFIT``i'''*/
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)"
+ di as text "**: As suggested by Bond and Fox (2007)"
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf' if `touse'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Iteration `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1') if `touse'
+ `qui' pcm `varlist' [iweight=`sinf'] if `touse',diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1') if `touse'
+ qui su `ecart_`it'' if `touse'
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*ANCIENNE PLACE DES CORRECTED VALUES*/
+
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt matgroupscorelt
+ *di "qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)"
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ qui matrix `matgroupscorelt'=J(`=`nbitems'*`modamax'+1'+2*`nbgroups'',7,.)
+ qui matrix colnames `matgroupscorelt'="Group" "Score" "Frequency" "Estimation of latent trait" "s.e. of latent trait" "Expected score" "Corrected latent trait"
+
+ local row=1
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.&`touse'
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'&`touse'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local eff=r(N)
+ local effscore`s'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local mean=r(mean)
+ *di "local ltscore`s'=`=ceil(`r(mean)'*100)/100'"
+ local ltscore`s'=`=ceil(`r(mean)'*100)/100'
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s'' `setlt`s''
+ }
+ *set trace on
+ *matrix list `matscorelt'
+ qui matrix `matscorelt'[`=`s'+1',1]=`eff'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ *set trace off
+ }
+
+ }
+ *set trace on
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local eff=r(N)
+ local eff_md_`g'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local mean=r(mean)
+ local lt_md_`g'=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local exp=r(mean)
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) /*%5.2f `exp'*/
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ *qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ }
+ *set trace off
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`effcompleted`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ if "`scoremin`g''"=="" {
+ local scoremin`g' "."
+ }
+ if "`scoremax`g''"=="" {
+ local scoremax`g' "."
+ }
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+ qui matrix `matgroupscorelt'=`matgroupscorelt'[1..`nbrowmat',1..7]
+ *matrix list `matscorelt'
+}
+
+*set trace on
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("`xtitle'") `fsc'
+ if "`corrected'"!="" {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ else {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi'
+ }
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ *tab Tcum
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fstii saving("`dirsave'//TICi",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("`xtitle'") `fst' subtitle(`dimname')
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("`xtitle'") `fsi' subtitle(`dimname')
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("`xtitle'") `fsti' subtitle(`dimname')
+ qui graph twoway (line Inf* u, lwidth(thin)) (line TInf u, lwidth(thick)), name(TIC,replace) title("Test/Item Information Curve") ytitle("Information") xtitle("`xtitle'") `fstii' subtitle(`dimname')
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ }
+ if "`graphs'"!="" {
+ if "`corrected'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo' subtitle(`dimname')
+ }
+ else {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo' subtitle(`dimname')
+ }
+ }
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!=""|"eqset1"!="" {
+ gen eff=0
+ gen eff_md=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ /*le bloc suivant Ă©tait pour avoir des batons par groupe*/
+ /*forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }*/
+ /*le bloc suivant est pour avoir des batons par score*/
+ qui gen uceil=ceil(u*100)/100
+ forvalues s=0/`scoremax' {
+ if `effscore`s''>`effmax' {
+ local effmax=`effscore`s''
+ }
+ *di "`s' qui replace eff=`effscore`s'' if ceil(u*100)/100==`=round(`ltscore`s'',0.01)'"
+ qui replace eff=`effscore`s'' if round(u,0.01)==round(`ltscore`s'',0.01)
+ }
+ forvalues g=1/`nbgroups' {
+ *di "if `eff_md_`g''>`effmax' { (`lt_md_`g'')"
+ if `eff_md_`g''>`effmax' {
+ local effmax=`eff_md_`g''
+ }
+ qui replace eff_md=`eff_md_`g'' if round(u,0.01)==round(`lt_md_`g'',0.01)
+ }
+
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0|eff_md!=0
+ *set trace on
+ *set tracedepth 1
+ *if eff!=0|eff_md!=0 {
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ *}
+ *else {
+ * local floor=-10
+ * local ceil=10
+ *}
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ local legend `"3 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'+1' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local ylbl `ylbl' `=-`i'*`unit'' "``i''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su eff_md
+ local maxe_md=ceil(`=(floor(`r(max)'/10)+1)*10')
+ local maxe=max(`maxe',`maxe_md')
+ qui su TInf
+ local maxi=1.2*ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ if "`eqset1'"==""&"`graphs'"!="" {
+ *list eff u uceil if eff!=0&eff!=.
+ *save tmp, replace
+ qui graph twoway (bar eff u, barwidth(.1) yaxis(1) xlabel(`floor'(1)`ceil') color(erose) ) (line TInf u,yaxis(2) lwidth(medthick)) (line density u,yaxis(3) lwidth(medthick) lcolo(green) ) (bar eff_md u, barwidth(.05) yaxis(1) xlabel(`floor'(1)`ceil') color(stred) ) `scatterj' , xline(0, lcolor(black)) legend(on position(6) cols(`modamax') rows(1) order(`"`legend'"') subtitle(Threshold parameters) size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(medium) lpattern(solid) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait - * : dysfunctioning items") xtitle("`xtitle'") `fsm' subtitle(`dimname')
+ }
+ else if "`eqset1'"!="" {
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+
+ qui tempfile equating
+ qui save `equating', replace
+ }
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di "``i''" _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+if "`eqset1'"!="" {
+ if "`eqgenscore'"!="" {
+ local tmp1 `=ustrlen("`eqgenscore'`eqset1name'")'
+ local tmp2 `=ustrlen("`eqgenscore'`eqset2name'")'
+ local mlength=max(`tmp1',`tmp2')
+ if `mlength'>27 {
+ di as error "The number of characters containing in the strings eqgenscore+eqset1name or eqgenscore+eqset2name must be lesser than 27"
+ di as error "eqgenscore+eqset1name : `tmp1' characters"
+ di as error "eqgenscore+eqset2name : `tmp2' characters"
+ error 130
+ *exit
+ }
+ }
+ if "`eqset1name'"=="" {
+ local eqset1name="Set 1"
+ }
+ if "`eqset2name'"=="" {
+ local eqset2name="Set 2"
+ }
+ local eqset1name `=regexreplaceall("`eqset1name'"," ","_",.)'
+ local eqset2name `=regexreplaceall("`eqset2name'"," ","_",.)'
+ *di "set1:`eqset1name' set2:`eqset2name'"
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ }
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ local pciset1
+ local pciset2
+ *set trace on
+ local minimini=0
+ local maximaxi=0
+ forvalues t=1/2 {
+ qui gen adjscore`t'=(score`t'+`eqaddset`t'')*`eqmultset`t''
+ qui gen adjscore`=3-`t''=(score`=3-`t''+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ *set trace on
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ if `ceil'==0 {
+ local ceil=1
+ }
+ if "`eqwithic'"=="" {
+ local pciset`t' `pciset`t'' scatteri `=-`ceil'/5*`t'' `r(mean)' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)||
+ }
+ local mean=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ local moins=r(mean)
+ if `moins'<`minimini' {
+ *di "local minimini=floor(`moins')"
+ local minimini=floor(`moins')
+ }
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ local plus=r(mean)
+ if `plus'>`maximaxi' {
+ *di "local maximaxi=ceil(`plus')"
+ local maximaxi=ceil(`plus')
+ }
+
+ if "`eqwithic'"!="" {
+ local y=-`ceil'/5*((2.5*`t'-2)+2*(`s'/`scoremaxset`t''))
+ *local pciset`t' `pciset`t'' scatteri `y' `mean' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ local pciset`t' `pciset`t'' scatteri `y' `mean' , mlabsize(tiny) mcolor(black) mlabcolor(black)|| scatteri `y' `moins' (9) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , msize(0) mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ }
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ di as text
+ di as text "{hline 78}"
+ di as text "EQUATING `eqset`t'name' TO `eqset`=3-`t''name'"
+ di as text "{hline 78}"
+ di "`eqset`t'name' : `eqset`t''"
+ di "`eqset`=3-`t''name' : `eqset`=3-`t'''"
+ local eqset`t'namea=abbrev("`eqset`t'name'",18)
+ local eqset`=3-`t''namea=abbrev("`eqset`=3-`t''name'",12)
+ di "{hline 78}"
+ di "Score" _col(20) "<----- Latent trait ----->" _col(52) "<- Score `eqset`=3-`t''namea'" _col(77) "->"
+ di "`eqset`t'namea'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+
+ di %4.0f `=(`matscore`t''[`=`s'+1',1]+`eqaddset`t'')*`eqmultset`t''' _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' _col(66) "[" %5.2f `min' ";" %5.2f `max' "]"
+ }
+ di "{hline 78}"
+ if "`eqgraph'"!="" {
+ *set trace on
+ if `eqmultset`=3-`t'''>0 {
+ local xlabel "`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''(`=ceil((`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''"
+ }
+ else {
+ local xlabel "`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''(`=ceil((-`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''"
+ }
+ if `eqmultset`t''>0 {
+ local ylabel "`=`eqaddset`t''*`eqmultset`t'''(`=ceil((`scoremaxset`t''*`eqmultset`t'')/20)')`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''"
+ }
+ else {
+ local ylabel "`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''(`=ceil((-`scoremaxset`t''*`eqmultset`t'')/20)')`=`eqaddset`t''*`eqmultset`t'''"
+ }
+ *set trace off
+ *di "xlabel : `xlabel'"
+ *di "subtitle=`subtitle'"
+ twoway (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''!=.,lcolor(black) lpattern(solid) lwidth(thick)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''m!=.,lcolor(black) lpattern(dash) lwidth(thin)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''p!=.,lcolor(black) lpattern(dash) lwidth(thin)), title("Equating score of `eqset`=3-`t''name' to `eqset`t'name' ") ytitle("Score `eqset`t'name'") xtitle("Score `eqset`=3-`t''name'") ylabel(`ylabel') xlabel(`xlabel') name(eq`t'to`=3-`t'') legend(order(1 2) label(1 "Estimated") label(2 "95%IC") position(6)) subtitle("`dimname'")
+ }
+ qui drop adjscore`t' adjscore`=3-`t''
+ }
+
+ if "`eqgraph'"!="" {
+ qui use "`equating'",clear
+ qui su u
+ local flooru=floor(`r(min)')
+ local ceilu=ceil(`r(max)')
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+ if `ceil'==0 {
+ local ceil=1
+ }
+
+ local title "Equating"
+ if "`eqset1name'"!=""&"`eqset2name'"!=""{
+ local title "Equating between `eqset1name' and `eqset2name'"
+ }
+ if "`eqwithic'"=="" {
+ local ylabel1=-`ceil'/5
+ local ylabel2=-2*`ceil'/5
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ else {
+ local ylabel1=-0.5*`ceil'/5
+ local ylabel2=-3*`ceil'/5
+ local flooru=min(`flooru',`minimini')
+ local ceilu=max(`ceilu',`maximaxi')
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(1)`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle( Frequencies) ylabel(`=-`ceil'/5*2' `eqset1name' `=-`ceil'/5' `eqset2name' 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title(Equating) xsize(12) ysize(9) xtitle(Latent trait) "
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(`gapu')`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle(" Frequencies") /*ylabel(`ylbl', grid angle(0) axis(1))*/ ylabel(`ylabel1' "`eqset1name'" `ylabel2' "`eqset2name'" 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title("`title'") subtitle("`dimname'") xsize(12) ysize(9) xtitle("Latent trait")
+ }
+ qui use `fileeq',clear
+ *set trace on
+ tempname scoreset1 scoreset2
+ forvalues t=1/2 {
+ qui genscore `eqset`t'' if `touse',score(`scoreset`t'')
+ qui su `scoreset`t'' if `touse'
+ local maxscoreset=r(max)
+ *qui matrix list `matscore`t''
+ if "`eqgenscore'"!="" {
+ local eqgenscore `=regexreplaceall("`eqgenscore'"," ","_")'
+ *di "eqgenscore : `eqgenscore'"
+ foreach k in mean min max random {
+ capture confirm variable `eqgenscore'_`k'_`eqset`=3-`t''name'
+ if _rc==0&"`replace'"!="" {
+ qui replace `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ else if _rc==0&"`replace'"!="" {
+ di as error "The variable `eqgenscore'_`k'_`eqset`=3-`t''name' already exists"
+ error 198
+ }
+ else {
+ qui gen `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ }
+ *tab `scoreset`t''
+ forvalues s=0/`maxscoreset' {
+ *di "qui replace `eqgenscore'_`eqset`=3-`t''name'=`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' if `scoreset`t''==`s'"
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ qui replace `eqgenscore'_mean_`eqset`=3-`t''name'=round(`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_min_`eqset`=3-`t''name'=round(`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_max_`eqset`=3-`t''name'=round(`max',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_random_`eqset`=3-`t''name'=round(uniform()*(`max'-`min')+`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ }
+ }
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ }
+
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+*set trace on
+if "`visit'"!="" {
+ tempfile sauv
+ *set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_opt
+ capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=`corrlatent' if `touse'
+/* qui gen `genlt'_corr2=. if `touse'
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr2=`estlt`s'' if `score'==`s'&`touse'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr2=`clt`g'' if `group'==`g'&`genlt'_corr==.&`touse'
+ }
+*/
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=. if `touse'
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'&`touse'
+ }
+ }
+ *su
+ qui egen `genlt'_opt=rowmean(`tmpitem'_*) if `touse'
+ *qui egen `genlt'_opt_se=rowsd(`tmpitem'_*) if `touse'
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*) if `touse'
+ *qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss') if `touse'
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin, footer(fall_report)
+ putdocx table hdr = (1, 3), border(all, nil) tofooter(fall_report)
+ if "`rsm'"=="" {
+ putdocx table hdr(1, 1) = ("Partial Credit Model")
+ }
+ else {
+ putdocx table hdr(1, 1) = ("Rating Scale Model")
+ }
+ putdocx table hdr(1, 2) = ("`dimname'"), halign(center)
+ putdocx table hdr(1, 3) = ("Page "), pagenumber
+ putdocx table hdr(1, 3) = ("/"), totalpages append
+ putdocx table hdr(1, 3), halign(right)
+ putdocx paragraph ,style(Title)
+ if "`dimname'" =="" {
+ local dimname2 "Rasch analysis"
+ }
+ else {
+ local dimname2 "Rasch analysis of the `dimname' dimension"
+ }
+ putdocx text ("`dimname2'") ,
+ putdocx paragraph ,style(Subtitle)
+ putdocx text ("General informations") ,
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("Names of the dimension: `dimname'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation of the parameters") ,
+ local paramname
+ forvalues j=1/`nbitems' {
+ forvalues k=1/`modamax' {
+ if `k'<=`modamax`j'' {
+ local paramname `paramname' "``j''_`k'"
+ }
+ }
+ }
+ *di "matrix colnames `diff'=`paramname'"
+ matrix rownames `diff'=`paramname'
+ putdocx table table1 = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1) halign(center)
+ putdocx table table1(.,1), halign(left)
+ putdocx table table1(.,2/7), halign(right)
+ putdocx table table1(1,.), halign(right) border(top) border(bottom)
+
+
+ qui putdocx table table2 = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table2(.,1), halign(left)
+ putdocx table table2(.,2/7), halign(right)
+ putdocx table table2(1,.), halign(right) border(top) border(bottom)
+
+
+
+
+ putdocx paragraph,style(Subtitle)
+ putdocx text ("Fit indexes for items") , /*bold underline font(,14) smallcaps*/
+ qui putdocx table table3 = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table3(.,1), halign(left)
+ putdocx table table3(.,2/5), halign(right)
+ putdocx table table3(1,.), halign(right) border(top) border(bottom)
+
+
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation per group/score")
+ *putdocx text ("Estimation per group/score") , bold underline font(,14) smallcaps
+ *set trace on
+ putdocx table tbl = (`=`nbrowmat'+1',7), border(all,nil) width(7) halign(center) note(EAP: Expected A Posteriori ; BE: Best Estimates) headerrow(1)
+ putdocx table tbl(1,.), halign(right) border(top) border(bottom)
+ putdocx table tbl(1,1) = ("Group"), halign(right)
+ putdocx table tbl(1,2) = ("score"), halign(right)
+ putdocx table tbl(1,3) = ("Frequency"), halign(right)
+ putdocx table tbl(1,4) = ("EAP Mean"), halign(right)
+ putdocx table tbl(1,5) = ("EAP s.e."), halign(right)
+ putdocx table tbl(1,6) = ("Exp score"), halign(right)
+ putdocx table tbl(1,7) = ("BE Mean"), halign(right)
+ local fin=1
+ forvalues row=1/`nbrowmat' {
+ local row2=`row'+1
+ local g: di %9.0f `matgroupscorelt'[`row',1]
+ local gh=`matgroupscorelt'[`row',1]
+ if `fin'==1 {
+ putdocx table tbl(`row2',1) = ("`g'"), halign(right)
+ }
+ if `matgroupscorelt'[`row',2]!=.|`matgroupscorelt'[`row',7]==. {
+ local s: di %9.0f `matgroupscorelt'[`row',2]
+ local fin=0
+ }
+ else {
+ local s "`scoremin`gh''/`scoremax`gh''"
+ local fin=1
+ *local fin "border(top) border(bottom)"
+ *di "c'est la fin"
+ putdocx table tbl(`row2',.), border(bottom) border(top, dashed)
+ putdocx table tbl(`row2',1), border(top, nil)
+ }
+ local eff: di %9.0f `matgroupscorelt'[`row',3]
+ local lt: di %9.3f `matgroupscorelt'[`row',4]
+ local se: di %9.3f `matgroupscorelt'[`row',5]
+ local exp: di %9.2f `matgroupscorelt'[`row',6]
+ local clt: di %9.3f `matgroupscorelt'[`row',7]
+ *putdocx table tbl(`row',.), addrows(7)
+ putdocx table tbl(`row2',2) = ("`s'"), halign(right)
+ putdocx table tbl(`row2',3) = ("`eff'"), halign(right)
+ putdocx table tbl(`row2',4) = ("`lt'"), halign(right)
+ putdocx table tbl(`row2',5) = ("`se'"), halign(right)
+ putdocx table tbl(`row2',6) = ("`exp'"), halign(right)
+ putdocx table tbl(`row2',7) = ("`clt'"), halign(right)
+
+ }
+
+/*
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+
+
+local row 1
+local vari 1
+foreach x in gear_ratio turn foreign _cons {
+putdocx table tbl5(`row',.), addrows(2)
+local b: display %9.3f rtable[`vari',1]
+local se: display %9.3f rtable[`vari',2]
+local ++vari
+local ++row
+putdocx table tbl5(`row',1) = ("`x'"), halign(right)
+putdocx table tbl5(`row',2) = ("`b'"), halign(right)
+local ++row
+local se = strtrim("`se'")
+putdocx table tbl5(`row',2) = ("(`se')"), halign(right)
+}*/
+
+ *qui putdocx table tablename = matrix(`matgroupscorelt') , nformat(%9.3f) /*rownames*/ colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("General Graphs")
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Graphs per item")
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph, style(Heading1)
+ putdocx text ("Graphs for ``i''")
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+*set trace on
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix matgroupscorelt=`matgroupscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm 5.4.ado b/Modules/ado/personal/p/pcm 5.4.ado
new file mode 100644
index 0000000..2ef1b82
--- /dev/null
+++ b/Modules/ado/personal/p/pcm 5.4.ado
@@ -0,0 +1,2298 @@
+*! Version 5.4 28July2023
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+* Version 5.2: July 16th, 2023 [Jean-Benoit Hardouin] : Add of new graphs for Equating
+* Version 5.3: July 21th, 2023 [Jean-Benoit Hardouin] : Improvements for the docx option
+* Version 5.4: July 28th, 2023 [Jean-Benoit Hardouin] : Improvements for graphs et corrections of bugs
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [if] [in] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems noCORRected filesave dirsave(string) docx(string) extension(string) alpha(real 0.01) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) eqset1name(string) eqset2name(string) EQGraph eqaddset1(real 0) eqaddset2(real 0) eqmultset1(real 1) eqmultset2(real 1) eqwithci eqgenscore(string) DIMname(string) minsize(int 30) vardif(varname) itemsdif(varlist) noRESiduals]
+
+version 14
+preserve
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+if "`corrected'"!="" {
+ local xtitle "Latent trait"
+}
+else {
+ local xtitle "Corrected latent trait"
+}
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count if `touse'
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local name``i'': variable label ``i''
+ if "`name``i'''"=="" {
+ local name``i'' ``i''
+ }
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ *di "i: `i' ``i''"
+ qui su ``i'' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count if `touse'
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist' if `touse'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist' if `touse', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' if `touse' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'* if `touse',latent se(`selatent'*)
+*di "latent=`latent' "
+*su
+*set trace on
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'1 if `touse'
+ qui gen `genlt'_se=`selatent'1 if `touse'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t' if `touse'
+ qui gen `genlt'`t'_se=`selatent'`t' if `touse'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t' if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit' if `touse',score(`score'`t')
+ qui gengroup `latent'`t' if `touse',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'1+invnorm(uniform())*`selatent'1 if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit' if `touse',score(`score')
+ qui gengroup `latent'1 if `touse',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'&`touse'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit' if `touse'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+10',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+7']=r(min)
+ matrix `groups'[`g',`=`nbitems'+8']=r(max)
+ qui count if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.&`touse'
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*) if `touse'
+qui count if `miss'==0&`touse'
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of individuals with a complete answer pattern:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+*di "matrix rownames `diff'=`rn'"
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(59) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("`name``i'''",20) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %6.2f `diff'[`t',3] _col(62) %5.3f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %6.2f `diff'[`t',3] _col(62) %5.3f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+ local n: word count `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `continuous'
+ local v2 : variable label `v'
+ if "`v2'"=="" {
+ local v2 `v'
+ }
+ di as text _col(1) %5.2f abbrev("`v2'",20) as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count `categorical'
+ *di "local n: word count of `categorical' "
+ *di "n=`n'"
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local v2 : variable label `v'
+ if "`v2'"=="" {
+ local v2 `v'
+ }
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v2'",20) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'1 if `touse'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent'1)^2 if `touse'
+ qui su `se2latent' if `touse'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED VALUES OF THE LT ESTIMATORS (values of lt that explained the best the score)
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=2*sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ *set trace on
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues l=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`l''
+ }
+ qui gen ecart=.
+ local listlt
+ forvalues l=0/`scoremax' {
+ if `l'==0 {
+ local j=0.25
+ }
+ else if `l'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`l'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`l'=`r(mean)'
+ local listlt `listlt' `estlt`l''
+ *qui su TInf if round(ecart, 0.01)==round(`tmp',0.01)
+ *local setlt`l'=sqrt(1/`r(mean)')
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+*set trace on
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+/*Quelques explications
+latent : estimation EAP du trait latent
+latent2 : estimation Plausible Value Ă partir de l'estimation EAP
+corrlatent : estimation corrigée cherchant la meilleur valeur du trait latent qui explique le score, interpolation à partir de l'EAP pour les individus avec des données manquantes
+*/
+
+
+if "`visit'"==""{
+ tempvar corrlatent corrlatenttmp
+ qui gen `corrlatenttmp'=.
+ forvalues s=0/`scoremax' {
+ qui replace `corrlatenttmp'=`estlt`s'' if `score'==`s'
+ }
+ qui ipolate `corrlatenttmp' `latent'1 , generate(`corrlatent') epolate
+ *list `corrlatenttmp' `latent2' `corrlatent'
+ qui replace `corrlatent'=`corrlatenttmp' if `corrlatenttmp'!=.
+ qui replace `corrlatent'=`latent' if `corrlatenttmp'==.
+ *su `corrlatenttmp' `latent2' `corrlatent'
+ *twoway (scatter `corrlatent' `score') (scatter `latent2' `score')
+ forvalues g=1/`nbgroups' {
+ *di "group=`g'"
+ qui su `corrlatent' if `group'==`g'&`touse'
+ *di "qui matrix `groups'[`g',`=`nbitems'+9']=`r(min)'"
+ *di "qui matrix `groups'[`g',`=`nbitems'+10']=`r(max)'"
+ if r(N)!=0 {
+ qui matrix `groups'[`g',`=`nbitems'+9']=`r(min)'
+ qui matrix `groups'[`g',`=`nbitems'+10']=`r(max)'
+ }
+ }
+ tempname fit
+ qui matrix `fit'=J(`nbitems',6,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT" "corrOUTFIT" "corrINFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0 if `touse'
+ qui gen `TInf'=0 if `touse'
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+ tempvar corrcum``i'' corrc0_``i'' corrInf``i'' corry``i'' corrz``i'' corrz2``i'' corri``i''
+
+ local d=1
+ local corrd=1
+ local d_old=1
+ qui gen `corrcum``i'''=0 if `touse'
+ qui gen `cum``i'''=0 if `touse'
+ qui gen `cum_old``i'''=0 if `touse'
+ forvalues k=1/`mm' {
+ local corrd `corrd'+exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'1-`diffmat2'[`i',`k'])
+ }
+ qui gen `corrc0_``i'''=1/(`corrd') if `touse'
+ qui gen `c0_``i'''=1/(`d') if `touse'
+ qui gen `c_old0_``i'''=1/(`d_old') if `touse'
+ forvalues k=1/`mm' {
+ tempvar corrc`k'_``i'' c`k'_``i'' c_old`k'_``i''
+ qui gen `corrc`k'_``i'''=exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])/(`corrd') if `touse'
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'1-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui replace `corrcum``i'''=`corrcum``i'''+`corrc`k'_``i'''*`k' if `touse'
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k' if `touse'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k' if `touse'
+ }
+ qui gen `corrInf``i'''=0 if `touse'
+ qui gen `Inf``i'''=0 if `touse'
+ qui gen `Inf_old``i'''=0 if `touse'
+ qui gen `C``i'''=0 if `touse'
+ forvalues k=0/`mm' {
+ qui replace `corrInf``i'''=`corrInf``i'''+(`k'-`corrcum``i''')^2*`corrc`k'_``i''' if `touse'
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i''' if `touse'
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i''' if `touse'
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i''' if `touse'
+ }
+ qui count if ``i''!=.&`touse'
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2) if `touse'
+ qui su `C2``i''' if `touse'
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2 if `touse'
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i''' if `touse'
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i''' if `touse'
+ qui replace `TInf'=`TInf'+`Inf``i''' if `touse'
+ qui gen `corry``i'''=``i''-`corrcum``i''' if `touse'
+ qui gen `y``i'''=``i''-`cum``i''' if `touse'
+ qui gen `y_old``i'''=``i''-`cum_old``i''' if `touse'
+ qui gen `y2``i'''=(`y``i''')^2 if `touse'
+ qui gen `y2_old``i'''=(`y_old``i''')^2 if `touse'
+ qui gen `corrz``i'''=(`corry``i'''/sqrt(`corrInf``i''')) if `touse'
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i''')) if `touse'
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+
+ qui su `y2``i''' if `group'==`g'&`touse'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'&`touse'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'&`touse'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'&`touse'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'&`touse'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'&`touse'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `corrz``i''' "Corrected standardized residuals associated to ``i''"
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent'1 "Latent trait"
+ label variable `corrlatent' "Corrected latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ *set trace on
+ *set tracedepth 1
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ local thr=abs(invnorm(`alpha'/2))
+ tempvar id``i''
+ local hline
+ forvalues l=1/`modamax`i'' {
+ local hline `hline' `=`diffmat'[`i',`l']'
+ }
+ if "`residuals'"=="" {
+ if "`corrected'"!="" {
+ qui gen `id``i'''=_n if abs(`z``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `z``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent' if `touse', xline(`hline',lwidth(vthin) lcolor(gray)) colordiscrete colorvar(``i'') colorlist(blue green orange purple gray red cyan ) ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])', lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals") subtitle(`name``i''') `fs'
+ }
+ else {
+ *set trace on
+ qui gen `id``i'''=_n if abs(`corrz``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `corrz``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+ qui graph twoway scatter `corrz``i''' `corrlatent' if `touse',xline(`hline',lwidth(vthin) lcolor(gray)) colordiscrete colorvar(``i'') colorlist(blue green orange purple gray red cyan ) ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])', lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals") subtitle(`name``i''') `fs'
+ }
+ }
+ *set trace off
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2 if `touse'
+ qui su `z2``i''' if `touse'
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.&`touse'
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i''' if `touse'
+ qui su `i``i''' if ``i''!=.&`touse'
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+
+ /*corrected*/
+ qui gen `corrz2``i'''=(`corrz``i''')^2 if `touse'
+ qui su `corrz2``i''' if `touse'
+ local corrOUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',5]=`corrOUTFIT``i'''
+ *local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ *qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `corrInf``i''' if ``i''!=.&`touse'
+ local corrsumw``i''=r(sum)
+ qui gen `corri``i'''=`corrInf``i'''*`corrz2``i''' if `touse'
+ qui su `corri``i''' if ``i''!=.&`touse'
+ local corrINFIT``i'' = `=`r(sum)'/`corrsumw``i''''
+ qui matrix `fit'[`i',6]=`corrINFIT``i'''
+ *local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ *qui matrix `fit'[`i',4]=`INFITs``i'''
+
+
+ if "`postpce'"=="" {
+ di abbrev("`name``i'''",20) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i''' /*_col(94) %5.3f `corrOUTFIT``i''' _col(109) %5.3f `corrINFIT``i'''*/
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Bond and Fox (2007)"
+ di as text "**: As suggested by Wright (Smith, 1998)"
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf' if `touse'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Iteration `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1') if `touse'
+ `qui' pcm `varlist' [iweight=`sinf'] if `touse',diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1') if `touse'
+ qui su `ecart_`it'' if `touse'
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*ANCIENNE PLACE DES CORRECTED VALUES*/
+
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt matgroupscorelt
+ *di "qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)"
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ qui matrix `matgroupscorelt'=J(`=(`nbitems'*`modamax'+1+2*`nbgroups')*4',7,.)
+ qui matrix colnames `matgroupscorelt'="Group" "Score" "Frequency" "Estimation of latent trait" "s.e. of latent trait" "Expected score" "Corrected latent trait"
+
+ local row=1
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.&`touse'
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'&`touse'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local eff=r(N)
+ local effscore`s'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local mean=r(mean)
+ *di "local ltscore`s'=`=ceil(`r(mean)'*100)/100'"
+ local ltscore`s'=`=ceil(`r(mean)'*100)/100'
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s'' `setlt`s''
+ }
+ *set trace on
+ *matrix list `matscorelt'
+ qui matrix `matscorelt'[`=`s'+1',1]=`eff'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ *set trace off
+ }
+
+ }
+ *set trace on
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local eff=r(N)
+ local eff_md_`g'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local mean=r(mean)
+ local lt_md_`g'=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local exp=r(mean)
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) /*%5.2f `exp'*/
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ *qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ }
+ *set trace off
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`effcompleted`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ if "`scoremin`g''"=="" {
+ local scoremin`g' "."
+ }
+ if "`scoremax`g''"=="" {
+ local scoremax`g' "."
+ }
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+ qui matrix `matgroupscorelt'=`matgroupscorelt'[1..`nbrowmat',1..7]
+ *matrix list `matscorelt'
+}
+
+*set trace on
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ local pas=round(`pas')
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local xmin=`groups'[`g',`=`nbitems'+7']
+ local xmax=`groups'[`g',`=`nbitems'+8']
+ local xcmin=`groups'[`g',`=`nbitems'+9']
+ local xcmax=`groups'[`g',`=`nbitems'+10']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=20
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off) || pci `y' `xmin' `y' `xmax' ,lcolor(black)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off) || pci `y' `xcmin' `y' `xcmax' ,lcolor(black)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(X=0)"
+ local xline
+ local yline
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(X=`k')"
+ local xline `xline' `=`diffmat'[`i',`k']'
+ local yline `yline' `=`k'-0.5'
+
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ label variable Inf``i'' "`name``i'''"
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC)) subtitle(`name``i''') ytitle("Probability") xtitle("`xtitle'") `fsc' xline(`xline',lwidth(vthin) lcolor(gray))
+ if "`corrected'"!="" {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC)") subtitle(`name``i''') ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi' xline(`xline',lwidth(vthin) lcolor(gray)) ylabel(0(.5)`modamax`i'')
+ }
+ else {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC)") subtitle(`name``i''') ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi' xline(`xline',lwidth(vthin) lcolor(gray)) ylabel(0(.5)`modamax`i'')
+ }
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fstii saving("`dirsave'//TICi",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ label variable TInf "Information curve"
+
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("`xtitle'") `fst' subtitle(`dimname') ylabel(0(1)`scoremax') xline(`listlt',lwidth(vthin) lcolor(gray))
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("`xtitle'") `fsi' subtitle(`dimname')
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("`xtitle'") `fsti' subtitle(`dimname')
+ qui graph twoway (line Inf* u, lwidth(thin)) (line TInf u, lwidth(thick)), name(TIC,replace) title("Test/Item Information Curve") ytitle("Information") xtitle("`xtitle'") `fstii' subtitle(`dimname')
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ *matrix list `groups'
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local xmin=`groups'[`g',`=`nbitems'+7']
+ local xmax=`groups'[`g',`=`nbitems'+8']
+ local xcmin=`groups'[`g',`=`nbitems'+9']
+ local xcmax=`groups'[`g',`=`nbitems'+10']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=20
+ local s tiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)|| pci `y' `xmin' `y' `xmax' ,lcolor(black)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off) || pci `y' `xcmin' `y' `xcmax' ,lcolor(black)
+ }
+ *set trace on
+ if "`graphs'"!="" {
+ if "`corrected'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo' subtitle(`dimname') xline(`listlt',lwidth(vthin) lcolor(gray))
+ }
+ else {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo' subtitle(`dimname') xline(`listlt',lwidth(vthin) lcolor(gray))
+ }
+ }
+ *set trace off
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!=""|"eqset1"!="" {
+ gen eff=0
+ gen eff_md=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ /*le bloc suivant Ă©tait pour avoir des batons par groupe*/
+ /*forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }*/
+ /*le bloc suivant est pour avoir des batons par score*/
+ qui gen uceil=ceil(u*100)/100
+ forvalues s=0/`scoremax' {
+ if `effscore`s''>`effmax' {
+ local effmax=`effscore`s''
+ }
+ *di "`s' qui replace eff=`effscore`s'' if ceil(u*100)/100==`=round(`ltscore`s'',0.01)'"
+ qui replace eff=`effscore`s'' if round(u,0.01)==round(`ltscore`s'',0.01)
+ }
+ forvalues g=1/`nbgroups' {
+ *di "if `eff_md_`g''>`effmax' { (`lt_md_`g'')"
+ if `eff_md_`g''>`effmax' {
+ local effmax=`eff_md_`g''
+ }
+ qui replace eff_md=`eff_md_`g'' if round(u,0.01)==round(`lt_md_`g'',0.01)
+ }
+
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Complete"
+ label variable eff_md "Incomplete"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0|eff_md!=0
+ *set trace on
+ *set tracedepth 1
+ *if eff!=0|eff_md!=0 {
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ *}
+ *else {
+ * local floor=-10
+ * local ceil=10
+ *}
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ *local legend `"1 2 `=(`modamax'+1)*`nbitems'+1' `=(`modamax'+1)*`nbitems'+2' 3 "1" "'
+ local legend `"5 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'+3' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local nomcourt``i''=abbrev("`name``i'''",20)
+ local ylbl `ylbl' `=-`i'*`unit'' "`nomcourt``i'''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su eff_md
+ local maxe_md=ceil(`=(floor(`r(max)'/10)+1)*10')
+ local maxe=max(`maxe',`maxe_md')
+ qui su TInf
+ local maxi=1.2*ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ if "`eqset1'"==""&"`graphs'"!="" {
+ *list eff u uceil if eff!=0&eff!=.
+ *save tmp, replace
+ *di "`legend'"
+ *di "holes(3/`nbcolslegende' `=`nbcolslegende'+3'/`=`nbcolslegende'*2')"
+ local nbcolslegende=max(2,`modamax')
+ if `modamax'==1 {
+ local holes "holes(2)"
+ }
+ tempvar line1 line2
+ qui gen `line1'=.
+ qui gen `line2'=.
+ label variable `line2' "Density"
+ label variable `line1' "Information"
+ qui graph twoway (line `line1' u ,lwidth(medthick) lcolo(red)) (line `line2' u ,lwidth(medthick) lcolo(green)) (line density u,yaxis(3) lwidth(medthick) lcolo(green) ) (bar eff u, barwidth(.1) yaxis(1) xlabel(`floor'(1)`ceil') color(erose) ) (bar eff_md u, barwidth(.05) yaxis(1) xlabel(`floor'(1)`ceil') color(stred) ) (line TInf u,yaxis(2) lwidth(medthick) lcolo(red) ) `scatterj' , xline(0, lcolor(black)) legend(on position(3) /*symysize(*.6) symxsize(*.6) textwidth(*.6)*/ /*cols(`nbcolslegende')*/ cols(1) `holes' order(`"- "Functions" 2 1 - "" - "Patterns" 3 4 - "" - "Thresholds" `legend' "') /*subtitle(Threshold parameters,size(*.7)) */size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(medium) lpattern(solid) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("* : dysfunctioning items") xtitle("`xtitle'") `fsm' subtitle(`dimname')
+ }
+ else if "`eqset1'"!="" {
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+
+ qui tempfile equating
+ qui save `equating', replace
+ }
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di abbrev("`name``i'''",20) _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+if "`eqset1'"!="" {
+ if "`eqgenscore'"!="" {
+ local tmp1 `=ustrlen("`eqgenscore'`eqset1name'")'
+ local tmp2 `=ustrlen("`eqgenscore'`eqset2name'")'
+ local mlength=max(`tmp1',`tmp2')
+ if `mlength'>27 {
+ di as error "The number of characters containing in the strings eqgenscore+eqset1name or eqgenscore+eqset2name must be lesser than 27"
+ di as error "eqgenscore+eqset1name : `tmp1' characters"
+ di as error "eqgenscore+eqset2name : `tmp2' characters"
+ error 130
+ *exit
+ }
+ }
+ if "`eqset1name'"=="" {
+ local eqset1name="Set_1"
+ }
+ else if `c(version)'>17 {
+ local eqset1name `=regexreplaceall("`eqset1name'"," ","_",.)'
+ }
+ if "`eqset2name'"=="" {
+ local eqset2name="Set_2"
+ }
+ else if `c(version)'>17 {
+ local eqset2name `=regexreplaceall("`eqset2name'"," ","_",.)'
+ }
+ *di "set1:`eqset1name' set2:`eqset2name'"
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ }
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ local pciset1
+ local pciset2
+ *set trace on
+ local minimini=0
+ local maximaxi=0
+ forvalues t=1/2 {
+ qui gen adjscore`t'=(score`t'+`eqaddset`t'')*`eqmultset`t''
+ qui gen adjscore`=3-`t''=(score`=3-`t''+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ *set trace on
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ if `ceil'==0 {
+ local ceil=1
+ }
+ if "`eqwithci'"=="" {
+ local pciset`t' `pciset`t'' scatteri `=-`ceil'/5*`t'' `r(mean)' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)||
+ }
+ local mean=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ local moins=r(mean)
+ if `moins'<`minimini' {
+ *di "local minimini=floor(`moins')"
+ local minimini=floor(`moins')
+ }
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ local plus=r(mean)
+ if `plus'>`maximaxi' {
+ *di "local maximaxi=ceil(`plus')"
+ local maximaxi=ceil(`plus')
+ }
+
+ if "`eqwithci'"!="" {
+ local y=-`ceil'/5*((2.5*`t'-2)+2*(`s'/`scoremaxset`t''))
+ *local pciset`t' `pciset`t'' scatteri `y' `mean' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ local pciset`t' `pciset`t'' scatteri `y' `mean' , mlabsize(tiny) mcolor(black) mlabcolor(black)|| scatteri `y' `moins' (9) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , msize(0) mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ }
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ di as text
+ di as text "{hline 78}"
+ di as text "EQUATING `eqset`t'name' TO `eqset`=3-`t''name'"
+ di as text "{hline 78}"
+ di "`eqset`t'name' : `eqset`t''"
+ di "`eqset`=3-`t''name' : `eqset`=3-`t'''"
+ local eqset`t'namea=abbrev("`eqset`t'name'",18)
+ local eqset`=3-`t''namea=abbrev("`eqset`=3-`t''name'",12)
+ di "{hline 78}"
+ di "Score" _col(20) "<----- Latent trait ----->" _col(52) "<- Score `eqset`=3-`t''namea'" _col(77) "->"
+ di "`eqset`t'namea'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+
+ di %4.0f `=(`matscore`t''[`=`s'+1',1]+`eqaddset`t'')*`eqmultset`t''' _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' _col(66) "[" %5.2f `min' ";" %5.2f `max' "]"
+ }
+ di "{hline 78}"
+ if "`eqgraph'"!="" {
+ *set trace on
+ if `eqmultset`=3-`t'''>0 {
+ local xlabel "`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''(`=ceil((`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''"
+ }
+ else {
+ local xlabel "`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''(`=ceil((-`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''"
+ }
+ if `eqmultset`t''>0 {
+ local ylabel "`=`eqaddset`t''*`eqmultset`t'''(`=ceil((`scoremaxset`t''*`eqmultset`t'')/20)')`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''"
+ }
+ else {
+ local ylabel "`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''(`=ceil((-`scoremaxset`t''*`eqmultset`t'')/20)')`=`eqaddset`t''*`eqmultset`t'''"
+ }
+ *set trace off
+ *di "xlabel : `xlabel'"
+ *di "subtitle=`subtitle'"
+ twoway (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''!=.,lcolor(black) lpattern(solid) lwidth(thick)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''m!=.,lcolor(black) lpattern(dash) lwidth(thin)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''p!=.,lcolor(black) lpattern(dash) lwidth(thin)), title("Equating score of `eqset`=3-`t''name' to `eqset`t'name' ") ytitle("Score `eqset`t'name'") xtitle("Score `eqset`=3-`t''name'") ylabel(`ylabel') xlabel(`xlabel') name(eq`t'to`=3-`t'') legend(order(1 2) label(1 "Estimated") label(2 "95%IC") position(6)) subtitle("`dimname'")
+ }
+ qui drop adjscore`t' adjscore`=3-`t''
+ }
+
+ if "`eqgraph'"!="" {
+ qui use "`equating'",clear
+ qui su u
+ local flooru=floor(`r(min)')
+ local ceilu=ceil(`r(max)')
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+ if `ceil'==0 {
+ local ceil=1
+ }
+
+ local title "Equating"
+ if "`eqset1name'"!=""&"`eqset2name'"!=""{
+ local title "Equating between `eqset1name' and `eqset2name'"
+ }
+ if "`eqwithci'"=="" {
+ local ylabel1=-`ceil'/5
+ local ylabel2=-2*`ceil'/5
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ else {
+ local ylabel1=-0.5*`ceil'/5
+ local ylabel2=-3*`ceil'/5
+ local flooru=min(`flooru',`minimini')
+ local ceilu=max(`ceilu',`maximaxi')
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(1)`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle( Frequencies) ylabel(`=-`ceil'/5*2' `eqset1name' `=-`ceil'/5' `eqset2name' 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title(Equating) xsize(12) ysize(9) xtitle(Latent trait) "
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(`gapu')`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle(" Frequencies") /*ylabel(`ylbl', grid angle(0) axis(1))*/ ylabel(`ylabel1' "`eqset1name'" `ylabel2' "`eqset2name'" 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title("`title'") subtitle("`dimname'") xsize(12) ysize(9) xtitle("Latent trait")
+ }
+ qui use `fileeq',clear
+ *set trace on
+ tempname scoreset1 scoreset2
+ forvalues t=1/2 {
+ qui genscore `eqset`t'' if `touse',score(`scoreset`t'')
+ qui su `scoreset`t'' if `touse'
+ local maxscoreset=r(max)
+ *qui matrix list `matscore`t''
+ if "`eqgenscore'"!="" {
+ local eqgenscore `=regexreplaceall("`eqgenscore'"," ","_")'
+ *di "eqgenscore : `eqgenscore'"
+ foreach k in mean min max random {
+ capture confirm variable `eqgenscore'_`k'_`eqset`=3-`t''name'
+ if _rc==0&"`replace'"!="" {
+ qui replace `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ else if _rc==0&"`replace'"!="" {
+ di as error "The variable `eqgenscore'_`k'_`eqset`=3-`t''name' already exists"
+ error 198
+ }
+ else {
+ qui gen `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ }
+ *tab `scoreset`t''
+ forvalues s=0/`maxscoreset' {
+ *di "qui replace `eqgenscore'_`eqset`=3-`t''name'=`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' if `scoreset`t''==`s'"
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ qui replace `eqgenscore'_mean_`eqset`=3-`t''name'=round(`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_min_`eqset`=3-`t''name'=round(`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_max_`eqset`=3-`t''name'=round(`max',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_random_`eqset`=3-`t''name'=round(uniform()*(`max'-`min')+`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ }
+ }
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ }
+
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+*set trace on
+if "`visit'"!="" {
+ tempfile sauv
+ *set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_best
+ *capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=`corrlatent' if `touse'
+/* qui gen `genlt'_corr2=. if `touse'
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr2=`estlt`s'' if `score'==`s'&`touse'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr2=`clt`g'' if `group'==`g'&`genlt'_corr==.&`touse'
+ }
+*/
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=. if `touse'
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'&`touse'
+ }
+ }
+ *su
+ qui egen `genlt'_best=rowmean(`tmpitem'_*) if `touse'
+ *qui egen `genlt'_opt_se=rowsd(`tmpitem'_*) if `touse'
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*) if `touse'
+ *qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss') if `touse'
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin, footer(fall_report)
+ putdocx table hdr = (1, 3), border(all, nil) tofooter(fall_report)
+ if "`rsm'"=="" {
+ putdocx table hdr(1, 1) = ("Partial Credit Model")
+ }
+ else {
+ putdocx table hdr(1, 1) = ("Rating Scale Model")
+ }
+ putdocx table hdr(1, 2) = ("`dimname'"), halign(center)
+ putdocx table hdr(1, 3) = ("Page "), pagenumber
+ putdocx table hdr(1, 3) = ("/"), totalpages append
+ putdocx table hdr(1, 3), halign(right)
+ putdocx paragraph ,style(Title)
+ if "`dimname'" =="" {
+ local dimname2 "Rasch analysis"
+ }
+ else {
+ local dimname2 "Rasch analysis of the `dimname' dimension"
+ }
+ putdocx text ("`dimname2'") ,
+ putdocx paragraph ,style(Subtitle)
+ putdocx text ("General informations") ,
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("Names of the dimension: `dimname'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation of the parameters") ,
+ local paramname
+ forvalues j=1/`nbitems' {
+ forvalues k=1/`modamax' {
+ if `k'<=`modamax`j'' {
+ local paramname `paramname' "``j''_`k'"
+ }
+ }
+ }
+ *di "matrix colnames `diff'=`paramname'"
+ matrix rownames `diff'=`paramname'
+ putdocx table table1 = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1) halign(center)
+ putdocx table table1(.,1), halign(left)
+ putdocx table table1(.,2/7), halign(right)
+ putdocx table table1(1,.), halign(right) border(top) border(bottom)
+
+
+ qui putdocx table table2 = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table2(.,1), halign(left)
+ putdocx table table2(.,2/7), halign(right)
+ putdocx table table2(1,.), halign(right) border(top) border(bottom)
+
+
+
+
+ putdocx paragraph,style(Subtitle)
+ putdocx text ("Fit indexes for items") , /*bold underline font(,14) smallcaps*/
+ qui putdocx table table3 = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table3(.,1), halign(left)
+ putdocx table table3(.,2/5), halign(right)
+ putdocx table table3(1,.), halign(right) border(top) border(bottom)
+
+
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation per group/score")
+ *putdocx text ("Estimation per group/score") , bold underline font(,14) smallcaps
+ *set trace on
+ putdocx table tbl = (`=`nbrowmat'+1',7), border(all,nil) width(7) halign(center) note(EAP: Expected A Posteriori ; BE: Best Estimates) headerrow(1)
+ putdocx table tbl(1,.), halign(right) border(top) border(bottom)
+ putdocx table tbl(1,1) = ("Group"), halign(right)
+ putdocx table tbl(1,2) = ("score"), halign(right)
+ putdocx table tbl(1,3) = ("Frequency"), halign(right)
+ putdocx table tbl(1,4) = ("EAP Mean"), halign(right)
+ putdocx table tbl(1,5) = ("EAP s.e."), halign(right)
+ putdocx table tbl(1,6) = ("Exp score"), halign(right)
+ putdocx table tbl(1,7) = ("BE Mean"), halign(right)
+ local fin=1
+ forvalues row=1/`nbrowmat' {
+ local row2=`row'+1
+ local g: di %9.0f `matgroupscorelt'[`row',1]
+ local gh=`matgroupscorelt'[`row',1]
+ if `fin'==1 {
+ putdocx table tbl(`row2',1) = ("`g'"), halign(right)
+ }
+ if `matgroupscorelt'[`row',2]!=.|`matgroupscorelt'[`row',7]==. {
+ local s: di %9.0f `matgroupscorelt'[`row',2]
+ local fin=0
+ }
+ else {
+ local s "`scoremin`gh''/`scoremax`gh''"
+ local fin=1
+ *local fin "border(top) border(bottom)"
+ *di "c'est la fin"
+ putdocx table tbl(`row2',.), border(bottom) border(top, dashed)
+ putdocx table tbl(`row2',1), border(top, nil)
+ }
+ local eff: di %9.0f `matgroupscorelt'[`row',3]
+ local lt: di %9.3f `matgroupscorelt'[`row',4]
+ local se: di %9.3f `matgroupscorelt'[`row',5]
+ local exp: di %9.2f `matgroupscorelt'[`row',6]
+ local clt: di %9.3f `matgroupscorelt'[`row',7]
+ *putdocx table tbl(`row',.), addrows(7)
+ putdocx table tbl(`row2',2) = ("`s'"), halign(right)
+ putdocx table tbl(`row2',3) = ("`eff'"), halign(right)
+ putdocx table tbl(`row2',4) = ("`lt'"), halign(right)
+ putdocx table tbl(`row2',5) = ("`se'"), halign(right)
+ putdocx table tbl(`row2',6) = ("`exp'"), halign(right)
+ putdocx table tbl(`row2',7) = ("`clt'"), halign(right)
+
+ }
+
+/*
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+
+
+local row 1
+local vari 1
+foreach x in gear_ratio turn foreign _cons {
+putdocx table tbl5(`row',.), addrows(2)
+local b: display %9.3f rtable[`vari',1]
+local se: display %9.3f rtable[`vari',2]
+local ++vari
+local ++row
+putdocx table tbl5(`row',1) = ("`x'"), halign(right)
+putdocx table tbl5(`row',2) = ("`b'"), halign(right)
+local ++row
+local se = strtrim("`se'")
+putdocx table tbl5(`row',2) = ("(`se')"), halign(right)
+}*/
+
+ *qui putdocx table tablename = matrix(`matgroupscorelt') , nformat(%9.3f) /*rownames*/ colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("General Graphs")
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Graphs per item")
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph, style(Heading1)
+ putdocx text ("Graphs for ``i''")
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+*set trace on
+
+matrix colnames `diff'="Estimate" "Std err" "z" "p" "lb" "ul"
+matrix colnames `covariates'=Estimate s.e. z p lb ul
+matrix rownames `diff'=`diffname'
+*matrix list `diff'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix matgroupscorelt=`matgroupscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm.ado b/Modules/ado/personal/p/pcm.ado
new file mode 100644
index 0000000..ec43d62
--- /dev/null
+++ b/Modules/ado/personal/p/pcm.ado
@@ -0,0 +1,2299 @@
+*! Version 5.4 28July2023
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+* Version 5.1: July 8th, 2023 [Jean-Benoit Hardouin] : Correction of the MAP graph (histogram) and residuals graphs
+* Version 5.2: July 16th, 2023 [Jean-Benoit Hardouin] : Add of new graphs for Equating
+* Version 5.3: July 21th, 2023 [Jean-Benoit Hardouin] : Improvements for the docx option
+* Version 5.4: July 28th, 2023 [Jean-Benoit Hardouin] : Improvements for graphs et corrections of bugs
+* Version 5.5: October 25th, 2023 [Jean-Benoit Hardouin] : first attemp with DIF
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022, 2023 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [if] [in] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems noCORRected filesave dirsave(string) docx(string) extension(string) alpha(real 0.01) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) eqset1name(string) eqset2name(string) EQGraph eqaddset1(real 0) eqaddset2(real 0) eqmultset1(real 1) eqmultset2(real 1) eqwithci eqgenscore(string) DIMname(string) minsize(int 30) vardif(varname) itemsdif(varlist) noRESiduals scorewithdif(varname) vardif(varname) ]
+
+version 14
+preserve
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+if "`corrected'"!="" {
+ local xtitle "Latent trait"
+}
+else {
+ local xtitle "Corrected latent trait"
+}
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count if `touse'
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local name``i'': variable label ``i''
+ if "`name``i'''"=="" {
+ local name``i'' ``i''
+ }
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ *di "i: `i' ``i''"
+ qui su ``i'' if `touse'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count if `touse'
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist' if `touse'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist' if `touse', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' if `touse' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ *di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ *di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' if `touse',iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'* if `touse',latent se(`selatent'*)
+*di "latent=`latent' "
+*su
+*set trace on
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'1 if `touse'
+ qui gen `genlt'_se=`selatent'1 if `touse'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t' if `touse'
+ qui gen `genlt'`t'_se=`selatent'`t' if `touse'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t' if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit' if `touse',score(`score'`t')
+ qui gengroup `latent'`t' if `touse',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'1+invnorm(uniform())*`selatent'1 if `touse'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit' if `touse',score(`score')
+ qui gengroup `latent'1 if `touse',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'&`touse'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit' if `touse'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+10',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'1 if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+7']=r(min)
+ matrix `groups'[`g',`=`nbitems'+8']=r(max)
+ qui count if `group'`multivisit'==`g'&`touse'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.&`touse'
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*) if `touse'
+qui count if `miss'==0&`touse'
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of individuals with a complete answer pattern:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+*di "matrix rownames `diff'=`rn'"
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(59) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("`name``i'''",20) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %6.2f `diff'[`t',3] _col(62) %5.3f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %6.2f `diff'[`t',3] _col(62) %5.3f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+ local n: word count `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `continuous'
+ local v2 : variable label `v'
+ if "`v2'"=="" {
+ local v2 `v'
+ }
+ di as text _col(1) %5.2f abbrev("`v2'",20) as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count `categorical'
+ *di "local n: word count of `categorical' "
+ *di "n=`n'"
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local v2 : variable label `v'
+ if "`v2'"=="" {
+ local v2 `v'
+ }
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v2'",20) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %6.2f `covariates'[`t',3] _col(62) %5.3f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'1 if `touse'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent'1)^2 if `touse'
+ qui su `se2latent' if `touse'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED VALUES OF THE LT ESTIMATORS (values of lt that explained the best the score)
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=2*sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ *set trace on
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues l=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`l''
+ }
+ qui gen ecart=.
+ local listlt
+ forvalues l=0/`scoremax' {
+ if `l'==0 {
+ local j=0.25
+ }
+ else if `l'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`l'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`l'=`r(mean)'
+ local listlt `listlt' `estlt`l''
+ *qui su TInf if round(ecart, 0.01)==round(`tmp',0.01)
+ *local setlt`l'=sqrt(1/`r(mean)')
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+*set trace on
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+/*Quelques explications
+latent : estimation EAP du trait latent
+latent2 : estimation Plausible Value Ă partir de l'estimation EAP
+corrlatent : estimation corrigée cherchant la meilleur valeur du trait latent qui explique le score, interpolation à partir de l'EAP pour les individus avec des données manquantes
+*/
+
+
+if "`visit'"==""{
+ tempvar corrlatent corrlatenttmp
+ qui gen `corrlatenttmp'=.
+ forvalues s=0/`scoremax' {
+ qui replace `corrlatenttmp'=`estlt`s'' if `score'==`s'
+ }
+ qui ipolate `corrlatenttmp' `latent'1 , generate(`corrlatent') epolate
+ *list `corrlatenttmp' `latent2' `corrlatent'
+ qui replace `corrlatent'=`corrlatenttmp' if `corrlatenttmp'!=.
+ qui replace `corrlatent'=`latent' if `corrlatenttmp'==.
+ *su `corrlatenttmp' `latent2' `corrlatent'
+ *twoway (scatter `corrlatent' `score') (scatter `latent2' `score')
+ forvalues g=1/`nbgroups' {
+ *di "group=`g'"
+ qui su `corrlatent' if `group'==`g'&`touse'
+ *di "qui matrix `groups'[`g',`=`nbitems'+9']=`r(min)'"
+ *di "qui matrix `groups'[`g',`=`nbitems'+10']=`r(max)'"
+ if r(N)!=0 {
+ qui matrix `groups'[`g',`=`nbitems'+9']=`r(min)'
+ qui matrix `groups'[`g',`=`nbitems'+10']=`r(max)'
+ }
+ }
+ tempname fit
+ qui matrix `fit'=J(`nbitems',6,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT" "corrOUTFIT" "corrINFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0 if `touse'
+ qui gen `TInf'=0 if `touse'
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+ tempvar corrcum``i'' corrc0_``i'' corrInf``i'' corry``i'' corrz``i'' corrz2``i'' corri``i''
+
+ local d=1
+ local corrd=1
+ local d_old=1
+ qui gen `corrcum``i'''=0 if `touse'
+ qui gen `cum``i'''=0 if `touse'
+ qui gen `cum_old``i'''=0 if `touse'
+ forvalues k=1/`mm' {
+ local corrd `corrd'+exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'1-`diffmat2'[`i',`k'])
+ }
+ qui gen `corrc0_``i'''=1/(`corrd') if `touse'
+ qui gen `c0_``i'''=1/(`d') if `touse'
+ qui gen `c_old0_``i'''=1/(`d_old') if `touse'
+ forvalues k=1/`mm' {
+ tempvar corrc`k'_``i'' c`k'_``i'' c_old`k'_``i''
+ qui gen `corrc`k'_``i'''=exp(`k'*`corrlatent'-`diffmat2'[`i',`k'])/(`corrd') if `touse'
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'1-`diffmat2'[`i',`k'])/(`d') if `touse'
+ qui replace `corrcum``i'''=`corrcum``i'''+`corrc`k'_``i'''*`k' if `touse'
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k' if `touse'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k' if `touse'
+ }
+ qui gen `corrInf``i'''=0 if `touse'
+ qui gen `Inf``i'''=0 if `touse'
+ qui gen `Inf_old``i'''=0 if `touse'
+ qui gen `C``i'''=0 if `touse'
+ forvalues k=0/`mm' {
+ qui replace `corrInf``i'''=`corrInf``i'''+(`k'-`corrcum``i''')^2*`corrc`k'_``i''' if `touse'
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i''' if `touse'
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i''' if `touse'
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i''' if `touse'
+ }
+ qui count if ``i''!=.&`touse'
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2) if `touse'
+ qui su `C2``i''' if `touse'
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2 if `touse'
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i''' if `touse'
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i''' if `touse'
+ qui replace `TInf'=`TInf'+`Inf``i''' if `touse'
+ qui gen `corry``i'''=``i''-`corrcum``i''' if `touse'
+ qui gen `y``i'''=``i''-`cum``i''' if `touse'
+ qui gen `y_old``i'''=``i''-`cum_old``i''' if `touse'
+ qui gen `y2``i'''=(`y``i''')^2 if `touse'
+ qui gen `y2_old``i'''=(`y_old``i''')^2 if `touse'
+ qui gen `corrz``i'''=(`corry``i'''/sqrt(`corrInf``i''')) if `touse'
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i''')) if `touse'
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+
+ qui su `y2``i''' if `group'==`g'&`touse'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'&`touse'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'&`touse'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'&`touse'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'&`touse'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'&`touse'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'&`touse'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `corrz``i''' "Corrected standardized residuals associated to ``i''"
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent'1 "Latent trait"
+ label variable `corrlatent' "Corrected latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ *set trace on
+ *set tracedepth 1
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ local thr=abs(invnorm(`alpha'/2))
+ tempvar id``i''
+ local hline
+ forvalues l=1/`modamax`i'' {
+ local hline `hline' `=`diffmat'[`i',`l']'
+ }
+ if "`residuals'"=="" {
+ if "`corrected'"!="" {
+ qui gen `id``i'''=_n if abs(`z``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `z``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+
+ qui graph twoway scatter `z``i''' `latent' if `touse', xline(`hline',lwidth(vthin) lcolor(gray)) colordiscrete colorvar(``i'') colorlist(blue green orange purple gray red cyan ) ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])', lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals") subtitle(`name``i''') `fs'
+ }
+ else {
+ *set trace on
+ qui gen `id``i'''=_n if abs(`corrz``i''')>`thr'*sqrt(`covariates'[1,1])&`touse'
+ qui tostring `id``i''',replace
+ qui replace `id``i'''="" if `id``i'''=="."&`touse'
+ qui su `corrz``i''' if `touse'
+ local min=r(min)
+ local max=r(max)
+ local min=floor(min(`min',`=-`thr'*sqrt(`covariates'[1,1])'))
+ local max=ceil(max(`max',`=`thr'*sqrt(`covariates'[1,1])'))
+ qui graph twoway scatter `corrz``i''' `corrlatent' if `touse',xline(`hline',lwidth(vthin) lcolor(gray)) colordiscrete colorvar(``i'') colorlist(blue green orange purple gray red cyan ) ylabel(`min'(1)`max') yline(`=-`thr'*sqrt(`covariates'[1,1])' `=`thr'*sqrt(`covariates'[1,1])', lcolor(black)) mlabel(`id``i''') name(residuals``i'',replace) title("Standardized residuals") subtitle(`name``i''') `fs'
+ }
+ }
+ *set trace off
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2 if `touse'
+ qui su `z2``i''' if `touse'
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.&`touse'
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i''' if `touse'
+ qui su `i``i''' if ``i''!=.&`touse'
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+
+ /*corrected*/
+ qui gen `corrz2``i'''=(`corrz``i''')^2 if `touse'
+ qui su `corrz2``i''' if `touse'
+ local corrOUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',5]=`corrOUTFIT``i'''
+ *local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ *qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `corrInf``i''' if ``i''!=.&`touse'
+ local corrsumw``i''=r(sum)
+ qui gen `corri``i'''=`corrInf``i'''*`corrz2``i''' if `touse'
+ qui su `corri``i''' if ``i''!=.&`touse'
+ local corrINFIT``i'' = `=`r(sum)'/`corrsumw``i''''
+ qui matrix `fit'[`i',6]=`corrINFIT``i'''
+ *local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ *qui matrix `fit'[`i',4]=`INFITs``i'''
+
+
+ if "`postpce'"=="" {
+ di abbrev("`name``i'''",20) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i''' /*_col(94) %5.3f `corrOUTFIT``i''' _col(109) %5.3f `corrINFIT``i'''*/
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Bond and Fox (2007)"
+ di as text "**: As suggested by Wright (Smith, 1998)"
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf' if `touse'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Iteration `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1') if `touse'
+ `qui' pcm `varlist' [iweight=`sinf'] if `touse',diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1') if `touse'
+ qui su `ecart_`it'' if `touse'
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*ANCIENNE PLACE DES CORRECTED VALUES*/
+
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt matgroupscorelt
+ *di "qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)"
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ qui matrix `matgroupscorelt'=J(`=(`nbitems'*`modamax'+1+2*`nbgroups')*4',7,.)
+ qui matrix colnames `matgroupscorelt'="Group" "Score" "Frequency" "Estimation of latent trait" "s.e. of latent trait" "Expected score" "Corrected latent trait"
+
+ local row=1
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'&`touse'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.&`touse'
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'&`touse'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'&`touse'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local eff=r(N)
+ local effscore`s'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local mean=r(mean)
+ *di "local ltscore`s'=`=ceil(`r(mean)'*100)/100'"
+ local ltscore`s'=`=ceil(`r(mean)'*100)/100'
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'&`touse'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s'' `setlt`s''
+ }
+ *set trace on
+ *matrix list `matscorelt'
+ qui matrix `matscorelt'[`=`s'+1',1]=`eff'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ *set trace off
+ }
+
+ }
+ *set trace on
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local eff=r(N)
+ local eff_md_`g'=r(N)
+ if `eff'!=0 {
+ qui su `latent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local mean=r(mean)
+ local lt_md_`g'=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent'1 if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.&`touse'
+ local exp=r(mean)
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) /*%5.2f `exp'*/
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]=`s'
+ qui matrix `matgroupscorelt'[`row',3]=`eff'
+ qui matrix `matgroupscorelt'[`row',4]=`mean'
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ qui matrix `matgroupscorelt'[`row',6]=`exp'
+ *qui matrix `matgroupscorelt'[`row',7]=`estlt`s''
+ local ++row
+ }
+ *set trace off
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`effcompleted`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ if "`scoremin`g''"=="" {
+ local scoremin`g' "."
+ }
+ if "`scoremax`g''"=="" {
+ local scoremax`g' "."
+ }
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+ qui matrix `matgroupscorelt'=`matgroupscorelt'[1..`nbrowmat',1..7]
+ *matrix list `matscorelt'
+}
+
+*set trace on
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+ local pas=1000*round(`=sqrt(`covariates'[1,1])',0.001)
+ local pas=round(`pas')
+ qui set obs `pas'
+ qui gen u=round((_n-`pas'/2)/(`pas'/10)*`=sqrt(`covariates'[1,1])',0.01)
+ *list u
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local xmin=`groups'[`g',`=`nbitems'+7']
+ local xmax=`groups'[`g',`=`nbitems'+8']
+ local xcmin=`groups'[`g',`=`nbitems'+9']
+ local xcmax=`groups'[`g',`=`nbitems'+10']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=20
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off) || pci `y' `xmin' `y' `xmax' ,lcolor(black)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off) || pci `y' `xcmin' `y' `xcmax' ,lcolor(black)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(X=0)"
+ local xline
+ local yline
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(X=`k')"
+ local xline `xline' `=`diffmat'[`i',`k']'
+ local yline `yline' `=`k'-0.5'
+
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ label variable Inf``i'' "`name``i'''"
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC)) subtitle(`name``i''') ytitle("Probability") xtitle("`xtitle'") `fsc' xline(`xline',lwidth(vthin) lcolor(gray))
+ if "`corrected'"!="" {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC)") subtitle(`name``i''') ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi' xline(`xline',lwidth(vthin) lcolor(gray)) ylabel(0(.5)`modamax`i'')
+ }
+ else {
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC)") subtitle(`name``i''') ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi' xline(`xline',lwidth(vthin) lcolor(gray)) ylabel(0(.5)`modamax`i'')
+ }
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fstii saving("`dirsave'//TICi",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+*qui save "C:\temp\info\info",replace
+ label variable TInf "Information curve"
+
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("`xtitle'") `fst' subtitle(`dimname') ylabel(0(1)`scoremax') xline(`listlt',lwidth(vthin) lcolor(gray))
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("`xtitle'") `fsi' subtitle(`dimname')
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("`xtitle'") `fsti' subtitle(`dimname')
+ qui graph twoway (line Inf* u, lwidth(thin)) (line TInf u, lwidth(thick)), name(TIC,replace) title("Test/Item Information Curve") ytitle("Information") xtitle("`xtitle'") `fstii' subtitle(`dimname')
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ *matrix list `groups'
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local xmin=`groups'[`g',`=`nbitems'+7']
+ local xmax=`groups'[`g',`=`nbitems'+8']
+ local xcmin=`groups'[`g',`=`nbitems'+9']
+ local xcmax=`groups'[`g',`=`nbitems'+10']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=20
+ local s tiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)|| pci `y' `xmin' `y' `xmax' ,lcolor(black)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off) || pci `y' `xcmin' `y' `xcmax' ,lcolor(black)
+ }
+ *set trace on
+ if "`graphs'"!="" {
+ if "`corrected'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo' subtitle(`dimname') xline(`listlt',lwidth(vthin) lcolor(gray))
+ }
+ else {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo' subtitle(`dimname') xline(`listlt',lwidth(vthin) lcolor(gray))
+ }
+ }
+ *set trace off
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!=""|"eqset1"!="" {
+ gen eff=0
+ gen eff_md=0
+ local effmax=0
+ *gen uround=round(u,0.01)
+ *list uround
+ /*le bloc suivant Ă©tait pour avoir des batons par groupe*/
+ /*forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.01)
+ *di "replace eff=`eff' if round(u,0.01)==`lat'"
+ qui replace eff=`eff' if round(u,0.01)==`lat'
+ }*/
+ /*le bloc suivant est pour avoir des batons par score*/
+ qui gen uceil=ceil(u*100)/100
+ forvalues s=0/`scoremax' {
+ if `effscore`s''>`effmax' {
+ local effmax=`effscore`s''
+ }
+ *di "`s' qui replace eff=`effscore`s'' if ceil(u*100)/100==`=round(`ltscore`s'',0.01)'"
+ qui replace eff=`effscore`s'' if round(u,0.01)==round(`ltscore`s'',0.01)
+ }
+ forvalues g=1/`nbgroups' {
+ *di "if `eff_md_`g''>`effmax' { (`lt_md_`g'')"
+ if `eff_md_`g''>`effmax' {
+ local effmax=`eff_md_`g''
+ }
+ qui replace eff_md=`eff_md_`g'' if round(u,0.01)==round(`lt_md_`g'',0.01)
+ }
+
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Complete"
+ label variable eff_md "Incomplete"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0|eff_md!=0
+ *set trace on
+ *set tracedepth 1
+ *if eff!=0|eff_md!=0 {
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ *}
+ *else {
+ * local floor=-10
+ * local ceil=10
+ *}
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ *local legend `"1 2 `=(`modamax'+1)*`nbitems'+1' `=(`modamax'+1)*`nbitems'+2' 3 "1" "'
+ local legend `"5 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'+3' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local nomcourt``i''=abbrev("`name``i'''",20)
+ local ylbl `ylbl' `=-`i'*`unit'' "`nomcourt``i'''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su eff_md
+ local maxe_md=ceil(`=(floor(`r(max)'/10)+1)*10')
+ local maxe=max(`maxe',`maxe_md')
+ qui su TInf
+ local maxi=1.2*ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ *su
+*list eff u if eff!=0
+*browse
+ if "`eqset1'"==""&"`graphs'"!="" {
+ *list eff u uceil if eff!=0&eff!=.
+ *save tmp, replace
+ *di "`legend'"
+ *di "holes(3/`nbcolslegende' `=`nbcolslegende'+3'/`=`nbcolslegende'*2')"
+ local nbcolslegende=max(2,`modamax')
+ if `modamax'==1 {
+ local holes "holes(2)"
+ }
+ tempvar line1 line2
+ qui gen `line1'=.
+ qui gen `line2'=.
+ label variable `line2' "Density"
+ label variable `line1' "Information"
+ qui graph twoway (line `line1' u ,lwidth(medthick) lcolo(red)) (line `line2' u ,lwidth(medthick) lcolo(green)) (line density u,yaxis(3) lwidth(medthick) lcolo(green) ) (bar eff u, barwidth(.1) yaxis(1) xlabel(`floor'(1)`ceil') color(erose) ) (bar eff_md u, barwidth(.05) yaxis(1) xlabel(`floor'(1)`ceil') color(stred) ) (line TInf u,yaxis(2) lwidth(medthick) lcolo(red) ) `scatterj' , xline(0, lcolor(black)) legend(on position(3) /*symysize(*.6) symxsize(*.6) textwidth(*.6)*/ /*cols(`nbcolslegende')*/ cols(1) `holes' order(`"- "Functions" 2 1 - "" - "Patterns" 3 4 - "" - "Thresholds" `legend' "') /*subtitle(Threshold parameters,size(*.7)) */size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(medium) lpattern(solid) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("* : dysfunctioning items") xtitle("`xtitle'") `fsm' subtitle(`dimname')
+ }
+ else if "`eqset1'"!="" {
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+
+ qui tempfile equating
+ qui save `equating', replace
+ }
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di
+di "Best estimates by answer category"
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di abbrev("`name``i'''",20) _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+if "`eqset1'"!="" {
+ if "`eqgenscore'"!="" {
+ local tmp1 `=ustrlen("`eqgenscore'`eqset1name'")'
+ local tmp2 `=ustrlen("`eqgenscore'`eqset2name'")'
+ local mlength=max(`tmp1',`tmp2')
+ if `mlength'>27 {
+ di as error "The number of characters containing in the strings eqgenscore+eqset1name or eqgenscore+eqset2name must be lesser than 27"
+ di as error "eqgenscore+eqset1name : `tmp1' characters"
+ di as error "eqgenscore+eqset2name : `tmp2' characters"
+ error 130
+ *exit
+ }
+ }
+ if "`eqset1name'"=="" {
+ local eqset1name="Set_1"
+ }
+ else if `c(version)'>17 {
+ local eqset1name `=regexreplaceall("`eqset1name'"," ","_",.)'
+ }
+ if "`eqset2name'"=="" {
+ local eqset2name="Set_2"
+ }
+ else if `c(version)'>17 {
+ local eqset2name `=regexreplaceall("`eqset2name'"," ","_",.)'
+ }
+ *di "set1:`eqset1name' set2:`eqset2name'"
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ }
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ local pciset1
+ local pciset2
+ *set trace on
+ local minimini=0
+ local maximaxi=0
+ forvalues t=1/2 {
+ qui gen adjscore`t'=(score`t'+`eqaddset`t'')*`eqmultset`t''
+ qui gen adjscore`=3-`t''=(score`=3-`t''+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ *set trace on
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ if `ceil'==0 {
+ local ceil=1
+ }
+ if "`eqwithci'"=="" {
+ local pciset`t' `pciset`t'' scatteri `=-`ceil'/5*`t'' `r(mean)' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)||
+ }
+ local mean=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ local moins=r(mean)
+ if `moins'<`minimini' {
+ *di "local minimini=floor(`moins')"
+ local minimini=floor(`moins')
+ }
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ local plus=r(mean)
+ if `plus'>`maximaxi' {
+ *di "local maximaxi=ceil(`plus')"
+ local maximaxi=ceil(`plus')
+ }
+
+ if "`eqwithci'"!="" {
+ local y=-`ceil'/5*((2.5*`t'-2)+2*(`s'/`scoremaxset`t''))
+ *local pciset`t' `pciset`t'' scatteri `y' `mean' (12) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ local pciset`t' `pciset`t'' scatteri `y' `mean' , mlabsize(tiny) mcolor(black) mlabcolor(black)|| scatteri `y' `moins' (9) "`=round((`s'+`eqaddset`t'')*`eqmultset`t'',1)'" , msize(0) mlabsize(tiny) mcolor(black) mlabcolor(black)|| pci `y' `moins' `y' `plus',pstyle(p1) color(black)||
+ }
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ di as text
+ di as text "{hline 78}"
+ di as text "EQUATING `eqset`t'name' TO `eqset`=3-`t''name'"
+ di as text "{hline 78}"
+ di "`eqset`t'name' : `eqset`t''"
+ di "`eqset`=3-`t''name' : `eqset`=3-`t'''"
+ local eqset`t'namea=abbrev("`eqset`t'name'",18)
+ local eqset`=3-`t''namea=abbrev("`eqset`=3-`t''name'",12)
+ di "{hline 78}"
+ di "Score" _col(20) "<----- Latent trait ----->" _col(52) "<- Score `eqset`=3-`t''namea'" _col(77) "->"
+ di "`eqset`t'namea'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+
+ di %4.0f `=(`matscore`t''[`=`s'+1',1]+`eqaddset`t'')*`eqmultset`t''' _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' _col(66) "[" %5.2f `min' ";" %5.2f `max' "]"
+ }
+ di "{hline 78}"
+ if "`eqgraph'"!="" {
+ *set trace on
+ if `eqmultset`=3-`t'''>0 {
+ local xlabel "`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''(`=ceil((`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''"
+ }
+ else {
+ local xlabel "`=(`scoremaxset`=3-`t'''+`eqaddset`=3-`t''')*`eqmultset`=3-`t''''(`=ceil((-`scoremaxset`=3-`t'''*`eqmultset`=3-`t''')/20)')`=`eqaddset`=3-`t'''*`eqmultset`=3-`t''''"
+ }
+ if `eqmultset`t''>0 {
+ local ylabel "`=`eqaddset`t''*`eqmultset`t'''(`=ceil((`scoremaxset`t''*`eqmultset`t'')/20)')`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''"
+ }
+ else {
+ local ylabel "`=(`scoremaxset`t''+`eqaddset`t'')*`eqmultset`t'''(`=ceil((-`scoremaxset`t''*`eqmultset`t'')/20)')`=`eqaddset`t''*`eqmultset`t'''"
+ }
+ *set trace off
+ *di "xlabel : `xlabel'"
+ *di "subtitle=`subtitle'"
+ twoway (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''!=.,lcolor(black) lpattern(solid) lwidth(thick)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''m!=.,lcolor(black) lpattern(dash) lwidth(thin)) (line adjscore`t' adjscore`=3-`t'' if scoreset`=3-`t''p!=.,lcolor(black) lpattern(dash) lwidth(thin)), title("Equating score of `eqset`=3-`t''name' to `eqset`t'name' ") ytitle("Score `eqset`t'name'") xtitle("Score `eqset`=3-`t''name'") ylabel(`ylabel') xlabel(`xlabel') name(eq`t'to`=3-`t'') legend(order(1 2) label(1 "Estimated") label(2 "95%IC") position(6)) subtitle("`dimname'")
+ }
+ qui drop adjscore`t' adjscore`=3-`t''
+ }
+
+ if "`eqgraph'"!="" {
+ qui use "`equating'",clear
+ qui su u
+ local flooru=floor(`r(min)')
+ local ceilu=ceil(`r(max)')
+ qui su eff
+ local ceil=ceil(ceil(`r(max)'/10)*10)
+ if `ceil'==0 {
+ local ceil=1
+ }
+
+ local title "Equating"
+ if "`eqset1name'"!=""&"`eqset2name'"!=""{
+ local title "Equating between `eqset1name' and `eqset2name'"
+ }
+ if "`eqwithci'"=="" {
+ local ylabel1=-`ceil'/5
+ local ylabel2=-2*`ceil'/5
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ else {
+ local ylabel1=-0.5*`ceil'/5
+ local ylabel2=-3*`ceil'/5
+ local flooru=min(`flooru',`minimini')
+ local ceilu=max(`ceilu',`maximaxi')
+ local gapu=ceil((`ceilu'-`flooru')/15)
+ }
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(1)`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle( Frequencies) ylabel(`=-`ceil'/5*2' `eqset1name' `=-`ceil'/5' `eqset2name' 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title(Equating) xsize(12) ysize(9) xtitle(Latent trait) "
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`flooru'(`gapu')`ceilu') color(erose)) || `pciset1' `pciset2' , yline(0, lcolor(black)) legend(off) name(equating,replace) ytitle(" Frequencies") /*ylabel(`ylbl', grid angle(0) axis(1))*/ ylabel(`ylabel1' "`eqset1name'" `ylabel2' "`eqset2name'" 0(`=`ceil'/5')`ceil', grid angle(0) axis(1)) title("`title'") subtitle("`dimname'") xsize(12) ysize(9) xtitle("Latent trait")
+ }
+ qui use `fileeq',clear
+ *set trace on
+ tempname scoreset1 scoreset2
+ forvalues t=1/2 {
+ qui genscore `eqset`t'' if `touse',score(`scoreset`t'')
+ qui su `scoreset`t'' if `touse'
+ local maxscoreset=r(max)
+ *qui matrix list `matscore`t''
+ if "`eqgenscore'"!="" {
+ local eqgenscore `=regexreplaceall("`eqgenscore'"," ","_")'
+ *di "eqgenscore : `eqgenscore'"
+ foreach k in mean min max random {
+ capture confirm variable `eqgenscore'_`k'_`eqset`=3-`t''name'
+ if _rc==0&"`replace'"!="" {
+ qui replace `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ else if _rc==0&"`replace'"!="" {
+ di as error "The variable `eqgenscore'_`k'_`eqset`=3-`t''name' already exists"
+ error 198
+ }
+ else {
+ qui gen `eqgenscore'_`k'_`eqset`=3-`t''name'=. if `touse'
+ }
+ }
+ *tab `scoreset`t''
+ forvalues s=0/`maxscoreset' {
+ *di "qui replace `eqgenscore'_`eqset`=3-`t''name'=`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''' if `scoreset`t''==`s'"
+ local min=min(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ local max=max(`=(`matscore`t''[`=`s'+1',6]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',`=(`matscore`t''[`=`s'+1',7]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''')
+ qui replace `eqgenscore'_mean_`eqset`=3-`t''name'=round(`=(`matscore`t''[`=`s'+1',5]+`eqaddset`=3-`t''')*`eqmultset`=3-`t'''',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_min_`eqset`=3-`t''name'=round(`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_max_`eqset`=3-`t''name'=round(`max',1) if round(`scoreset`t'',1)==`s'&`touse'
+ qui replace `eqgenscore'_random_`eqset`=3-`t''name'=round(uniform()*(`max'-`min')+`min',1) if round(`scoreset`t'',1)==`s'&`touse'
+ }
+ }
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ }
+
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+*set trace on
+if "`visit'"!="" {
+ tempfile sauv
+ *set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_best
+ *capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=`corrlatent' if `touse'
+/* qui gen `genlt'_corr2=. if `touse'
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr2=`estlt`s'' if `score'==`s'&`touse'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr2=`clt`g'' if `group'==`g'&`genlt'_corr==.&`touse'
+ }
+*/
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=. if `touse'
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'&`touse'
+ }
+ }
+ *su
+ qui egen `genlt'_best=rowmean(`tmpitem'_*) if `touse'
+ *qui egen `genlt'_opt_se=rowsd(`tmpitem'_*) if `touse'
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*) if `touse'
+ *qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss') if `touse'
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin, footer(fall_report)
+ putdocx table hdr = (1, 3), border(all, nil) tofooter(fall_report)
+ if "`rsm'"=="" {
+ putdocx table hdr(1, 1) = ("Partial Credit Model")
+ }
+ else {
+ putdocx table hdr(1, 1) = ("Rating Scale Model")
+ }
+ putdocx table hdr(1, 2) = ("`dimname'"), halign(center)
+ putdocx table hdr(1, 3) = ("Page "), pagenumber
+ putdocx table hdr(1, 3) = ("/"), totalpages append
+ putdocx table hdr(1, 3), halign(right)
+ putdocx paragraph ,style(Title)
+ if "`dimname'" =="" {
+ local dimname2 "Rasch analysis"
+ }
+ else {
+ local dimname2 "Rasch analysis of the `dimname' dimension"
+ }
+ putdocx text ("`dimname2'") ,
+ putdocx paragraph ,style(Subtitle)
+ putdocx text ("General informations") ,
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("Names of the dimension: `dimname'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation of the parameters") ,
+ local paramname
+ forvalues j=1/`nbitems' {
+ forvalues k=1/`modamax' {
+ if `k'<=`modamax`j'' {
+ local paramname `paramname' "``j''_`k'"
+ }
+ }
+ }
+ *di "matrix colnames `diff'=`paramname'"
+ matrix rownames `diff'=`paramname'
+ putdocx table table1 = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1) halign(center)
+ putdocx table table1(.,1), halign(left)
+ putdocx table table1(.,2/7), halign(right)
+ putdocx table table1(1,.), halign(right) border(top) border(bottom)
+
+
+ qui putdocx table table2 = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table2(.,1), halign(left)
+ putdocx table table2(.,2/7), halign(right)
+ putdocx table table2(1,.), halign(right) border(top) border(bottom)
+
+
+
+
+ putdocx paragraph,style(Subtitle)
+ putdocx text ("Fit indexes for items") , /*bold underline font(,14) smallcaps*/
+ qui putdocx table table3 = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil) headerrow(1)
+ putdocx table table3(.,1), halign(left)
+ putdocx table table3(.,2/5), halign(right)
+ putdocx table table3(1,.), halign(right) border(top) border(bottom)
+
+
+
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Estimation per group/score")
+ *putdocx text ("Estimation per group/score") , bold underline font(,14) smallcaps
+ *set trace on
+ putdocx table tbl = (`=`nbrowmat'+1',7), border(all,nil) width(7) halign(center) note(EAP: Expected A Posteriori ; BE: Best Estimates) headerrow(1)
+ putdocx table tbl(1,.), halign(right) border(top) border(bottom)
+ putdocx table tbl(1,1) = ("Group"), halign(right)
+ putdocx table tbl(1,2) = ("score"), halign(right)
+ putdocx table tbl(1,3) = ("Frequency"), halign(right)
+ putdocx table tbl(1,4) = ("EAP Mean"), halign(right)
+ putdocx table tbl(1,5) = ("EAP s.e."), halign(right)
+ putdocx table tbl(1,6) = ("Exp score"), halign(right)
+ putdocx table tbl(1,7) = ("BE Mean"), halign(right)
+ local fin=1
+ forvalues row=1/`nbrowmat' {
+ local row2=`row'+1
+ local g: di %9.0f `matgroupscorelt'[`row',1]
+ local gh=`matgroupscorelt'[`row',1]
+ if `fin'==1 {
+ putdocx table tbl(`row2',1) = ("`g'"), halign(right)
+ }
+ if `matgroupscorelt'[`row',2]!=.|`matgroupscorelt'[`row',7]==. {
+ local s: di %9.0f `matgroupscorelt'[`row',2]
+ local fin=0
+ }
+ else {
+ local s "`scoremin`gh''/`scoremax`gh''"
+ local fin=1
+ *local fin "border(top) border(bottom)"
+ *di "c'est la fin"
+ putdocx table tbl(`row2',.), border(bottom) border(top, dashed)
+ putdocx table tbl(`row2',1), border(top, nil)
+ }
+ local eff: di %9.0f `matgroupscorelt'[`row',3]
+ local lt: di %9.3f `matgroupscorelt'[`row',4]
+ local se: di %9.3f `matgroupscorelt'[`row',5]
+ local exp: di %9.2f `matgroupscorelt'[`row',6]
+ local clt: di %9.3f `matgroupscorelt'[`row',7]
+ *putdocx table tbl(`row',.), addrows(7)
+ putdocx table tbl(`row2',2) = ("`s'"), halign(right)
+ putdocx table tbl(`row2',3) = ("`eff'"), halign(right)
+ putdocx table tbl(`row2',4) = ("`lt'"), halign(right)
+ putdocx table tbl(`row2',5) = ("`se'"), halign(right)
+ putdocx table tbl(`row2',6) = ("`exp'"), halign(right)
+ putdocx table tbl(`row2',7) = ("`clt'"), halign(right)
+
+ }
+
+/*
+ qui matrix `matgroupscorelt'[`row',1]=`g'
+ *qui matrix `matgroupscorelt'[`row',2]="`scoremin`g''/`scoremax`g''"
+ qui matrix `matgroupscorelt'[`row',3]=`eff`g''
+ qui matrix `matgroupscorelt'[`row',4]=`lt`g''
+ qui matrix `matgroupscorelt'[`row',5]=`se'
+ *qui matrix `matgroupscorelt'[`row',6]=`exp'
+ qui matrix `matgroupscorelt'[`row',7]=`clt`g''
+ local ++row
+ }
+ local nbrowmat=`row'-1
+
+
+local row 1
+local vari 1
+foreach x in gear_ratio turn foreign _cons {
+putdocx table tbl5(`row',.), addrows(2)
+local b: display %9.3f rtable[`vari',1]
+local se: display %9.3f rtable[`vari',2]
+local ++vari
+local ++row
+putdocx table tbl5(`row',1) = ("`x'"), halign(right)
+putdocx table tbl5(`row',2) = ("`b'"), halign(right)
+local ++row
+local se = strtrim("`se'")
+putdocx table tbl5(`row',2) = ("(`se')"), halign(right)
+}*/
+
+ *qui putdocx table tablename = matrix(`matgroupscorelt') , nformat(%9.3f) /*rownames*/ colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("General Graphs")
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ putdocx paragraph, style(Subtitle)
+ putdocx text ("Graphs per item")
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph, style(Heading1)
+ putdocx text ("Graphs for ``i''")
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+*set trace on
+
+matrix colnames `diff'="Estimate" "Std err" "z" "p" "lb" "ul"
+matrix colnames `covariates'=Estimate s.e. z p lb ul
+matrix rownames `diff'=`diffname'
+*matrix list `diff'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix matgroupscorelt=`matgroupscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm.sthlp b/Modules/ado/personal/p/pcm.sthlp
new file mode 100644
index 0000000..dd7e2e5
--- /dev/null
+++ b/Modules/ado/personal/p/pcm.sthlp
@@ -0,0 +1,167 @@
+{smcl}
+{* 2August2022}{...}
+{hline}
+help for {hi:pcm}{right:Jean-Benoit Hardouin, Myriam Blanchin}
+{hline}
+
+{title:Estimation of the parameters of a Partial Credit Model (PCM) or a Rating Scale Model (RSM) and specific graphs}
+
+{title:Syntax for Rasch analysis}
+
+{p 8 14 2}{cmd:pcm} {it:varlist} [{it:if}] [{it:in}]
+[, {cmdab:rsm} {cmdab:it:erate}({it:#}) {cmdab:model} {cmdab:diff:iculties}({it:matrix}) {cmdab:var:iance}({it:real}) {cmdab:minsize}({it:#})
+{cmdab:cont:inuous}({it:varlist}) {cmdab:cat:egorical}({ir:varlist})
+{cmdab:G:raphs} {cmdab:nographi:tems} {cmdab:dim:name}({it:string}) {cmdab:nocorr:ected} {cmdab:alpha}({it:#})
+{cmdab:filesave} {cmdab:extension}({it:string}) {cmdab:dirsave}({it:directory} {cmdab:docx}({it:string})
+{cmdab:genlt}({it:string}) {cmdab:geninf}({it:string}) {cmdab:rep:lace}
+
+{title:Syntax for Rasch equating}
+{p 8 14 2}{cmd:pcm} {it:varlist} [{it:if}] [{it:in}] [, {cmdab:rsm} {cmdab:it:erate}({it:#}) {cmdab:model} {cmdab:diff:iculties}({it:matrix}) {cmdab:var:iance}({it:real}) {cmdab:minsize}({it:#}) {cmdab:G:raphs} {cmdab:dim:name}({it:string}) {cmdab:eqset1}({it:varlist}) {cmdab:eqset2}({it:varlist}) {cmdab:eqset1name}({it:string}) {cmdab:eqset2name}({it:string}) {cmdab:EQG:raph} {cmdab:eqaddset1}({it:#}) {cmdab:eqaddset2}({it:#}) {cmdab:eqmultset1}({it:#) {cmdab:eqmultset2}({it:#})
+{cmdab:eqwithci} {cmdab:eqgenscore}({it:string}) {cmdab:rep:lace} ]
+
+
+{p 8 14 2}{it:varlist} is a list of two existing categorical variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:pcm} estimates the parameters of a Partial Credit Model (PCM) or of a Rating Scale Model (RSM). Parameters are estimated using Marginal Maximum Likelihood (MML). Several graphical representations can be easily obtained: comparison of the observed and theorical Item Characteristic Curves (ICC), Map difficulty parameters/Scores, results of the split tests, and information function (for the scale and by item). {cmd:pcm} allow equating two sets of items.
+
+{title:Options for a Rasch analysis}
+
+{p 4 8 2}{cmdab:rsm} estimates a Rating Scale Model instead of a Partial Credit Model.
+
+{p 4 8 2}{cmdab:it:erate} defines the maximal number of iterations of the maximisation algorithm.
+By default, this number is fixed to 100.
+
+{p 4 8 2}{cmd:model} displays the outputs of the maximisation alogorithm .
+
+{p 4 8 2}{cmdab:diff:iculties}({it:matrix}) fixes the values of the difficulties parameters of the items (by default, these values are estimated).
+The vector must be a matrix containing as many rows as items, and a column for each threshold parameter (number of answer categories minus 1).
+A missing value (.) replaces unexisting difficulty paremeters in the matrix.
+
+{p 4 8 2}{cmdab:var:iance}({it:#}) fixes the value of the variance of the latent trait (by default, this value is estimated).
+
+{p 4 8 2}{cmdab:minsize}({it:#}) fixes the minimal value of the groups (30 individuals by default).
+
+{p 4 8 2}{cmdab:cont:inuous}({it:varlist}) defines a list of continuous variables explaining the latent trait.
+
+{p 4 8 2}{cmdab:cat:egorical}({it:varlist}) defines a list of categorical variables explaining the latent trait.
+
+{p 4 8 2}{cmdab:G:raphs} displays the graphs.
+
+{p 4 8 2}{cmdab:nographi:tems} avoids displaying the graphs by items.
+
+{p 4 8 2}{cmdab:dim:name}({it:string}) defines the name of the analysed dimension (this name appears on the graphs).
+
+{p 4 8 2}{cmdab:nocorr:ected} avoids using corrected latent trait estimates on the graphs.
+
+{p 4 8 2}{cmdab:alpha}({it:#}) defines the level of confidence of the interval presented on the graphs of residuals.
+
+{p 4 8 2}{cmdab:filesave} save the graph files.
+
+{p 4 8 2}{cmdab:extension}({it:string}) defines the extension of the graph files.
+
+{p 4 8 2}{cmdab:dirsave}({it:directory} defines the directory to save the graph files and the docx file.
+
+{p 4 8 2}{cmdab:docx}({it:string}) creates a docx file with the main results and graphs.
+
+{p 4 8 2}{cmdab:genlt}({it:string}) creates several variables. The new variables {it:string} contains Expected A Posteriori estimates of the latent trait and {it:string_se} their standard deviations. The new variable {it:string_corr} contains estimates of the latent traits allowing obtaining the closer estimations of the item-sum scores. The new variables {it:string_opt} contains estimated of the latent traits obtained by searching, for each observed item to maximize the probability to obtain the observed answer (the obtained value is the mean of all these estimates).
+
+{p 4 8 2}{cmd:geninf}({it:string}) contains the information associated for each individual.
+
+{p 4 8 2}{cmdab:rep:lace} specifies that the existing files or variables will be replaced.
+
+{title:Options for a Rasch equating}
+
+
+{p 4 8 2}{cmdab:rsm} estimates a Rating Scale Model instead of a Partial Credit Model.
+
+{p 4 8 2}{cmdab:it:erate} defines the maximal number of iterations of the maximisation algorithm.
+By default, this number is fixed to 100.
+
+{p 4 8 2}{cmd:model} displays the outputs of the maximisation alogorithm .
+
+{p 4 8 2}{cmdab:diff:iculties}({it:matrix}) fixes the values of the difficulties parameters of the items (by default, these values are estimated).
+The vector must be a matrix containing as many rows as items, and a column for each threshold parameter (number of answer categories minus 1).
+A missing value (.) replaces unexisting difficulty paremeters in the matrix.
+
+{p 4 8 2}{cmdab:var:iance}({it:#}) fixes the value of the variance of the latent trait (by default, this value is estimated).
+
+{p 4 8 2}{cmdab:minsize}({it:#}) fixes the minimal value of the groups (30 individuals by default).
+
+{p 4 8 2}{cmdab:G:raphs} displays the graphs.
+
+{p 4 8 2}{cmdab:dim:name}({it:string}) defines the name of the analysed dimension (this name appears on the graphs).
+
+{p 4 8 2}{cmdab:eqset1}({it:varlist}) and {cmdab:eqset2}({it:varlist}) define the items containing in the two sets of items to equate (disjoint or not sets of items)
+
+{p 4 8 2}{cmdab:eqset1name}({it:string}) and {cmdab:eqset2name}({it:string}) define the names of the two sets of items (set1 and set2 by default). The string cannot contains spaces if the version of Stata is 17 or less.
+
+{p 4 8 2}{cmdab:EQG:raph} displays graphs
+
+{p 4 8 2}{cmdab:eqaddset1}({it:#}) and {cmdab:eqaddset2}({it:#}) allows adding a real to the row score to obtain a linear transformed score for each set of items (0 by default)
+
+{p 4 8 2}{cmdab:eqmultset1}({it:#) and {cmdab:eqmultset2}({it:#}) allows multiplying the row score by a real to obtain a linear transformed score for each set of items (1 by default)
+
+{p 4 8 2}{cmdab:eqwithci} allows representing the 95% confidence interval of the equated score on the graph
+
+{p 4 8 2}{cmdab:eqgenscore}({it:string}) create several variables containing the center (_mean_), the minimal (_min_) and the maximal (_max_) values of the 95% confidence interval and a random value (_random_) drawn in this interval
+
+{p 4 8 2}{cmdab:rep:lace} specifies that the existing files or variables will be replaced.
+
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:e()}: Output of the gsem procedure
+
+{p 4 8 2}{cmd:r(ll)}: Marginal Log-likelihood
+
+{p 4 8 2}{cmd:r(PSI)}: Personal Separation Index
+
+{p 4 8 2}{cmd:r(difficulties)}: Estimates of the threshold parameters
+
+{p 4 8 2}{cmd:r(matscorelt)} : estimates of the latent trait associated to each complete item-sum score
+
+{p 4 8 2}{cmd:r(matgroupscorelt)} : estimates of the latent trait associated to each complete item-sum score and to each group of individuals used for graphical fit tests
+
+{p 4 8 2}{cmd:r(covariates)} : estimates of the variance of the latent trait and of the parameters associates to covariates
+
+{p 4 8 2}{cmd:r(bestest)}: estimates of the latent trait obtained for each item by searching the value maximizing the response to each answer category
+
+{p 4 8 2}{cmd:r(score2_to_1)} : gives the results to equate the raw scores of the set2 to set1
+
+{p 4 8 2}{cmd:r(score1_to_2)}: gives the results to equate the raw scores of the set1 to set2
+
+
+
+{title:Examples of Rasch analysis}
+
+{p 4 8 2}{cmd: . pcm item1-item9}
+
+{p 4 8 2}{cmd: . pcm item*, graph dirsave(c:\graphs) filesave genlt(lt) docx(report)}
+
+{p 4 8 2}{cmd: . matrix diff=(-1,-0.8,0.2\-.5,0,0.5\0,1,.\0.2,1,1.2\0.5,.,.)}{p_end}
+{p 4 8 2}{cmd: . pcm item1-item5 , diff(diff) cat(sex) cont(age) }
+
+{title:Example of Rasch equating}
+
+{p 4 8 2}{cmd: . pcm item1-item9, eqset1(item1-item5) eqset2(item6-item9) eqnameset1(First part) eqnameset2(Second part) eqaddset1(5) eqmultset1(-1) graph}
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD-HDR, Associate professor - Hospital Practitioner{p_end}
+{p 4 8 2}Myriam Blanchin, PhD, Research engineer{p_end}
+{p 4 8 2}INSERM UMR 1246-SPHERE "Methods in Patients Centered Outcomes and Health Research"{p_end}
+{p 4 8 2}Nantes University - Faculty of Medicine{p_end}
+{p 4 8 2}Intitute of Research in Health 2{p_end}
+{p 4 8 2}22 boulevard BĂ©noni-Goullin{p_end}
+{p 4 8 2}44200 Nantes - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}, {browse "mailto:myriam.blanchin@univ-nantes.fr":myriam.blanchin@univ-nantes.fr}{p_end}
+
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help raschtest} and {help gsem} if installed.{p_end}
+
diff --git a/Modules/ado/personal/p/pcm.zip b/Modules/ado/personal/p/pcm.zip
new file mode 100644
index 0000000..b0bba31
Binary files /dev/null and b/Modules/ado/personal/p/pcm.zip differ
diff --git a/Modules/ado/personal/p/pcm21.ado b/Modules/ado/personal/p/pcm21.ado
new file mode 100644
index 0000000..8e0ef5c
--- /dev/null
+++ b/Modules/ado/personal/p/pcm21.ado
@@ -0,0 +1,244 @@
+*! Version 2.1 18october2011
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007
+* Version 2 : July 15, 2011
+* Version 2.1 : October 18th, 2011 : -fixedvar- option, new presentation
+*
+* Jean-benoit Hardouin, EA4275 Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* Faculties of Pharmaceutical Sciences & Medicine - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007, 2011 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 pcm,eclass
+version 8.0
+syntax varlist(min=3 numeric) [if] [in] [,rsm fixed(string) fixedvar(real -1) fixedmu short COVariates(varname)]
+preserve
+tempfile pcmfile
+qui save `pcmfile',replace
+
+if "`fixedmu'"!=""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the mean (fixedmu option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+if "`fixed'"!=""&"`fixedmu'"==""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the difficulties (fixed option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+
+/*******************************************************************************
+ESTIMATION OF THE PARAMETERS
+********************************************************************************/
+
+marksample touse
+qui keep if `touse'
+qui count
+local N=r(N)
+tokenize `varlist'
+local nbitems : word count `varlist'
+
+if "`rsm'"=="" {
+ di in gr "Model: " in ye "Partial Credit Model"
+}
+else {
+ di in gr "Model: " in ye "Rating Scale Model"
+}
+
+tempname one var w id item it obs x chosen d score
+qui gen `one'=1
+qui gen `id'=_n
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui rename ``i'' `var'`i'
+ qui su `var'`i'
+ local moda`i'=`r(max)'
+ if `modamax'<`r(max)' {
+ local modamax=r(max)
+ }
+}
+qui genscore `var'1-`var'`nbitems' ,score(`score')
+qui collapse (sum) `w'=`one',by(`var'1-`var'`nbitems' `covariates')
+qui gen `id'=_n
+qui reshape long `var',i(`id') j(`item')
+qui drop if `var'==.
+qui gen `obs'=_n
+qui expand `=`modamax'+1'
+qui sort `id' `item' `obs'
+by `obs', sort: gen `x'=_n-1
+
+qui gen `chosen'=`var'==`x'
+qui tab `item', gen(`it')
+forvalues i=1/`nbitems' {
+ forvalues g=1/`modamax' {
+ qui gen `d'`i'_`g'=-1*`it'`i'*(`x'>=`g')
+ }
+}
+qui rename `w' `w'2
+bysort `id':egen score=sum(`x'*`chosen')
+qui su score
+local maxscore=r(max)
+
+
+if "`covariates'"!="" {
+ qui gen covw=`covariates'*`x'
+ local listcov covw
+}
+else {
+ local listcov
+}
+if `fixedvar'!=-1 {
+ local tmp=sqrt(`fixedvar')
+ constraint 1 `x'=`tmp'
+ local listconstr "constraints(1)"
+}
+if "`rsm'"=="" {
+ if "`fixed'"!="" {
+ qui gen offset=0
+ local l=1
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ qui replace offset=offset+`fixed'[1,`l']*`d'`i'_`mi'
+ local ++l
+ }
+ }
+ if "`fixedmu'"!="" {
+ local mu
+ }
+ else {
+ local mu "`x'"
+ }
+
+ eq slope:`x'
+ noi di "gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace"
+ gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace
+ }
+ else if "`short'"!="" {
+ eq slope:`x'
+ qui gllamm `x' `d'1_1-`d'`nbitems'_`modamax',i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons init
+ tempname bsave Vsave
+ matrix `bsave'=e(b)
+ matrix `Vsave'=e(V)
+ restore
+ qui pcm `varlist' , fixed(`bsave')
+ }
+ else {
+ di "no short"
+ eq slope:`x'
+ qui gen i=`id'
+ constraint 1 `x'=1
+ gllamm `x' `d'1_1-`d'`nbitems'_`modamax' `listcov',i(i) `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons
+ }
+}
+else {
+ tempname step n
+ forvalues i=2/`modamax' {
+ qui gen `step'`i'=-1*(`x'>=`i')
+ }
+ forvalues i=1/`nbitems' {
+ qui gen `n'`var'`i'=(-1)*(`it'`i')*(`x')
+ }
+ qui sort `id' `item' `x'
+ eq slope:`x'
+ gllamm `x' `n'`var'1-`n'`var'`nbitems' `step'2-`step'`modamax' `listcov', i(`id') `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons
+}
+
+tempname b V chol
+matrix b=e(b)
+matrix V=e(V)
+local ll=e(ll)
+matrix chol=e(chol)
+
+
+if "`rsm'"=="" {
+ di
+ di in gr "Number of observations: " in ye `N'
+ di in gr "Number of items: " in ye `nbitems'
+ di in gr "Number of parameters: " in ye `=`nbitems'*`modamax'+1'
+ di in gr "Log-likelihood: " in ye `ll'
+ di
+ di
+ di in gr "{hline 100}"
+ di in gr "Item" _col(10) "Modality" _col(20) "Parameter" _col(30) "Std Error"
+ di in gr "{hline 100}"
+ if "`fixed'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ if "`short'"!="" {
+ di in ye _col(17) `j' _col(20) %9.6f `bsave'[1,`k'] in ye _col(30) %9.6f (`Vsave'[`k',`k'])^.5
+ }
+ else {
+ di in ye _col(17) `j' _col(20) %9.6f b[1,`k'] in ye _col(30) %9.6f (V[`k',`k'])^.5
+ }
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ else {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ di in ye _col(17) `j' _col(20) %9.6f `fixed'[1,`k'] in ye _col(32) "(fixed)"
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ if "`fixed'"==""&"`short'"=="" {
+ local k=`nbitems'*`modamax'+1
+ }
+ else if "`fixed'"!=""&"`fixedmu'"=="" {
+ di in ye "Mu" in ye _col(20) %9.6f b[1,1] _col(29) %10.6f (V[1,1])^.5
+ local k=2
+ }
+ else if "`fixed'"!=""&"`fixedmu'"!="" {
+ di in ye "Mu" in ye _col(20) %9.6f 0 _col(32) %10.6f "(fixed)"
+ local k=1
+ }
+ else {
+ local k=1
+ }
+ if "`covariates'"!="" {
+ di in ye "`covariates'" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ local k=`k'+1
+ }
+ if `fixedvar'==-1 {
+ di in ye "Sigma" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ di in ye "Variance" in ye _col(20) %9.6f b[1,`k']^2 _col(29) %10.6f 2*(V[`k',`k'])^.5*b[1,`k']
+ }
+ else {
+ di in ye "Sigma" in ye _col(20) %9.6f `fixedvar'^.5 _col(32) %10.6f "(fixed)"
+ di in ye "Variance" in ye _col(20) %9.6f `fixedvar' _col(32) %10.6f "(fixed)"
+ }
+ di in gr "{hline 100}"
+ di
+ di
+}
+
+end
diff --git a/Modules/ado/personal/p/pcm22.ado b/Modules/ado/personal/p/pcm22.ado
new file mode 100644
index 0000000..3320946
--- /dev/null
+++ b/Modules/ado/personal/p/pcm22.ado
@@ -0,0 +1,245 @@
+*! Version 2.2 23october2013
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007
+* Version 2 : July 15, 2011
+* Version 2.1 : October 18th, 2011 : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 : correction of -fixedvar- option
+*
+* Jean-benoit Hardouin, EA4275 Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* Faculties of Pharmaceutical Sciences & Medicine - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007, 2011 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 pcm,eclass
+version 8.0
+syntax varlist(min=3 numeric) [if] [in] [,rsm fixed(string) fixedvar(real -1) fixedmu short COVariates(varname)]
+preserve
+tempfile pcmfile
+qui save `pcmfile',replace
+
+if "`fixedmu'"!=""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the mean (fixedmu option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+if "`fixed'"!=""&"`fixedmu'"==""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the difficulties (fixed option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+
+/*******************************************************************************
+ESTIMATION OF THE PARAMETERS
+********************************************************************************/
+
+marksample touse
+qui keep if `touse'
+qui count
+local N=r(N)
+tokenize `varlist'
+local nbitems : word count `varlist'
+
+if "`rsm'"=="" {
+ di in gr "Model: " in ye "Partial Credit Model"
+}
+else {
+ di in gr "Model: " in ye "Rating Scale Model"
+}
+
+tempname one var w id item it obs x chosen d score
+qui gen `one'=1
+qui gen `id'=_n
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui rename ``i'' `var'`i'
+ qui su `var'`i'
+ local moda`i'=`r(max)'
+ if `modamax'<`r(max)' {
+ local modamax=r(max)
+ }
+}
+qui genscore `var'1-`var'`nbitems' ,score(`score')
+qui collapse (sum) `w'=`one',by(`var'1-`var'`nbitems' `covariates')
+qui gen `id'=_n
+qui reshape long `var',i(`id') j(`item')
+qui drop if `var'==.
+qui gen `obs'=_n
+qui expand `=`modamax'+1'
+qui sort `id' `item' `obs'
+by `obs', sort: gen `x'=_n-1
+
+qui gen `chosen'=`var'==`x'
+qui tab `item', gen(`it')
+forvalues i=1/`nbitems' {
+ forvalues g=1/`modamax' {
+ qui gen `d'`i'_`g'=-1*`it'`i'*(`x'>=`g')
+ }
+}
+qui rename `w' `w'2
+bysort `id':egen score=sum(`x'*`chosen')
+qui su score
+local maxscore=r(max)
+
+
+if "`covariates'"!="" {
+ qui gen covw=`covariates'*`x'
+ local listcov covw
+}
+else {
+ local listcov
+}
+if `fixedvar'!=-1 {
+ local tmp=sqrt(`fixedvar')
+ constraint 1 `x'=`tmp'
+ local listconstr "constraints(1)"
+}
+if "`rsm'"=="" {
+ if "`fixed'"!="" {
+ qui gen offset=0
+ local l=1
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ qui replace offset=offset+`fixed'[1,`l']*`d'`i'_`mi'
+ local ++l
+ }
+ }
+ if "`fixedmu'"!="" {
+ local mu
+ }
+ else {
+ local mu "`x'"
+ }
+
+ eq slope:`x'
+ noi di "gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace"
+ gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace
+ }
+ else if "`short'"!="" {
+ eq slope:`x'
+ qui gllamm `x' `d'1_1-`d'`nbitems'_`modamax',i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons init
+ tempname bsave Vsave
+ matrix `bsave'=e(b)
+ matrix `Vsave'=e(V)
+ restore
+ qui pcm `varlist' , fixed(`bsave')
+ }
+ else {
+ di "no short"
+ eq slope:`x'
+ qui gen i=`id'
+ constraint 1 `x'=1
+ gllamm `x' `d'1_1-`d'`nbitems'_`modamax' `listcov',i(i) `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons
+ }
+}
+else {
+ tempname step n
+ forvalues i=2/`modamax' {
+ qui gen `step'`i'=-1*(`x'>=`i')
+ }
+ forvalues i=1/`nbitems' {
+ qui gen `n'`var'`i'=(-1)*(`it'`i')*(`x')
+ }
+ qui sort `id' `item' `x'
+ eq slope:`x'
+ gllamm `x' `n'`var'1-`n'`var'`nbitems' `step'2-`step'`modamax' `listcov', i(`id') `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons
+}
+
+tempname b V chol
+matrix b=e(b)
+matrix V=e(V)
+local ll=e(ll)
+matrix chol=e(chol)
+
+
+if "`rsm'"=="" {
+ di
+ di in gr "Number of observations: " in ye `N'
+ di in gr "Number of items: " in ye `nbitems'
+ di in gr "Number of parameters: " in ye `=`nbitems'*`modamax'+1'
+ di in gr "Log-likelihood: " in ye `ll'
+ di
+ di
+ di in gr "{hline 100}"
+ di in gr "Item" _col(10) "Modality" _col(20) "Parameter" _col(30) "Std Error"
+ di in gr "{hline 100}"
+ if "`fixed'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ if "`short'"!="" {
+ di in ye _col(17) `j' _col(20) %9.6f `bsave'[1,`k'] in ye _col(30) %9.6f (`Vsave'[`k',`k'])^.5
+ }
+ else {
+ di in ye _col(17) `j' _col(20) %9.6f b[1,`k'] in ye _col(30) %9.6f (V[`k',`k'])^.5
+ }
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ else {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ di in ye _col(17) `j' _col(20) %9.6f `fixed'[1,`k'] in ye _col(32) "(fixed)"
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ if "`fixed'"==""&"`short'"=="" {
+ local k=`nbitems'*`modamax'+1
+ }
+ else if "`fixed'"!=""&"`fixedmu'"=="" {
+ di in ye "Mu" in ye _col(20) %9.6f b[1,1] _col(29) %10.6f (V[1,1])^.5
+ local k=2
+ }
+ else if "`fixed'"!=""&"`fixedmu'"!="" {
+ di in ye "Mu" in ye _col(20) %9.6f 0 _col(32) %10.6f "(fixed)"
+ local k=1
+ }
+ else {
+ local k=1
+ }
+ if "`covariates'"!="" {
+ di in ye "`covariates'" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ local k=`k'+1
+ }
+ if `fixedvar'==-1 {
+ di in ye "Sigma" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ di in ye "Variance" in ye _col(20) %9.6f b[1,`k']^2 _col(29) %10.6f 2*(V[`k',`k'])^.5*b[1,`k']
+ }
+ else {
+ di in ye "Sigma" in ye _col(20) %9.6f `fixedvar'^.5 _col(32) %10.6f "(fixed)"
+ di in ye "Variance" in ye _col(20) %9.6f `fixedvar' _col(32) %10.6f "(fixed)"
+ }
+ di in gr "{hline 100}"
+ di
+ di
+}
+
+end
diff --git a/Modules/ado/personal/p/pcm23.ado b/Modules/ado/personal/p/pcm23.ado
new file mode 100644
index 0000000..ab130f2
--- /dev/null
+++ b/Modules/ado/personal/p/pcm23.ado
@@ -0,0 +1,283 @@
+*! Version 2.3 10april2014
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007
+* Version 2 : July 15, 2011
+* Version 2.1 : October 18th, 2011 : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 : correction of -fixedvar- option
+*
+* Jean-benoit Hardouin, EA4275 Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* Faculties of Pharmaceutical Sciences & Medicine - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007-2014 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 pcm,eclass
+version 8.0
+syntax varlist(min=3 numeric) [if] [in] [,rsm fixed(string) fixedvar(real -1) fixedmu short COVariates(varname) fixedvargroupc(string) vargroupc]
+preserve
+tempfile pcmfile
+qui save `pcmfile',replace
+
+if "`fixedmu'"!=""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the mean (fixedmu option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+if "`fixed'"!=""&"`fixedmu'"==""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the difficulties (fixed option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+
+/*******************************************************************************
+ESTIMATION OF THE PARAMETERS
+********************************************************************************/
+
+marksample touse
+qui keep if `touse'
+qui count
+local N=r(N)
+tokenize `varlist'
+local nbitems : word count `varlist'
+
+if "`rsm'"=="" {
+ di in gr "Model: " in ye "Partial Credit Model"
+}
+else {
+ di in gr "Model: " in ye "Rating Scale Model"
+}
+
+tempname one var w id item it obs x chosen d score
+qui gen `one'=1
+qui gen `id'=_n
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui rename ``i'' `var'`i'
+ qui su `var'`i'
+ local moda`i'=`r(max)'
+ if `modamax'<`r(max)' {
+ local modamax=r(max)
+ }
+}
+qui genscore `var'1-`var'`nbitems' ,score(`score')
+qui collapse (sum) `w'=`one',by(`var'1-`var'`nbitems' `covariates')
+qui gen `id'=_n
+qui reshape long `var',i(`id') j(`item')
+qui drop if `var'==.
+qui gen `obs'=_n
+qui expand `=`modamax'+1'
+qui sort `id' `item' `obs'
+by `obs', sort: gen `x'=_n-1
+
+qui gen `chosen'=`var'==`x'
+qui tab `item', gen(`it')
+forvalues i=1/`nbitems' {
+ forvalues g=1/`modamax' {
+ qui gen `d'`i'_`g'=-1*`it'`i'*(`x'>=`g')
+ }
+}
+qui rename `w' `w'2
+bysort `id':egen score=sum(`x'*`chosen')
+qui su score
+local maxscore=r(max)
+
+
+if "`covariates'"!="" {
+ qui gen covw=`covariates'*`x'
+ local listcov covw
+}
+else {
+ local listcov
+}
+if `fixedvar'!=-1 {
+ local tmp=sqrt(`fixedvar')
+ constraint 1 `x'=`tmp'
+ local listconstr "constraints(1)"
+ local eq "eqs(slope) nrf(1)"
+}
+local eq "eqs(slope) nrf(1)"
+*set trace on
+if "`rsm'"=="" { /*PARTIAL CREDIT MODEL*/
+ *di "cas 1"
+ if "`fixed'"!="" { /*FIXED ITEMS DIFFICULTIES*/
+ *di "cas 2"
+ qui gen offset=0
+ local l=1
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ qui replace offset=offset+`fixed'[1,`l']*`d'`i'_`mi'
+ local ++l
+ }
+ }
+ if "`fixedmu'"!="" {
+ local mu
+ }
+ else {
+ local mu "`x'"
+ }
+*set trace on
+ if "`fixedvargroupc'"!=""|"`vargroupc'"!="" {/*INEQUAL VARIANCES*/
+ local var0: word 1 of `fixedvargroupc'
+ local var1: word 2 of `fixedvargroupc'
+ tempvar G0 G1
+ qui gen `G0'=groupc<0
+ qui gen `G1'=groupc>0
+ qui replace `G0'=`G0'*`x'
+ qui replace `G1'=`G1'*`x'
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`fixedvargroupc'"!="" {/*FIXED INEQUAL VARIANCES*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ local listconstr "constraints(1 2 3)"
+ }
+ else { /*FREE INEQUAL VARIANCE*/
+ local listconstr "constraints(1)"
+ }
+ local eq "eqs(B0 B1) nrf(2)"
+ }
+ eq slope:`x'
+ su
+ tab covw
+ di "ICI*******************jb"
+ di "`x' : x"
+ di "`listcov' : listcov"
+ di "`mu' : mu"
+ noi di "gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace `eq'"
+*set trace on
+ noi gllamm `x' `listcov' `mu' ,offset(offset) `listconstr' nocons i(`id') link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace `eq' iterate(100)
+ }
+ else if "`short'"!="" {
+ *di "cas 3"
+ eq slope:`x'
+ qui gllamm `x' `d'1_1-`d'`nbitems'_`modamax',i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons init iterate(100)
+ tempname bsave Vsave
+ matrix `bsave'=e(b)
+ matrix `Vsave'=e(V)
+ restore
+ qui pcm `varlist' , fixed(`bsave')
+ }
+ else {
+ *di "cas 4"
+ di "no short"
+ eq slope:`x'
+ qui gen i=`id'
+ constraint 1 `x'=1
+ gllamm `x' `d'1_1-`d'`nbitems'_`modamax' `listcov',i(i) `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons iterate(100)
+ }
+}
+else {
+ *di "cas 5"
+
+ tempname step n
+ forvalues i=2/`modamax' {
+ qui gen `step'`i'=-1*(`x'>=`i')
+ }
+ forvalues i=1/`nbitems' {
+ qui gen `n'`var'`i'=(-1)*(`it'`i')*(`x')
+ }
+ qui sort `id' `item' `x'
+ eq slope:`x'
+ gllamm `x' `n'`var'1-`n'`var'`nbitems' `step'2-`step'`modamax' `listcov', i(`id') `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons iterate(100)
+}
+
+tempname b V chol
+matrix b=e(b)
+matrix V=e(V)
+local ll=e(ll)
+matrix chol=e(chol)
+
+
+if "`rsm'"=="" {
+ di
+ di in gr "Number of observations: " in ye `N'
+ di in gr "Number of items: " in ye `nbitems'
+ di in gr "Number of parameters: " in ye `=`nbitems'*`modamax'+1'
+ di in gr "Log-likelihood: " in ye `ll'
+ di
+ di
+ di in gr "{hline 100}"
+ di in gr "Item" _col(10) "Modality" _col(20) "Parameter" _col(30) "Std Error"
+ di in gr "{hline 100}"
+ if "`fixed'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ if "`short'"!="" {
+ di in ye _col(17) `j' _col(20) %9.6f `bsave'[1,`k'] in ye _col(30) %9.6f (`Vsave'[`k',`k'])^.5
+ }
+ else {
+ di in ye _col(17) `j' _col(20) %9.6f b[1,`k'] in ye _col(30) %9.6f (V[`k',`k'])^.5
+ }
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ else {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ di in ye _col(17) `j' _col(20) %9.6f `fixed'[1,`k'] in ye _col(32) "(fixed)"
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ if "`fixed'"==""&"`short'"=="" {
+ local k=`nbitems'*`modamax'+1
+ }
+ else if "`fixed'"!=""&"`fixedmu'"=="" {
+ di in ye "Mu" in ye _col(20) %9.6f b[1,1] _col(29) %10.6f (V[1,1])^.5
+ local k=2
+ }
+ else if "`fixed'"!=""&"`fixedmu'"!="" {
+ di in ye "Mu" in ye _col(20) %9.6f 0 _col(32) %10.6f "(fixed)"
+ local k=1
+ }
+ else {
+ local k=1
+ }
+ if "`covariates'"!="" {
+ di in ye "`covariates'" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ local k=`k'+1
+ }
+ if `fixedvar'==-1 {
+ di in ye "Sigma" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ di in ye "Variance" in ye _col(20) %9.6f b[1,`k']^2 _col(29) %10.6f 2*(V[`k',`k'])^.5*b[1,`k']
+ }
+ else {
+ di in ye "Sigma" in ye _col(20) %9.6f `fixedvar'^.5 _col(32) %10.6f "(fixed)"
+ di in ye "Variance" in ye _col(20) %9.6f `fixedvar' _col(32) %10.6f "(fixed)"
+ }
+ di in gr "{hline 100}"
+ di
+ di
+}
+
+end
diff --git a/Modules/ado/personal/p/pcm3.2.ado b/Modules/ado/personal/p/pcm3.2.ado
new file mode 100644
index 0000000..2215ace
--- /dev/null
+++ b/Modules/ado/personal/p/pcm3.2.ado
@@ -0,0 +1,917 @@
+*! Version 3.2 17july2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+*
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(string) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string)]
+
+qui count
+local nbobs=r(N)
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+local modcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local modcont (`modcont'->T)
+}
+
+local modcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local modcat (`modcat'->T)
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ local modamax``i''=r(max)
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax``i'''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax``i''' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local code `code' `code`k''
+}
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+if "`difficulties'"!="" {
+ local t=1
+ local constraints
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax``i''' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ local val=0
+ forvalues l=1/`k' {
+ local val=`val'-`difficulties'[`i',`l']
+ }
+ constraint `t' [`k'.``i'']_cons=`val'
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+
+if "`rsm'"!="" {
+ local t=1
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ constraint `t' [`=`k'-1'.``i'']_cons-[`k'.``i'']_cons+[1.``i'']_cons=[`=`k'-1'.`1']_cons-[`k'.`1']_cons+[1.`1']_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')"
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2
+tempname groups
+qui predict mu, mu
+*su mu
+qui predict `latent',latent se(`selatent')
+set seed 123456
+qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+qui genscore `varlist',score(`score')
+qui gengroup `latent',newvariable(`group') continuous
+qui levelsof `group'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'==`g'
+ qui count if ``i''!=.&`group'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i'' if `group'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent' if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+qui count if `score'!=.
+local nbobsssmd=r(N)
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i'':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i'':_cons]
+ qui lincom -_b[1.``i'':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i'':_cons]^2
+ local rn `rn' 1.``i''
+ local ++t
+ local sum _b[1.``i'':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax``i''' {
+ local sum "_b[`k'.``i'':_cons]-`sum'"
+ qui lincom -(`sum')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1':_cons]-_b[`k'.`1':_cons]+_b[1.`1':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES ET LA VARIANCE
+*************************************************************************************************************/
+
+tempname covariates
+qui matrix `covariates'=J(`=`nbpar'+1',6,.)
+
+*set trace on
+if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T)]
+}
+else {
+ qui lincom _b[/var(T)]
+}
+qui matrix `covariates'[1,1]=`r(estimate)'
+qui matrix `covariates'[1,2]=`r(se)'
+qui matrix `covariates'[1,3]=`r(z)'
+qui matrix `covariates'[1,4]=`r(p)'
+qui matrix `covariates'[1,5]=`r(lb)'
+qui matrix `covariates'[1,6]=`r(ub)'
+
+local t=2
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+* matrix list `covariates'
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+
+local t=1
+local diffname
+*set trace on
+di "{hline 73}"
+di as text _col(60) "<--95% IC -->"
+di "Items" _col(60) "Lower" _col(68) "Upper"
+di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+di "{hline 73}"
+*set trace on
+forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax``i''' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+}
+di as text "{hline 73}"
+local t=1
+local n: word count Variance `continuous'
+forvalues i=1/`n' {
+ local v: word `i' of Variance `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+}
+
+local rn Variance `continuous'
+
+local n: word count of `categorical'
+local catname
+forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ local ++t
+}
+di as text "{hline 73}"
+di
+qui su `latent'
+qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])^2)
+di as text "PSI:" as result %4.2f `PSI'
+di
+
+
+
+matrix colnames `covariates'=`cn'
+matrix rownames `covariates'=`rn'
+
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+tempname fit
+qui matrix `fit'=J(`nbitems',4,.)
+matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+matrix rownames `fit'=`varlist'
+*matrix list `fit'
+
+tempvar Tcum TInf cum
+qui gen `Tcum'=0
+qui gen `TInf'=0
+di as text "{hline 90}"
+di as text _col(60) "<--- Standardized --->"
+di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+di as text "{hline 90}"
+di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+di as text "{hline 90}"
+
+*set trace on
+local chi2=0
+local chi2_old=0
+forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+}
+forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving(`dirsave'//residuals_``i'',replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+
+}
+di as text "{hline 90}"
+di as text "*: As suggested by Wright (Smith, 1998)
+di as text "**: As suggested by Bond and Fox (2007)
+
+set trace off
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+
+if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving(`dirsave'//CCC_``i'',replace)
+ local fsi saving(`dirsave'//ICC_``i'',replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving(`dirsave'//TCC,replace)
+ local fsteo saving(`dirsave'//TCCeo,replace)
+ local fsi saving(`dirsave'//ICC,replace)
+ local fsti saving(`dirsave'//TIC,replace)
+ local fsm saving(`dirsave'//map,replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil' {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+
+di
+di as text "{hline 57}"
+di _col(31) "Latent Variable" _col(50) "Expected"
+di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+di as text "{hline 57}"
+*set trace on
+forvalues g=1/`nbgroups' {
+ qui count if `group'==`g'
+ local eff`g'=r(N)
+ qui count if `score'!=.&`group'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score' if `group'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'==`g'&`score'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'==`g'&`score'==.
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+}
+
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export `dirsave'//`i'.`extension', replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save `dirsave'//`i', replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image `dirsave'//`i'.png, height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save `dirsave'//`j'_``i'', replace
+
+ if "`extension'"!="" {
+ qui graph export `dirsave'//`j'_``i''.`extension', replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image `dirsave'//`j'_``i''.png , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save `dirsave'//`docx'.docx, replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+restore, preserve
+end
diff --git a/Modules/ado/personal/p/pcm3.3.ado b/Modules/ado/personal/p/pcm3.3.ado
new file mode 100644
index 0000000..ea5fe5d
--- /dev/null
+++ b/Modules/ado/personal/p/pcm3.3.ado
@@ -0,0 +1,984 @@
+*! Version 3.3 25july2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+*
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(name) GENINF(name) postpce]
+
+qui count
+local nbobs=r(N)
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+local modcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local modcont (`modcont'->T)
+}
+
+local modcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local modcat (`modcat'->T)
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0 {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ local modamax``i''=r(max)
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax``i'''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax``i''' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local code `code' `code`k''
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ local t=1
+ local constraints
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax``i''' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ constraint `t' [`k'.``i'']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+
+if "`rsm'"!="" {
+ local t=1
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ constraint `t' [`=`k'-1'.``i'']_cons-[`k'.``i'']_cons+[1.``i'']_cons=[`=`k'-1'.`1']_cons-[`k'.`1']_cons+[1.`1']_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')"
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent',latent se(`selatent')
+if "`genlt'"!="" {
+ gen `genlt'=`latent'
+ gen se`genlt'=`selatent'
+}
+set seed 123456
+qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+qui genscore `varlist',score(`score')
+qui gengroup `latent',newvariable(`group') continuous
+qui levelsof `group'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'==`g'
+ qui count if ``i''!=.&`group'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i'' if `group'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent' if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+qui count if `score'!=.
+local nbobsssmd=r(N)
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i'':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i'':_cons]
+ qui lincom -_b[1.``i'':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i'':_cons]^2
+ local rn `rn' 1.``i''
+ local ++t
+ local sum _b[1.``i'':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax``i''' {
+ local sum "_b[`k'.``i'':_cons]-(`sum')"
+ di "``i'' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i'':_cons]-_b[`k'.``i'':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1':_cons]-_b[`k'.`1':_cons]+_b[1.`1':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES ET LA VARIANCE
+*************************************************************************************************************/
+
+tempname covariates
+qui matrix `covariates'=J(`=`nbpar'+1',6,.)
+
+*set trace on
+if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T)]
+}
+else {
+ qui lincom _b[/var(T)]
+}
+qui matrix `covariates'[1,1]=`r(estimate)'
+qui matrix `covariates'[1,2]=`r(se)'
+qui matrix `covariates'[1,3]=`r(z)'
+qui matrix `covariates'[1,4]=`r(p)'
+qui matrix `covariates'[1,5]=`r(lb)'
+qui matrix `covariates'[1,6]=`r(ub)'
+
+local t=2
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+* matrix list `covariates'
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax``i''' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local n: word count Variance `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of Variance `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ local ++t
+ }
+ di as text "{hline 73}"
+ di
+ qui su `latent'
+ qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])^2)
+ di as text "PSI:" as result %4.2f `PSI'
+ di
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+tempname fit
+qui matrix `fit'=J(`nbitems',4,.)
+matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+matrix rownames `fit'=`varlist'
+*matrix list `fit'
+
+tempvar Tcum TInf cum
+qui gen `Tcum'=0
+qui gen `TInf'=0
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+}
+*set trace on
+local chi2=0
+local chi2_old=0
+forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+}
+forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving(`dirsave'//residuals_``i'',replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+}
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+}
+if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+}
+
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+
+if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving(`dirsave'//CCC_``i'',replace)
+ local fsi saving(`dirsave'//ICC_``i'',replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving(`dirsave'//TCC,replace)
+ local fsteo saving(`dirsave'//TCCeo,replace)
+ local fsi saving(`dirsave'//ICC,replace)
+ local fsti saving(`dirsave'//TIC,replace)
+ local fsm saving(`dirsave'//map,replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil' {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+
+di
+di as text "{hline 57}"
+di _col(31) "Latent Variable" _col(50) "Expected"
+di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+di as text "{hline 57}"
+*set trace on
+forvalues g=1/`nbgroups' {
+ qui count if `group'==`g'
+ local eff`g'=r(N)
+ qui count if `score'!=.&`group'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score' if `group'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'==`g'&`score'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'==`g'&`score'==.
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+}
+
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export `dirsave'//`i'.`extension', replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save `dirsave'//`i', replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image `dirsave'//`i'.png, height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save `dirsave'//`j'_``i'', replace
+
+ if "`extension'"!="" {
+ qui graph export `dirsave'//`j'_``i''.`extension', replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image `dirsave'//`j'_``i''.png , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save `dirsave'//`docx'.docx, replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm3.ado b/Modules/ado/personal/p/pcm3.ado
new file mode 100644
index 0000000..5b7849d
--- /dev/null
+++ b/Modules/ado/personal/p/pcm3.ado
@@ -0,0 +1,1005 @@
+*! Version 3.5 16September2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : September 16th, 2019 [Jean-Benoit Hardouin] : Correction of bugs
+*
+*
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm3, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(name) GENINF(name) postpce]
+
+qui count
+local nbobs=r(N)
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+local modcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local modcont (`modcont'->T)
+}
+
+local modcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local modcat (`modcat'->T)
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0 {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ local modamax``i''=r(max)
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax``i'''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax``i''' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T@`k')
+ local code `code' `code`k''
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ local t=1
+ local constraints
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax``i''' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ constraint `t' [`k'.``i'']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+}
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+
+if "`rsm'"!="" {
+ local t=1
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ constraint `t' [`=`k'-1'.``i'']_cons-[`k'.``i'']_cons+[1.``i'']_cons=[`=`k'-1'.`1']_cons-[`k'.`1']_cons+[1.`1']_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')"
+local qui qui
+if "`model'"!="" {
+ local qui
+}
+`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints')
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent',latent se(`selatent')
+if "`genlt'"!="" {
+ gen `genlt'=`latent'
+ gen se`genlt'=`selatent'
+}
+set seed 123456
+qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+qui genscore `varlist',score(`score')
+qui gengroup `latent',newvariable(`group') continuous
+qui levelsof `group'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ *tab ``i'' if `group'==`g'
+ qui count if ``i''!=.&`group'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i'' if `group'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent' if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+*matrix list `groups'
+
+qui count if `score'!=.
+local nbobsssmd=r(N)
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i'':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i'':_cons]
+ qui lincom -_b[1.``i'':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=_se[1.``i'':_cons]^2
+ local rn `rn' 1.``i''
+ local ++t
+ local sum _b[1.``i'':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax``i''' {
+ local sum "_b[`k'.``i'':_cons]-(`sum')"
+ di "``i'' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i'':_cons]-_b[`k'.``i'':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1':_cons]-_b[`k'.`1':_cons]+_b[1.`1':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES ET LA VARIANCE
+*************************************************************************************************************/
+
+tempname covariates
+qui matrix `covariates'=J(`=`nbpar'+1',6,.)
+
+*set trace on
+if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T)]
+}
+else {
+ qui lincom _b[/var(T)]
+}
+qui matrix `covariates'[1,1]=`r(estimate)'
+qui matrix `covariates'[1,2]=`r(se)'
+qui matrix `covariates'[1,3]=`r(z)'
+qui matrix `covariates'[1,4]=`r(p)'
+qui matrix `covariates'[1,5]=`r(lb)'
+qui matrix `covariates'[1,6]=`r(ub)'
+
+local t=2
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+* matrix list `covariates'
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax``i''' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local n: word count Variance `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of Variance `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 73}"
+ /*
+ di
+ qui su `latent'
+ qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])^2)
+ di as text "PSI:" as result %4.2f `PSI'
+ di
+ */
+
+ di
+ qui su `latent'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `=(`r(mean)')'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`r(mean)'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`r(mean)'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+
+tempname fit
+qui matrix `fit'=J(`nbitems',4,.)
+matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+matrix rownames `fit'=`varlist'
+*matrix list `fit'
+
+tempvar Tcum TInf cum
+qui gen `Tcum'=0
+qui gen `TInf'=0
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+}
+*set trace on
+local chi2=0
+local chi2_old=0
+forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+}
+forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *di "chi2_`g'_``i''=`chi2'+(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+}
+if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+}
+if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+}
+
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+
+if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ qui clear
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax``i'''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+*set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui clear
+ qui use `savefile'
+
+}
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+
+di
+di as text "{hline 57}"
+di _col(31) "Latent Variable" _col(50) "Expected"
+di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+di as text "{hline 57}"
+*set trace on
+forvalues g=1/`nbgroups' {
+ qui count if `group'==`g'
+ local eff`g'=r(N)
+ qui count if `score'!=.&`group'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score' if `group'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'==`g'&`score'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ }
+ }
+ qui count if `group'==`g'&`score'==.
+ local eff=r(N)
+ qui su `latent' if `group'==`g'&`score'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'==`g'&`score'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'==`g'&`score'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+}
+
+
+
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm44.ado b/Modules/ado/personal/p/pcm44.ado
new file mode 100644
index 0000000..982c0b1
--- /dev/null
+++ b/Modules/ado/personal/p/pcm44.ado
@@ -0,0 +1,1517 @@
+*! Version 4.4 29September2021
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 4.4: September 29th, 2021 [Myriam Blanchin] : Correction of a bug in longitudinal option
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019 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 pcm44, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) EQGraph minsize(int 30)]
+
+preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' se`genlt' `geninf'
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', se`genlt' and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui drop `genlt' se`genlt' `geninf'
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivisit=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'`i'
+ qui gen se`genlt'=`selatent'`i'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t'
+ qui gen se`genlt'`t'=`selatent'`t'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit',score(`score')
+ qui gengroup `latent',newvariable(`group') continuous minsize(`minsize')
+}
+
+/*time 1 only*/
+qui levelsof `group'`multivisit'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+3',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 73}"
+ di as text _col(60) "<--95% IC -->"
+ di "Items" _col(60) "Lower" _col(68) "Upper"
+ di "parameters" _col(13) "category" _col(25) "Estimate" _col(37) "s.e." _col(48) "z" _col(56) "p" _col(59) " Bound" _col(68) "Bound"
+ di "{hline 73}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(28) %5.2f `diff'[`t',1] _col(36) %5.2f `diff'[`t',2] _col(44) %5.2f `diff'[`t',3] _col(52) %5.2f `diff'[`t',4] _col(60) %5.2f `diff'[`t',5] _col(68) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 73}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(20) %5.2f "`j'" as result _col(28) %5.2f `covariates'[`t',1] _col(36) %5.2f `covariates'[`t',2] _col(44) %5.2f `covariates'[`t',3] _col(52) %5.2f `covariates'[`t',4] _col(60) %5.2f `covariates'[`t',5] _col(68) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 73}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `=(`r(mean)')'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`r(mean)'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`r(mean)'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di abbrev("``i''",19) _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+if "`visit'"==""{
+ if "`graphs'"!="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+
+ qui set obs 2000
+ qui gen u=(_n-1000)/250
+ qui gen Tcum=0
+ qui gen TInf=0
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+
+ local scatteri
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ }
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+
+
+
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ qui su u if eff!=0
+ *set trace on
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local y=-`i'*`effmax'/`nbitems'
+ forvalues l=1/`modamax' {
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local scatteri `scatteri' || scatteri `y' `floor' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=ceil(`r(max)')
+ qui drop if u<`floor'|u>`ceil'
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(`floor'(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatteri' , name(map,replace) ytitle("Frequencies") ylabel(-`maxi'(`=`maxi'/5')`maxi' ,axis(2)) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait") xtitle("Latent trait") `fsm'
+
+
+ qui use `savefile', clear
+
+ }
+}
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+ *set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 57}"
+ di _col(31) "Latent Variable" _col(50) "Expected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score"
+ di as text "{hline 57}"
+ forvalues g=1/`nbgroups' {
+ qui count if `group'`multivisit'==`g'
+ local eff`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+ }
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local eff=r(N)
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local mean=r(mean)
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ di as text "{hline 57}"
+ }
+ *matrix list `matscorelt'
+}
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+*set trace on
+if "`eqset1'"!="" {
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ *di "set1 (`nbset1') : `eq1_`i''"
+ }
+ *di "`eqset1'"
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ *di "`eqset2'"
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ *di "set2 (`nbset2') : `eq2_`i''"
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ *di "`eq`t'_`i''"
+ *local tmp=""
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ *set trace on
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ *matrix list `diffmat'
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ *matrix list `diffset1'
+ *matrix list `diffset2'
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ *qui gen selt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ *di "matscorelt`t':"
+ *matrix list `matscorelt`t''
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ *qui replace selt=`matscorelt`t''[`=`i'+1',3] if scoreset`t'==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ *list
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ forvalues t=1/2 {
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ *matrix list `matscore`t''
+ di
+ di "{hline 78}"
+ di "EQUATING SET`t' TO SET`=3-`t''"
+ di "{hline 78}"
+ di "Set`t' : `eqset`t''"
+ di "Set`=3-`t'' : `eqset`=3-`t'''"
+ di "{hline 78}"
+ di _col(20) "<----- Latent trait ----->" _col(52) "<------- Score `=3-`t'' --------->"
+ di "Score`t'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ di %4.0f `matscore`t''[`=`s'+1',1] _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `matscore`t''[`=`s'+1',5] _col(66) "[" %5.2f `matscore`t''[`=`s'+1',6] ";" %5.2f `matscore`t''[`=`s'+1',7] "]"
+ }
+ di "{hline 78}"
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ if "`eqgraph'"!="" {
+ *twoway (line lt scoreset1) (line lt scoreset2), name(eq1)
+ *twoway (line scoreset1 scoreset2 lt) , name(eq2)
+ *twoway (line score1 scoreset1m scoreset1p score2), name(eq3)
+ *twoway (line score2 scoreset2m scoreset2p score1), name(eq4)
+ twoway (line score`t' score`=3-`t'' if scoreset`=3-`t''!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''m!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''p!=.), title("Equating score of the Set `t' from the Set `=3-`t''") ytitle("Score `t'") xtitle("Score `=3-`t''") ylabel(0(1)`scoremaxset`t'') xlabel(0(1)`scoremaxset`=3-`t''') name(eq`t'to`=3-`t'')
+ *twoway (line score2 score1 if scoreset1!=.) (line score2 score1 if scoreset1m!=.) (line score2 score1 if scoreset1p!=.), name(eq6)
+ }
+ }
+ *save prout, replace
+ *clear
+
+ qui use `fileeq',clear
+}
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ keep `latent'* `selatent'* `id'
+ qui reshape long `latent' `selatent', i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ *su
+ if "`replace'"!=""&("`genlt'"!=""|"`genfit'"!="") {
+ capture drop `genlt' se`genlt' `geninf'
+ }
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' `visit' using `sauv'
+ qui drop _merge
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+if "`visit'"==""{
+ return matrix matscorelt=`matscorelt'
+}
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcm5.ado b/Modules/ado/personal/p/pcm5.ado
new file mode 100644
index 0000000..44248b6
--- /dev/null
+++ b/Modules/ado/personal/p/pcm5.ado
@@ -0,0 +1,1771 @@
+*! Version 5 2August2022
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007 [Jean-Benoit Hardouin]
+* Version 2 : July 15, 2011 [Jean-Benoit Hardouin]
+* Version 2.1 : October 18th, 2011 [Jean-Benoit Hardouin] : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 [Jean-Benoit Hardouin] : correction of -fixedvar- option
+* Version 3 : July 6th, 2019 [Jean-Benoit Hardouin] : New version using gsem
+* Version 3.1 : July 9th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.2 : July 17th, 2019 [Jean-Benoit Hardouin] : Small corrections
+* Version 3.3 : July 25th, 2019 [Jean-Benoit Hardouin] : -pce- option
+* Version 3.4 : August 23th, 2019 [Jean-Benoit Hardouin] : Correction of a bug
+* Version 3.5 : August 29th, 2019 [Jean-Benoit Hardouin] : Correction of a bug with modamax``i''
+* Version 4: September 13th, 2019 [Myriam Blanchin]: addition of longitudinal pcm
+* Version 4.1: September 15th, 2019 [Jean-Benoit Hardouin]: correction of a small bug in the outputs
+* Version 4.2: September 27th, 2019 [Jean-Benoit Hardouin] : EQUATING
+* Version 4.3: November 8th, 2019 [Jean-Benoit Hardouin] : add a constant when difficulty parameters are fixed
+* Version 5: August 2nd, 2022 [Jean-Benoit Hardouin] : New MAP graph, corrected estimation of the latent trait
+*
+*
+* Jean-benoit Hardouin, Myriam Blanchin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr, myriam.blanchin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2007, 2011, 2013, 2014, 2019, 2022 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 pcm, rclass
+syntax varlist(min=2 numeric) [iweight] [, CONTinuous(varlist) CATegorical(varlist) ITerate(int 100) TOLerance(real 0.01) model DIFFiculties(name) VARiance(real -1) rsm Graphs noGRAPHItems filesave dirsave(string) docx(string) extension(string) PCE WMLiterate(int 1) GENLT(string) GENINF(string) REPlace postpce visit(varname) id(varname) eqset1(varlist) eqset2(varlist) EQGraph minsize(int 30)]
+
+preserve
+
+/*************************************************************************************************************
+QUELQUES TESTS
+*************************************************************************************************************/
+
+if `variance'!=-1&`variance'<=0 {
+ di in red "The -variance- option cannot be negative"
+ exit 198
+}
+if `variance'!=-1&"`visit'"!="" {
+ di in red "The -variance- and -visit- options cannot be used simultaneously."*
+ exit 198
+}
+if "`genlt'"!=""|"`geninf'"!="" {
+ capture confirm new variable `genlt' `genlt'_se `geninf' `genlt'_corr `genlt'_opt `genlt'_opt_se
+ if _rc!=0&"`replace'"=="" {
+ di in red "The variables `genlt', `genlt'_se, `genlt'_corr, `genlt'_opt, `genlt'_opt_se and/or `geninf' alreday exist. Please modify the -genlt- and/or -geninf- option"
+ exit 198
+ }
+ if _rc!=0&"`replace'"!="" {
+ qui capture drop `genlt'
+ qui capture drop `genlt'_se
+ qui capture drop `geninf'
+ qui capture drop `genlt'_corr
+ qui capture drop `genlt'_opt
+ qui capture drop `genlt'_opt_se
+ }
+}
+if ("`eqset1'"!=""&"`eqset2'"=="")|("`eqset1'"==""&"`eqset2'"!="") {
+ di in red "The two options -eqset1- and -eqset2- must be used simultaneously"
+ exit 198
+}
+if ("`eqset1'"!=""&"`graphs'"!="") {
+ di in red "The two options -eqset1- and -graph- cannot be used simultaneously"
+ exit 198
+}
+
+
+
+
+/*************************************************************************************************************
+GESTION DES VARIABLES CONTINUES ET CATEGORIELLES
+*************************************************************************************************************/
+if "`visit'"!=""{
+ if "`id'"==""{
+ di in red "Option -visit- must be combined with option -id-. Please fill in the -id- option"
+ exit 198
+ }
+ qui levelsof `visit'
+ local levelsofv `r(levels)'
+ local nbvisits=r(r)
+ local timemin: word 1 of `levelsofv'
+ local timemax: word `nbvisits' of `levelsofv'
+ if `timemax'>5{
+ di as error "You must use a discrete time variable (-visit- option) with less than 5 measurement occasions"
+ error 198
+ }
+ if `timemin'!=1{
+ di as error "You must use a -visit- variable coded at 1 for the first visit"
+ error 198
+ }
+ qui reshape wide `varlist', i(`id') j(`visit')
+ local multivist=1
+}
+else {
+ local timemax=1
+ foreach i in `varlist' {
+ *rename `i' `i'1
+ }
+ local multivisit
+}
+qui count
+local nbobs=r(N)
+
+local timelist
+forvalues t=1/`timemax'{
+ local timelist `timelist' T`t'
+}
+
+local modcont
+local premodcont
+local nbpar=0
+local nbcont=0
+local nbcat=0
+if "`continuous'"!="" {
+ tokenize `continuous'
+ local nbcont : word count `continuous'
+ local continuous
+ forvalues i=1/`nbcont' {
+ local cont`i' ``i''
+ local continuous `continuous' ``i''
+ local modcont `modcont' ``i''
+ local ++nbpar
+ }
+ local premodcont (`modcont'->T1)
+ local modcont (`modcont'->`timelist')
+}
+
+local modcat
+local premodcat
+if "`categorical'"!="" {
+ tokenize `categorical'
+ local nbcat : word count `categorical'
+ local categorical
+ forvalues i=1/`nbcat' {
+ local cat`i' ``i''
+ local categorical `categorical' ``i''
+ local modcat `modcat' i.``i''
+ qui levelsof ``i''
+ local levelsof``i'' `r(levels)'
+ local nbpar=`nbpar'+`r(r)'-1
+ *di "categorical : ``i'' levels : `levelsof``i'''"
+ }
+ local premodcat (`modcat'->T1)
+ local modcat (`modcat'->`timelist')
+}
+
+
+if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+}
+
+/*************************************************************************************************************
+GESTION DES ITEMS ET TESTS
+*************************************************************************************************************/
+
+tokenize `varlist'
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+*preserve
+
+local modamax=1
+local modamin=0
+local pbmin
+local nbdiff=0
+local scoremax=0
+forvalues i=1/`nbitems' {
+ local modamax`i'=1
+ local modamax``i''=1
+ if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ *qui replace ``i'`t''=``i'`t''-`min'
+ qui su ``i''`t'
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i'`t''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ }
+ }
+ }
+ else {
+ qui su ``i''
+ if `r(min)'!=`modamin' {
+ local modamin=r(min)
+ local pbmin `pbmin' ``i''
+ }
+ if `r(max)'>`modamax' {
+ local modamax=r(max)
+ }
+ if `r(max)'>`modamax`i'' {
+ local modamax`i'=r(max)
+ local modamax``i''=r(max)
+ }
+ }
+ *di "local scoremax=`scoremax'+`modamax`i''"
+ local scoremax=`scoremax'+`modamax`i''
+ if "`rsm'"=="" {
+ local nbdiff=`nbdiff'+`modamax`i''
+ }
+}
+if "`rsm'"!="" {
+ local nbdiff=`nbitems'+`modamax'-1
+}
+if `modamin'!=0 {
+ di as error "The minimal answer category of each item must be coded by 0. This is not the case for the following items: `pbmin' (`modamin') "
+ error 198
+}
+qui count
+local nbind=r(N)
+*set trace on
+local code
+local precode
+if `timemax'>1 {
+ forvalues k=1/`modamax' {
+ forvalues t=1/`timemax'{
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''`t'
+ }
+ }
+ local code`k' (`code`k''<-T`t'@`k')
+ if `t'==1{
+ local precode `precode' `code`k''
+ }
+ local code `code' `code`k''
+ }
+ }
+}
+else {
+ forvalues k=1/`modamax' {
+ local code`k'
+ forvalues i=1/`nbitems' {
+ if `k'<=`modamax`i'' {
+ local code`k' `code`k'' `k'.``i''
+ }
+ }
+ local code`k' (`code`k''<-T1@`k')
+ local precode `precode' `code`k''
+ local code `code' `code`k''
+ }
+}
+
+/*************************************************************************************************************
+OPTION PCE
+*************************************************************************************************************/
+
+if "`pce'"!=""&"`difficulties'"==""&"`visit'"=="" {
+ tempname sedelta b
+ qui raschpce `varlist'
+ local ll=r(ll)
+ matrix `sedelta'=r(sedelta)
+ matrix `sedelta'=`sedelta''
+ matrix `b'=r(b)
+ *matrix `b'=`b''
+ local difficulties `b'
+ *matrix list `b'
+ matrix loulou=`b'
+ return matrix diff_parm=`b'
+ `qui' pcm `varlist', diff(loulou) geninf(TInf_0) genlt(lt_0) /*postpce*/
+ *exit
+}
+
+
+/*************************************************************************************************************
+RECUPERATION DES PARAMETRES DE DIFFICULTES ET DEFINITION DES CONTRAINTES
+*************************************************************************************************************/
+if "`difficulties'"!=""&"`rsm'"!="" {
+ di as error "You can not defined in the same time the difficulties and the rsm options"
+ error 198
+}
+local t=1
+local constraints
+local codemean
+local codevar
+local codecov
+forvalues j=2/`timemax'{
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ qui constraint `t' [`k'.``i''`j']_cons=[`k'.``i''`multivisit']_cons
+ local constraints `constraints' `t'
+ local ++t
+
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codemean `codemean' T`j'@m`j'
+ local codevar `codevar' T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' T`l'*T`j'@cov`l'`j'
+ }
+ }
+ else{
+ local codevar `codevar' e.T`j'@v`j'
+ forvalues l=1/`=`j'-1'{
+ local codecov `codecov' e.T`l'*e.T`j'@cov`l'`j'
+ }
+ }
+}
+if `timemax'>1{
+ if "`continuous'"=="" & "`categorical'"==""{
+ local codelg means(T1@0 `codemean') var(T1@v1 `codevar') cov(`codecov')
+ }
+ else{
+ local codelg var(e.T1@v1 `codevar') cov(`codecov')
+ }
+}
+else {
+ local constrvar
+ if `variance'>0 {
+ if "`continuous'"=="" & "`categorical'"==""{
+ local constrvar var(T1@`variance')
+ }
+ else{
+ *local constrvar var(e.T1@`variance')
+ }
+ }
+}
+
+local fixedmean
+if "`difficulties'"!="" {
+ tempname beta
+ matrix `beta'=J(`nbitems',`modamax',.)
+ matrix list `difficulties'
+ forvalues i=1/`nbitems' {
+ forvalues k=1/`modamax`i'' {
+ if `difficulties'[`i',`k']==. {
+ di as error "The kth difficulty parameter of the item ``i'' is not correctly defined in the difficulties matrix"
+ error 198
+ }
+ else {
+ if `k'==1 {
+ matrix `beta'[`i',1]=-`difficulties'[`i',1]
+ }
+ else {
+ matrix `beta'[`i',`k']=`beta'[`i',`=`k'-1']-`difficulties'[`i',`k']
+ }
+ qui constraint `t' [`k'.``i''`multivisit']_cons=`beta'[`i',`k']
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+ }
+ if "`continuous'"=="" & "`categorical'"=="" {
+ local fixedmean mean(T1)
+ }
+ else{
+ local fixedmean
+ }
+}
+
+
+
+/*************************************************************************************************************
+DEFINITION DES CONTRAINTES POUR UN RSM
+*************************************************************************************************************/
+if "`rsm'"!="" {
+ local constraints
+ forvalues k=2/`modamax' {
+ forvalues i=2/`nbitems' {
+ qui constraint `t' [`=`k'-1'.``i''`multivisit']_cons-[`k'.``i''`multivisit']_cons+[1.``i''`multivisit']_cons=[`=`k'-1'.`1'1]_cons-[`k'.`1'1]_cons+[1.`1'1]_cons
+ local constraints `constraints' `t'
+ local ++t
+ }
+ }
+}
+
+/*************************************************************************************************************
+MODELE
+*************************************************************************************************************/
+
+
+discard
+*di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' "
+if "`model'"!="" {
+ local qui
+}
+else {
+ local qui qui
+}
+if `timemax'==1{
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+ *qui gen un=1
+ *`qui' gsem `code' (i.group un->T) ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `constrvar' `fixedmean'
+}
+else{
+ di "`qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') "
+ `qui' gsem `precode' `premodcont' `premodcat',iterate(`iterate') tol(`tolerance') constraint(`constraints')
+ matrix esti_B = e(b)
+ di "`qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)"
+ `qui' gsem `code' `modcont' `modcat' ,iterate(`iterate') tol(`tolerance') constraint(`constraints') latent(`timelist') `codelg' from(esti_B,skip)
+}
+local ll=e(ll)
+
+*set trace on
+tempvar latent score group selatent latent2 miss
+tempname groups
+*capture qui predict mu, mu
+*su mu
+qui predict `latent'*,latent se(`selatent'*)
+
+if "`genlt'"!="" {
+ if `timemax'==1 {
+ qui gen `genlt'=`latent'`i'
+ qui gen `genlt'_se=`selatent'`i'
+ }
+ forvalues t=2/`timemax' {
+ qui gen `genlt'`t'=`latent'`t'
+ qui gen `genlt'`t'_se=`selatent'`t'
+ }
+}
+
+set seed 123456
+if `timemax'>1 {
+ forvalues t=1/`timemax'{
+ qui gen `latent2'`t'=`latent'`t'+invnorm(uniform())*`selatent'`t'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''`t'
+ }
+ qui genscore `listit',score(`score'`t')
+ qui gengroup `latent'`t',newvariable(`group'`t') continuous minsize(`minsize')
+ }
+}
+else {
+ qui gen `latent2'=`latent'+invnorm(uniform())*`selatent'
+ local listit
+ forvalues i=1/`nbitems' {
+ local listit `listit' ``i''
+ }
+ qui genscore `listit',score(`score')
+ qui gengroup `latent',newvariable(`group') continuous minsize(`minsize')
+}
+forvalues s=0/`scoremax' {
+ qui count if `score'==`s'
+ local effscore`s'=r(N)
+}
+
+
+/*time 1 only*/
+qui levelsof `group'`multivisit'
+local nbgroups=r(r)
+matrix `groups'=J(`nbgroups',`=`nbitems'+6',.)
+forvalues g=1/`nbgroups' {
+ matrix `groups'[`g',`=`nbitems'+3']=0
+ qui count if `group'`multivisit'==`g'
+ local effgroup`g'=r(N)
+ forvalues i=1/`nbitems' {
+ qui count if ``i''`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ if `n'>0 {
+ qui su ``i''`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`i']=r(mean)
+ matrix `groups'[`g',`=`nbitems'+3']=`groups'[`g',`=`nbitems'+3']+`r(mean)'
+ }
+ else {
+ matrix `groups'[`g',`i']=.
+ matrix `groups'[`g',`=`nbitems'+3']=.
+ }
+ }
+ qui su `latent'`multivisit' if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+1']=r(mean)
+ qui count if `group'`multivisit'==`g'
+ matrix `groups'[`g',`=`nbitems'+2']=r(N)
+ qui su `score' if `group'`multivisit'==`g'&`score'!=.
+ matrix `groups'[`g',`=`nbitems'+4']=r(min)
+ matrix `groups'[`g',`=`nbitems'+5']=r(max)
+}
+
+/*number of non-missing on all time points*/
+egen `miss'=rowmiss(`score'*)
+qui count if `miss'==0
+local nbobsssmd=r(N)
+drop `miss'
+
+di
+di as text "Number of individuals:" %6.0f as result `nbobs'
+di as text "Number of complete individuals:" %6.0f as result `nbobsssmd'
+di as text "Number of items:" %6.0f as result `nbitems'
+
+di as text "Marginal log-likelihood:" %12.4f as result `ll'
+di
+return scalar ll=`ll'
+
+
+
+*set trace on
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES DE DIFFICULTE
+*************************************************************************************************************/
+
+tempname diff diffmat vardiff diffmat2
+*set trace on
+qui matrix `diffmat'=J(`nbitems',`modamax',.)
+qui matrix `diffmat2'=J(`nbitems',`modamax',.)
+qui matrix `diff'=J(`nbdiff',6,.)
+local rn
+*qui matrix `vardiff'=J(`nbdiff',`nbdiff',.)
+*matrix list `diff'
+*set trace on
+local t=1
+forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui matrix `diffmat2'[`i',1]=-_b[1.``i''`multivisit':_cons]
+ qui lincom -_b[1.``i''`multivisit':_cons]
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ local rn `rn' 1.``i''`multivisit'
+ local ++t
+ local sum _b[1.``i''`multivisit':_cons]
+ if "`rsm'"=="" {
+ forvalues k=2/`modamax`i'' {
+ local sum "_b[`k'.``i''`multivisit':_cons]-(`sum')"
+ *di "``i''`multivisit' `k' `sum'"
+ local sum2 "_b[`=`k'-1'.``i''`multivisit':_cons]-_b[`k'.``i''`multivisit':_cons]"
+ qui lincom (`sum2')
+ *set trace on
+ qui matrix `diffmat'[`i',`k']=`r(estimate)'
+ qui matrix `diffmat2'[`i',`k']=`diffmat2'[`i',`=`k'-1']+`diffmat'[`i',`k']
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ *qui matrix `vardiff'[`t',`t']=`r(se)'^2
+ *set trace off
+ local rn `rn' `k'.``i''`multivisit'
+ local ++t
+ }
+ }
+}
+if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ qui lincom _b[`=`k'-1'.`1'`multivisit':_cons]-_b[`k'.`1'`multivisit':_cons]+_b[1.`1'`multivisit':_cons] /*``i'' instead of `i'?*/
+ qui matrix `diff'[`t',1]=`r(estimate)'
+ qui matrix `diff'[`t',2]=`r(se)'
+ qui matrix `diff'[`t',3]=`r(z)'
+ qui matrix `diff'[`t',4]=`r(p)'
+ qui matrix `diff'[`t',5]=`r(lb)'
+ qui matrix `diff'[`t',6]=`r(ub)'
+ forvalues i=1/`nbitems' {
+ qui matrix `diffmat'[`i',`k']=`diff'[`t',1]+`diffmat'[`i',1]
+ qui matrix `diffmat2'[`i',`k']=`diffmat'[`i',`k']+`diffmat2'[`i',`=`k'-1']
+ }
+ local rn `rn' tau`k'
+ local ++t
+ }
+}
+local cn Estimate S.e. z p "Lower bound" "Upper Bound"
+matrix colnames `diff'=`cn'
+matrix rownames `diff'=`rn'
+*matrix list `diff'
+*matrix list `diffmat'
+*matrix list `diffmat2'
+*matrix list `vardiff'
+
+/*************************************************************************************************************
+RECUPERATION DES ESTIMATIONS DES PARAMETRES POUR LES COVARIABLES, MOYENNES ET VARIANCES
+*************************************************************************************************************/
+tempname covariates
+local nbcov=0
+forvalues j=2/`timemax'{
+ local nbcov=`nbcov'+`j'-1
+}
+qui matrix `covariates'=J(`=`nbpar'+`timemax'+2*`nbcov'',6,.)
+
+*set trace on
+local t=1
+
+
+forvalues j=1/`=`timemax'-1'{
+ forvalues k=`=`j'+1'/`timemax'{
+ if "`categorical'"=="" & "`continuous'"=="" {
+ if `j'==1{
+ qui lincom [/]mean(T`k')
+ }
+ else{
+ qui lincom [/]mean(T`k')-[/]mean(T`j')
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ else{
+ if "`categorical'"!=""{
+ local first=0
+ foreach l in `levelsof`cat1'' {
+ if `first'==0 {
+ local ++first
+ }
+ else{
+ if `first'==1 {
+ qui lincom [T`k']`l'.`cat1'-[T`j']`l'.`cat1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ local ++first
+ }
+ }
+ }
+ }
+ else{
+ qui lincom [T`k']`cont1'-[T`j']`cont1'
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ }
+}
+
+forvalues j=1/`timemax'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ qui lincom _b[/var(e.T`j')]
+ }
+ else {
+ qui lincom _b[/var(T`j')]
+ }
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues j=1/`=`timemax'-1'{
+ if "`continuous'"!=""|"`categorical'"!="" {
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(e.T`j',e.T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+ else{
+ forvalues k=`=`j'+1'/`timemax'{
+ qui lincom _b[/cov(T`j',T`k')]
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+forvalues i=1/ `nbcont' {
+ qui lincom `cont`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+}
+forvalues i=1/ `nbcat' {
+ local first=0
+ foreach j in `levelsof`cat`i''' {
+ if `first'==0 {
+ local ++first
+ }
+ else {
+ qui lincom `j'.`cat`i''
+ qui matrix `covariates'[`t',1]=`r(estimate)'
+ qui matrix `covariates'[`t',2]=`r(se)'
+ qui matrix `covariates'[`t',3]=`r(z)'
+ qui matrix `covariates'[`t',4]=`r(p)'
+ qui matrix `covariates'[`t',5]=`r(lb)'
+ qui matrix `covariates'[`t',6]=`r(ub)'
+ local ++t
+ }
+ }
+}
+*matrix list `covariates'
+
+
+/*************************************************************************************************************
+OUTPUTS
+*************************************************************************************************************/
+
+if "`postpce'"=="" {
+ local t=1
+ local diffname
+ *set trace on
+ di "{hline 83}"
+ di as text _col(70) "<--95% IC -->"
+ di _col(70) "Lower" _col(78) "Upper"
+ di "Items" _col(22) "Threshold" _col(35) "Estimate" _col(47) "s.e." _col(58) "z" _col(66) "p" _col(69) " Bound" _col(78) "Bound"
+ di "{hline 83}"
+ *set trace on
+ forvalues i=1/`nbitems' {
+ *local l=1
+ forvalues j=1/`modamax`i'' {
+ if "`rsm'"==""|`j'==1 {
+ if `j'==1 {
+ di as text abbrev("``i''",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local ++t
+ *local ++l
+ local diffname `diffname' `j'.``i''
+ }
+ }
+ }
+ if "`rsm'"!="" {
+ forvalues k=2/`modamax' {
+ di as text "tau`k'" as result _col(38) %5.2f `diff'[`t',1] _col(46) %5.2f `diff'[`t',2] _col(54) %5.2f `diff'[`t',3] _col(62) %5.2f `diff'[`t',4] _col(70) %5.2f `diff'[`t',5] _col(78) %5.2f `diff'[`t',6]
+ local diffname `diffname' tau`k'
+ local ++t
+ }
+ }
+ di as text "{hline 83}"
+ local t=1
+ local listmoy
+ local listvar
+ local listcov
+ forvalues j=1/`timemax'{
+ local listvar `listvar' Variance_T`j'
+ forvalues k=`=`j'+1'/`timemax'{
+ local listcov `listcov' Cov_T`j'_T`k'
+ }
+ forvalues k=`=`j'+1'/`timemax'{
+ local listmoy `listmoy' Mean_diff_T`j'_T`k'
+ }
+ }
+ local n: word count `listmoy' `listvar' `listcov' `continuous'
+ forvalues i=1/`n' {
+ local v: word `i' of `listmoy' `listvar' `listcov' `continuous'
+ di as text _col(1) %5.2f "`v'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++t
+ }
+
+ local rn Variance `continuous'
+
+ local n: word count of `categorical'
+ local catname
+ forvalues i=1/`n' {
+ local v: word `i' of `categorical'
+ local first=1
+ local saute=1
+ foreach j in `levelsof`cat`i''' {
+ if `saute'==0 {
+ if `first'==1 {
+ di as text _col(1) abbrev("`v'",19) _c
+ }
+ di as text _col(30) %5.2f "`j'" as result _col(38) %5.2f `covariates'[`t',1] _col(46) %5.2f `covariates'[`t',2] _col(54) %5.2f `covariates'[`t',3] _col(62) %5.2f `covariates'[`t',4] _col(70) %5.2f `covariates'[`t',5] _col(78) %5.2f `covariates'[`t',6]
+ local ++first
+ local rn `rn' `j'.`n'
+ local ++t
+ local catname `catname' `j'.`v'
+ }
+ else {
+ local saute=0
+ }
+ }
+ *local ++t
+ }
+ di as text "{hline 83}"
+ if "`visit'"==""{
+ di
+ qui su `latent'
+ *qui local PSI=1-(`r(sd)')^2/((`covariates'[1,1])+(`r(sd)')^2)
+ *di as text "Variance of the estimated latent variable: " as result %4.2f `=(`r(sd)')^2'
+ tempvar se2latent
+ qui gen `se2latent'=(`selatent')^2
+ qui su `se2latent'
+ local resvar=r(mean)
+ di as text "Mean squared std error of the latent variable: " as result %4.2f `resvar'
+ di as text "Global variance of the latent variable: " as result %4.2f `=((`covariates'[1,1])+(`resvar'))'
+ local PSI=(`covariates'[1,1])/((`covariates'[1,1])+(`resvar'))
+ di as text "PSI: " as result %4.2f `PSI' _c
+ if "`continuous'"!=""|"`categorical'"!="" {
+ di as text " (without adjustment on covariates)"
+ }
+ else {
+ di
+ }
+ di
+ return scalar PSI=`PSI'
+
+ }
+
+
+
+ matrix colnames `covariates'=`cn'
+ matrix rownames `covariates'=`rn'
+}
+
+/*************************************************************************************************************
+FIT TESTS
+*************************************************************************************************************/
+if "`visit'"==""{
+ tempname fit
+ qui matrix `fit'=J(`nbitems',4,.)
+ matrix colnames `fit'=OUTFIT INFIT "Standardized OUTFIT" "Standardized INFIT"
+ matrix rownames `fit'=`varlist'
+ *matrix list `fit'
+
+ tempvar Tcum TInf cum
+ qui gen `Tcum'=0
+ qui gen `TInf'=0
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text _col(60) "<--- Standardized --->"
+ di as text "Items" _col(34) "OUTFIT" _col(50) "INFIT" _col(64) "OUTFIT" _col(80) "INFIT"
+ di as text "{hline 90}"
+ di as text "Referenced values*" _col(29) "[" %4.2f `=1-6/sqrt(`nbobs')' ";" %4.2f `=1+6/sqrt(`nbobs')' "]" _col(44) "[" %4.2f `=1-2/sqrt(`nbobs')' ";" %4.2f `=1+2/sqrt(`nbobs')' "]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "Referenced values**" _col(29) "[0.75;1.30]" _col(44) "[0.75;1.30]" _col(60) "[-2.6;2.6]" _col(75) "[-2.6;2.6]"
+ di as text "{hline 90}"
+ }
+ *set trace on
+ local chi2=0
+ local chi2_old=0
+ forvalues g=1/`nbgroups' {
+ local chi2_g`g'=0
+ local chi2_old_g`g'=0
+ }
+ forvalues i=1/`nbitems' {
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ tempvar cum_old``i'' c_old0_``i'' Inf_old``i'' y_old``i'' y2_old``i''
+ tempvar cum``i'' c0_``i'' Inf``i'' C``i'' C2``i'' C3``i'' y``i'' y2``i'' z``i'' z2``i'' i``i''
+
+ local d=1
+ local d_old=1
+ qui gen `cum``i'''=0
+ qui gen `cum_old``i'''=0
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*`latent2'-`diffmat2'[`i',`k'])
+ local d_old `d_old'+exp(`k'*`latent'-`diffmat2'[`i',`k'])
+ }
+ qui gen `c0_``i'''=1/(`d')
+ qui gen `c_old0_``i'''=1/(`d_old')
+ forvalues k=1/`mm' {
+ tempvar c`k'_``i'' c_old`k'_``i''
+ qui gen `c`k'_``i'''=exp(`k'*`latent2'-`diffmat2'[`i',`k'])/(`d')
+ qui gen `c_old`k'_``i'''=exp(`k'*`latent'-`diffmat2'[`i',`k'])/(`d')
+ qui replace `cum``i'''=`cum``i'''+`c`k'_``i'''*`k'
+ qui replace `cum_old``i'''=`cum_old``i'''+`c_old`k'_``i'''*`k'
+ }
+ qui gen `Inf``i'''=0
+ qui gen `Inf_old``i'''=0
+ qui gen `C``i'''=0
+ forvalues k=0/`mm' {
+ qui replace `Inf``i'''=`Inf``i'''+(`k'-`cum``i''')^2*`c`k'_``i'''
+ qui replace `Inf_old``i'''=`Inf_old``i'''+(`k'-`cum_old``i''')^2*`c_old`k'_``i'''
+ qui replace `C``i'''=`C``i'''+(`k'-`cum``i''')^4*`c`k'_``i'''
+ }
+ qui count if ``i''!=.
+ local n``i''=r(N)
+
+ qui gen `C2``i'''=`C``i'''/((`Inf``i''')^2)
+ qui su `C2``i'''
+ local q2o``i''=(`r(mean)'-1)/((`n``i'''))
+
+ qui gen `C3``i'''=`C``i'''-(`Inf``i''')^2
+ qui su `C3``i'''
+ local n=r(sum)
+ qui su `Inf``i'''
+ local d=r(sum)
+ local q2i``i''=`n'/((`d')^2)
+
+ //di "``i'' qo = `=sqrt(`q2o``i''')' qi = `=sqrt(`q2i``i''')'"
+
+ qui replace `Tcum'=`Tcum'+`cum``i'''
+ qui replace `TInf'=`TInf'+`Inf``i'''
+ qui gen `y``i'''=``i''-`cum``i'''
+ qui gen `y_old``i'''=``i''-`cum_old``i'''
+ qui gen `y2``i'''=(`y``i''')^2
+ qui gen `y2_old``i'''=(`y_old``i''')^2
+ qui gen `z``i'''=(`y``i'''/sqrt(`Inf``i'''))
+ local chi2_``i''=0
+ local chi2_old_``i''=0
+ forvalues g=1/`nbgroups' {
+ qui su `y2``i''' if `group'==`g'
+ local n=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1=r(sum)
+ qui su `cum``i''' if `group'==`g'
+ local n2=r(sum)
+ qui su `Inf``i''' if `group'==`g'
+ local d=r(sum)
+ *qui count if `group'==`g'
+ *local eff=r(N)
+ *di "chi2_`g'_``i''=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')"
+ local chi2=`chi2'+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_``i''=`chi2_``i'''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ local chi2_g`g'=`chi2_g`g''+/*`eff'**/(`n1'-`n2')^2/(`d')
+ qui su `y2_old``i''' if `group'==`g'
+ local n_old=r(sum)
+ qui su ``i'' if `group'==`g'
+ local n1_old=r(sum)
+ qui su `cum_old``i''' if `group'==`g'
+ local n2_old=r(sum)
+ qui su `Inf_old``i''' if `group'==`g'
+ local d_old=r(sum)
+ local chi2_old=`chi2_old'+(`n1_old'-`n2_old')^2/(`d_old')
+ local chi2_old_``i''=`chi2_old_``i'''+(`n_old')/(`d_old')
+ local chi2_old_g`g'=`chi2_old_g`g''+(`n_old')/(`d_old')
+ }
+ *di "Item ``i'' Chi2``i''=`chi2_``i''' et chi2=`chi2' Chi2_old=`chi2_old_``i''' et chi2_old=`chi2_old' "
+ *su `z``i'''
+ label variable `z``i''' "Standardized residuals associated to ``i''"
+ label variable `latent' "Latent trait"
+ *set trace on
+ if "`graphs'"!=""&"`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fs saving("`dirsave'//residuals_``i''",replace)
+ }
+ qui graph twoway scatter `z``i''' `latent', name(residuals``i'',replace) title("Standardized residuals associated to ``i''") `fs'
+ }
+ *set trace off
+ qui gen `z2``i'''=(`z``i''')^2
+ qui su `z2``i'''
+ local OUTFIT``i''=`r(mean)'
+ qui matrix `fit'[`i',1]=`OUTFIT``i'''
+ local OUTFITs``i''=((`r(mean)')^(1/3)-1)*(3/sqrt(`q2o``i'''))+sqrt(`q2o``i''')/3
+ qui matrix `fit'[`i',3]=`OUTFITs``i'''
+ qui su `Inf``i''' if ``i''!=.
+ local sumw``i''=r(sum)
+ qui gen `i``i'''=`Inf``i'''*`z2``i'''
+ qui su `i``i''' if ``i''!=.
+ local INFIT``i'' = `=`r(sum)'/`sumw``i''''
+ qui matrix `fit'[`i',2]=`INFIT``i'''
+ local INFITs``i''=(`=`r(sum)'/`sumw``i''''^(1/3)-1)*(3/sqrt(`q2i``i'''))+sqrt(`q2i``i''')/3
+ qui matrix `fit'[`i',4]=`INFITs``i'''
+ if "`postpce'"=="" {
+ di "``i''" _col(35) %5.3f `OUTFIT``i''' _col(50) %5.3f `INFIT``i''' _col(64) %6.3f `OUTFITs``i''' _col(79) %6.3f `INFITs``i'''
+ }
+ }
+ if "`postpce'"=="" {
+ di as text "{hline 90}"
+ di as text "*: As suggested by Wright (Smith, 1998)
+ di as text "**: As suggested by Bond and Fox (2007)
+ }
+ if "`geninf'"!="" {
+ gen `geninf'=`TInf'
+ }
+}
+*set trace off
+/*************************************************************************************************************
+ESTIMATION OF THE WEIGHTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+*di "estimation `wmliterate'"
+if "`postpce'"!="" {
+ local conv=10
+ local it=`wmliterate'
+ di "Iteration : `it'"
+ while(`conv'>=1) {
+ di "Itération `it' : conv=`conv'"
+ tempvar sinf
+ qui gen `sinf'=sqrt(TInf_`=`it'-1')
+ `qui' pcm `varlist' [iweight=`sinf'],diff(loulou) wmliterate(`it') geninf(TInf_`it') genlt(lt_`it')
+ tempvar ecart_`it'
+ qui gen `ecart_`it''=abs(lt_`it'-lt_`=`it'-1')
+ qui su `ecart_`it''
+ local conv =r(mean)
+ local ++it
+ }
+ exit
+}
+
+/*************************************************************************************************************
+ESTIMATION OF THE CORRECTED ML ESTIMATORS
+**************************************************************************************************************/
+*set trace on
+tempfile savefile
+qui save `savefile'
+
+qui drop _all
+
+qui set obs 2000
+qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+qui gen Tcum=0
+qui gen TInf=0
+forvalues i=1/`nbitems' {
+ local d=1
+ qui gen cum``i''=0
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ }
+ qui gen Inf``i''=0
+ forvalues k=1/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ qui replace Tcum=Tcum+cum``i''
+ qui replace TInf=TInf+Inf``i''
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ }
+ qui drop ecart
+}
+qui use `savefile', clear
+
+
+
+
+/*************************************************************************************************************
+RESULTS BY GROUP
+*************************************************************************************************************/
+if "`visit'"==""{
+*set trace on
+ tempname matscorelt
+ qui matrix `matscorelt'=J(`=`nbitems'*`modamax'+1',3,.)
+ di
+ di as text "{hline 71}"
+ di _col(32) "Latent Trait" _col(50) "Expected" _col(63) "Corrected"
+ di "Group" _col(10) "Score" _col(20) "Freq" _col(32) "Mean" _col(42) "s.e." _col(53) "Score" _col(60) "latent trait"
+ di as text "{hline 71}"
+ forvalues g=1/`nbgroups' {
+ local sumuc=0
+ local sumc=0
+ qui count if `group'`multivisit'==`g'
+ local eff`g'=r(N)
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'!=.
+ local effcompleted`g'=r(N)
+ qui count if `score'`multivisit'!=.&`group'`multivisit'==`g'
+ local n=r(N)
+ di as text "`g' (n=" as result `eff`g'' as text ")" _c
+ if `n'>0 {
+ qui su `score'`multivisit' if `group'`multivisit'==`g'
+ local scoremin`g'=`r(min)'
+ local scoremax`g'=`r(max)'
+ forvalues s=`scoremin`g''/`scoremax`g'' {
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local eff=r(N)
+ if `eff'!=0 {
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local mean=r(mean)
+ *di "local sumc=`sumc'+(`eff')*(`estlt`s'')"
+ *di "local sumuc=`sumuc'+(`eff')*(`mean')"
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ local sumc=(`sumc'+((`eff')*(`estlt`s'')))
+ }
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==`s'
+ local exp=r(mean)
+ if `eff'>0 {
+ di as text _col(10) %5.0f `s' as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp' _col(66) %6.3f `estlt`s''
+ }
+ qui matrix `matscorelt'[`=`s'+1',1]=`s'
+ qui matrix `matscorelt'[`=`s'+1',2]=`mean'
+ qui matrix `matscorelt'[`=`s'+1',3]=`se'
+ }
+
+ }
+ qui count if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local eff=r(N)
+
+ qui su `latent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local mean=r(mean)
+ local sumuc=(`sumuc'+((`eff')*(`mean')))
+ qui su `selatent' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local se=r(mean)
+ qui su `Tcum' if `group'`multivisit'==`g'&`score'`multivisit'==.
+ local exp=r(mean)
+
+ if `eff'>0 {
+ di as text _col(10) " ." as result _col(20) %4.0f `eff' _col(30) %6.3f `mean' _col(40) %6.3f `se' _col(53) %5.2f `exp'
+ }
+ *di "local lt`g'=`sumuc'/`eff`g''"
+ *di "local clt`g'=`sumc'/`eff`g''"
+ local lt`g'=(`sumuc')/(`eff`g'')
+ local clt`g'=(`sumc')/(`effcompleted`g'')
+ matrix `groups'[`g',`=`nbitems'+6']=`clt`g''
+ *di "group `g' est=`lt`g'' corrected est=`clt`g''"
+ di as text " " "{dup 62:-}"
+ di as text _col(10) "`scoremin`g''/`scoremax`g''" as result _col(20) %4.0f `eff`g'' _col(30) %6.3f `lt`g'' _col(66) %6.3f `clt`g''
+ di as text "{hline 71}"
+ }
+ *matrix list `matscorelt'
+}
+
+
+
+/*************************************************************************************************************
+Categories/Items/Test Characteristics Curves and Information graphs
+*************************************************************************************************************/
+*set trace on
+if "`visit'"==""{
+ if "`graphs'"!=""|"`graphs'"=="" {
+
+ tempfile savefile
+ qui save `savefile'
+
+ *qui clear
+ qui drop _all
+
+ qui set obs 2000
+ qui gen u=(_n-1000)/200*`=sqrt(`covariates'[1,1])'
+ qui gen Tcum=0
+ qui gen TInf=0
+ qui gen ecartcum=.
+ forvalues i=1/`nbitems' {
+ local scatteri`i'
+ local scatteric`i'
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`i']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in /*tiny*/ vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri`i' `scatteri`i'' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric`i' `scatteric`i'' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ *set trace off
+ }
+ local d=1
+ qui gen cum``i''=0
+ *set trace on
+ if "`rsm'"=="" {
+ local mm=`modamax`i''
+ }
+ else {
+ local mm `modamax'
+ }
+ forvalues k=1/`mm' {
+ local d `d'+exp(`k'*u-`diffmat2'[`i',`k'])
+ }
+ qui gen c0_``i''=1/(`d')
+ label variable c0_``i'' "Pr(``i''=0)"
+ forvalues k=1/`mm' {
+ qui gen c`k'_``i''=exp(`k'*u-`diffmat2'[`i',`k'])/(`d')
+ qui replace cum``i''=cum``i''+c`k'_``i''*`k'
+ label variable c`k'_``i'' "Pr(``i''=`k')"
+ }
+ forvalues k=0/`mm' {
+ if `k'==0 {
+ local l=0.25
+ }
+ else if `k'==`mm' {
+ local l=`k'-0.25
+ }
+ else {
+ local l=`k'
+ }
+ qui replace ecartcum=abs(cum``i''-`l')
+ qui su ecartcum
+ qui su u if round(ecartcum,0.01)==round(`r(min)',0.01)
+ local bestest``i''_`k'=r(mean)
+ *di "item ``i'' cat `k' : est=`bestest``i''_`k''"
+ }
+ qui gen Inf``i''=0
+ forvalues k=0/`mm' {
+ qui replace Inf``i''=Inf``i''+(`k'-cum``i'')^2*c`k'_``i''
+ }
+ if "`graphitems'"=="" {
+ if "`filesave'"!="" {
+ local fsc saving("`dirsave'//CCC_``i''",replace)
+ local fsi saving("`dirsave'//ICC_``i''",replace)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line c*_``i'' u , name(CCC``i'', replace) title(Categories Characteristic Curve (CCC) of ``i'') ytitle("Probability") xtitle("Latent trait") `fsc'
+ qui graph twoway line cum``i'' u, name(ICC``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Latent trait") `scatteri`i'' `fsi'
+ qui graph twoway line cum``i'' u, name(ICCc``i'',replace) title("Item Characteristic Curve (ICC) of ``i''") ytitle("Score to the item") xtitle("Corrected latent trait") `scatteric`i'' `fsi'
+ }
+ }
+ qui replace Tcum=Tcum+cum``i''
+ *tab Tcum
+ qui replace TInf=TInf+Inf``i''
+ label variable Inf``i'' "``i''"
+ }
+ local scoremax=0
+ forvalues i=1/`nbitems' {
+ local scoremax=`scoremax'+`modamax`i''
+ }
+ qui gen ecart=.
+ forvalues i=0/`scoremax' {
+ if `i'==0 {
+ local j=0.25
+ }
+ else if `i'==`scoremax' {
+ local j=`scoremax'-0.25
+ }
+ else {
+ local j=`i'
+ }
+ qui replace ecart=abs(Tcum-`j')
+ qui su ecart
+ local tmp=r(min)
+ qui su u if round(ecart, 0.01)==round(`tmp',0.01)
+ local estlt`i'=`r(mean)'
+ *di "score `i' : `r(mean)'"
+ }
+ if "`filesave'"!="" {
+ local fst saving("`dirsave'//TCC",replace)
+ local fsteo saving("`dirsave'//TCCeo",replace)
+ local fsi saving("`dirsave'//ICC",replace)
+ local fsti saving("`dirsave'//TIC",replace)
+ local fsm saving("`dirsave'//map",replace)
+ }
+ if "`graphs'"!="" {
+qui save "C:\temp\info\info",replace
+ qui graph twoway line Tcum u, name(TCC,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `fst'
+ qui graph twoway line Inf* u, name(IIC,replace) title("Item Information Curves") ytitle("Information") xtitle("Latent trait") `fsi'
+ qui graph twoway line TInf u, name(TIC,replace) title("Test Information Curve") ytitle("Information") xtitle("Latent trait") `fsti'
+ }
+ local scatteri
+ local scatteric
+ forvalues g=1/`nbgroups' {
+ local x=`groups'[`g',`=`nbitems'+1']
+ local xc=`groups'[`g',`=`nbitems'+6']
+ local y=`groups'[`g',`=`nbitems'+3']
+ local s1=`groups'[`g',`=`nbitems'+2']
+ local seuil=30
+ local s vtiny
+ *set trace on
+ foreach lab in tiny vsmall small medsmall medium medlarge large vlarge huge vhuge /*ehuge*/ {
+ if `s1'>`seuil' {
+ local s `lab'
+ }
+ local seuil=`seuil'+10
+ }
+ local scatteri `scatteri' || scatteri `y' `x' , mcolor(black) msize(`s') legend(off)
+ local scatteric `scatteric' || scatteri `y' `xc' , mcolor(black) msize(`s') legend(off)
+ }
+ if "`graphs'"!="" {
+ qui graph twoway line Tcum u , name(TCCeo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Latent trait") `scatteri' `fsteo'
+ qui graph twoway line Tcum u , name(TCCceo,replace) title("Test Characteristic Curve (TCC)") ytitle("Score to the test") xtitle("Corrrected latent trait") `scatteric' `fsteo'
+ }
+ }
+
+
+/*************************************************************************************************************
+MAP
+*************************************************************************************************************/
+ *set trace on
+ if "`graphs'"!="" {
+ gen eff=0
+ local effmax=0
+ forvalues g=1/`nbgroups' {
+ local eff=`groups'[`g',`=`nbitems'+2']
+ if `groups'[`g',`=`nbitems'+2']>`effmax' {
+ local effmax=`groups'[`g',`=`nbitems'+2']
+ }
+ local lat=round(`groups'[`g',`=`nbitems'+1'],0.004)
+ *di "replace eff=`eff' if round(u,0.004)==`lat'"
+ qui replace eff=`eff' if round(u,0.004)==`lat'
+ }
+ gen density=normalden(u)*sqrt(`covariates'[1,1])
+ label variable eff "Frequencies"
+ label variable u "Latent trait"
+ label variable TInf "Information curve"
+ label variable density "Density function of the latent trait"
+ local scatteri
+ local scatterj
+ local color
+ qui su u if eff!=0
+ *set trace on
+ *set tracedepth 1
+ local floor=floor(`r(min)')
+ local ceil=ceil(`r(max)')
+ local sep
+ local ylbl
+ forvalues i=1/`nbitems' {
+ local color`i':word `i' of `color'
+ local unit=round(`effmax'/`nbitems',1)
+ local y=-`i'*`unit'
+ loca staritem
+ local legend `" 2 "1" "'
+ forvalues l=1/`modamax' {
+ if `l'>=2 {
+ local legend `" `legend' `=2*`l'' "`l'" "'
+ }
+ local x=`diffmat'[`i',`l']
+ local scatteri `scatteri' || scatteri `y' `x' "`l'" ,mcolor(black) mlabcolor(black)
+ if `l'==1 {
+ local xant=`x'
+ }
+ else {
+ local xant=`diffmat'[`i',`=`l'-1']
+ }
+ if `xant'>`x' {
+ local star *
+ local staritem *
+ }
+ else {
+ local star
+ }
+ local scatterj `" `scatterj' `sep' scatteri `y' `x' , pstyle(p`l') || pci `y' `xant' `y' `x', pstyle(p1) color(black)"'
+ local sep ||
+ if `x'<`floor' {
+ local floor=floor(`x')
+ }
+ if `x'>`ceil'&`x'!=. {
+ local ceil=ceil(`x')
+ }
+ }
+ local ylbl `ylbl' `=-`i'*`unit'' "``i''`staritem'"
+ local scatteri `scatteri' || scatteri `y' `=`floor'-2' "``i''",mcolor(black) mlabcolor(black) msize(vtiny)
+ }
+ qui su eff
+ local maxe=ceil(`=(floor(`r(max)'/10)+1)*10')
+ qui su TInf
+ local maxi=ceil(`r(max)')
+ qui su density
+ local maxd=round(`r(max)', 0.01)+0.01
+ qui drop if u<`floor'|u>`ceil'
+ *di "qui graph twoway (bar eff u, barwidth(.2) yaxis(1) legend(off) xlabel(0(1)`ceil')) (line TInf u,yaxis(2)) (line density u,yaxis(3)) `scatterj' , name(map,replace) ytitle(Frequencies) ylabel(0(`=`maxi'/5')`maxi' ,axis(2)) ylabel(0(`=`maxd'/5')`maxd' ,axis(3)) ylabel(-`maxe'(`=`maxe'/5')`maxe' ,axis(1)) title(Individuals/items representations (Map)) xsize(12) ysize(9) note(Red line: Information curve - Green line : Density of the latent trait) xtitle(Latent trait) `fsm'"
+ *graph combine TIC IIC, col(1)
+ *graph save "map" "map.gph", replace
+ *discard
+ *qui graph twoway line TInf u , name(map,replace)
+ *qui graph twoway `scatterj' , name(map2,replace) ytitle("") ylabel(`ylbl', grid angle(0)) legend(off) xsize(12) ysize(9)
+ qui graph twoway (bar eff u, barwidth(.2) yaxis(1) xlabel(`floor'(1)`ceil') color(erose)) (line TInf u,yaxis(2) lwidth(medthick)) (line density u,yaxis(3) lwidth(medthick) ) `scatterj' , xline(0, lcolor(black)) legend(on order(`"`legend'"') rows(1) subtitle(Threshold parameters) size(small)) name(map,replace) ytitle(" Frequencies") ylabel(0(`=`maxi'/5')`maxi' `maxi'(`maxi')`=`maxi'*2' ,axis(2)) yscale(axis(2) off) yscale(axis(3) off) ylabel(-`maxd'(`=`maxd'/5')`maxd' ,axis(3)) yline(0,lwidth(thick) lcolor(black)) ylabel(`ylbl',/*noticks*/ grid angle(0) axis(1)) ylabel(`ylbl' 0(`=`maxe'/5')`maxe', grid angle(0) axis(1)) title("Individuals/items representations (Map)") xsize(12) ysize(9) note("Red line: Information curve - Green line : Density of the latent trait - * : dysfunctioning items") xtitle("Latent trait") `fsm'
+ *histogram u, name(map,replace)
+ *graph use "map.gph", name(map, replace)
+ *graph combine TIC IIC, xcombine col(1)
+ }
+ qui use `savefile', clear
+}
+
+
+
+/*************************************************************************************************************
+Best estimates by category
+*************************************************************************************************************/
+
+tempname bestest
+matrix `bestest'=J(`nbitems',`=`modamax'+1',.)
+di
+local long=`modamax'*8+33
+di "{hline `long'}"
+di "Item" _col(29) "Cat 0" _c
+forvalues j=1/`modamax' {
+ local col=29+`j'*8
+ di _col(`col') "Cat `j'" _c
+}
+di
+di "{hline `long'}"
+forvalues i=1/`nbitems' {
+ di "``i''" _c
+ forvalues j=0/`modamax`i'' {
+ di _col(`=28+`j'*8') %6.3f round(`bestest``i''_`j'', 0.001) _c
+ matrix `bestest'[`i',`=`j'+1']=`bestest``i''_`j''
+ }
+ di
+}
+di "{hline `long'}"
+
+
+
+/*************************************************************************************************************
+EQUATING
+*************************************************************************************************************/
+*set trace on
+if "`eqset1'"!="" {
+
+ tokenize `eqset1'
+ local nbset1: word count `eqset1'
+ forvalues i=1/`nbset1' {
+ local eq1_`i':word `i' of `eqset1'
+ *di "set1 (`nbset1') : `eq1_`i''"
+ }
+ *di "`eqset1'"
+ tokenize `eqset2'
+ local nbset2: word count `eqset2'
+ *di "`eqset2'"
+ forvalues i=1/`nbset2' {
+ local eq2_`i':word `i' of `eqset2'
+ *di "set2 (`nbset2') : `eq2_`i''"
+ }
+
+
+
+ tempfile fileeq
+ qui save `fileeq',replace
+ forvalues t=1/2{
+ local scoremaxset`t'=0
+ forvalues i=1/`nbset`t'' {
+ *di "`eq`t'_`i''"
+ *local tmp=""
+ local scoremaxset`t'=`scoremaxset`t''+`modamax`eq`t'_`i'''
+ }
+ }
+ drop _all
+ *set trace on
+ qui set obs `=(`scoremaxset1'+`scoremaxset2'+2)*3'
+ forvalues t=1/2 {
+ qui gen scoreset`t'=.
+ qui gen scoreset`t'm=.
+ qui gen scoreset`t'p=.
+ }
+ forvalues i=0/`scoremaxset1' {
+ qui replace scoreset1=`i' in `=`i'+1'
+ qui replace scoreset1m=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset1p=`i' in `=`i'+1+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ forvalues i=`=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2' {
+ qui replace scoreset2=`i'-`scoremaxset1'-2 in `i'
+ qui replace scoreset2m=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)'
+ qui replace scoreset2p=`i'-`scoremaxset1'-2 in `=`i'+(`scoremaxset1'+`scoremaxset2'+2)*2'
+ }
+ local s=0
+ local eqset1b
+ foreach i in `eqset1' {
+ qui gen s1_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s1_`i'_`m'=0 in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'_`m'=1 if scoreset1>`s' in 1/`=`scoremaxset1'+1'
+ qui replace s1_`i'=s1_`i'+s1_`i'_`m'
+ local ++s
+ }
+ local eqset1b `eqset1b' s1_`i'
+ }
+ local s=0
+ local eqset2b
+ foreach i in `eqset2' {
+ qui gen s2_`i'=0
+ forvalues m=1/`modamax`i'' {
+ qui gen s2_`i'_`m'=0 in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'_`m'=1 if scoreset2>`s' in `=`scoremaxset1'+2'/`=`scoremaxset1'+`scoremaxset2'+2'
+ qui replace s2_`i'=s2_`i'+s2_`i'_`m'
+ local ++s
+ }
+ local eqset2b `eqset2b' s2_`i'
+ }
+ tokenize `varlist'
+ tempname diffset1 diffset2
+ *matrix list `diffmat'
+ forvalues t=1/2 {
+ qui matrix `diffset`t''=J(`nbset`t'',`modamax',.)
+ local n=1
+ local listset`t'
+ foreach j in `eqset`t'' {
+ forvalues i=1/`nbitems' {
+ if "`j'"=="``i''" {
+ local listset`t' `listset`t'' `i'
+ forvalues m=1/`modamax' {
+ qui matrix `diffset`t''[`n',`m']=`diffmat'[`i',`m']
+ }
+ local ++n
+ }
+ }
+ }
+ }
+ *matrix list `diffset1'
+ *matrix list `diffset2'
+ local var=`covariates'[1,1]
+ qui gen lt=.
+ *qui gen selt=.
+ forvalues t=1/2 {
+ tempname matscorelt`t'
+ qui pcm `eqset`t'b', diff(`diffset`t'') var(`var') minsize(1)
+ qui matrix `matscorelt`t''=r(matscorelt)
+ *di "matscorelt`t':"
+ *matrix list `matscorelt`t''
+ forvalues i=0/`scoremaxset`t'' {
+ qui replace lt=`matscorelt`t''[`=`i'+1',2] if scoreset`t'==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]+1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'p==`i'
+ qui replace lt=`matscorelt`t''[`=`i'+1',2]-1.96*`matscorelt`t''[`=`i'+1',3] if scoreset`t'm==`i'
+ *qui replace selt=`matscorelt`t''[`=`i'+1',3] if scoreset`t'==`i'
+ }
+ qui ipolate scoreset`t' lt, gen(score`t') epolate
+ }
+ qui ipolate scoreset1 lt, gen(score1bis) epolate
+
+
+ *list
+ forvalues t=1/2 {
+ qui replace score`t'=scoreset`t'm if scoreset`t'm!=.
+ qui replace score`t'=scoreset`t'p if scoreset`t'p!=.
+ qui replace score1=score1bis if score1==.
+ qui replace score`t'=0 if score`t'<0
+ qui replace score`t'=`scoremaxset`t'' if score`t'>`scoremaxset`t''
+ }
+ forvalues t=1/2 {
+ tempname matscore`t'
+ qui matrix `matscore`t''=J(`=`scoremaxset`t''+1',7,.)
+ forvalues s=0/`scoremaxset`t'' {
+ qui matrix `matscore`t''[`=`s'+1',1]=`s'
+ qui su lt if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',2]=r(mean)
+ qui su lt if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',3]=r(mean)
+ qui su lt if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',4]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'==`s'
+ qui matrix `matscore`t''[`=`s'+1',5]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'm==`s'
+ qui matrix `matscore`t''[`=`s'+1',6]=r(mean)
+ qui su score`=3-`t'' if scoreset`t'p==`s'
+ qui matrix `matscore`t''[`=`s'+1',7]=r(mean)
+ }
+ matrix colnames `matscore`t'' =score`t' lt lt- lt+ score`=3-`t'' score`=3-`t''- score`=3-`t''+
+ *matrix list `matscore`t''
+ di
+ di "{hline 78}"
+ di "EQUATING SET`t' TO SET`=3-`t''"
+ di "{hline 78}"
+ di "Set`t' : `eqset`t''"
+ di "Set`=3-`t'' : `eqset`=3-`t'''"
+ di "{hline 78}"
+ di _col(20) "<----- Latent trait ----->" _col(52) "<------- Score `=3-`t'' --------->"
+ di "Score`t'" _col(20) "Estimated" _col(39) "[95%IC]" _col(52) "Estimated" _col(72) "[95%IC]"
+ di "{hline 78}"
+ forvalues s=0/`scoremaxset`t'' {
+ di %4.0f `matscore`t''[`=`s'+1',1] _col(24) %5.2f `matscore`t''[`=`s'+1',2] _col(33) "[" %5.2f `matscore`t''[`=`s'+1',3] ";" %5.2f `matscore`t''[`=`s'+1',4] "]" _col(56) %5.2f `matscore`t''[`=`s'+1',5] _col(66) "[" %5.2f `matscore`t''[`=`s'+1',6] ";" %5.2f `matscore`t''[`=`s'+1',7] "]"
+ }
+ di "{hline 78}"
+ return matrix score`t'_to_`=3-`t''=`matscore`t''
+ if "`eqgraph'"!="" {
+ *twoway (line lt scoreset1) (line lt scoreset2), name(eq1)
+ *twoway (line scoreset1 scoreset2 lt) , name(eq2)
+ *twoway (line score1 scoreset1m scoreset1p score2), name(eq3)
+ *twoway (line score2 scoreset2m scoreset2p score1), name(eq4)
+ twoway (line score`t' score`=3-`t'' if scoreset`=3-`t''!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''m!=.) (line score`t' score`=3-`t'' if scoreset`=3-`t''p!=.), title("Equating score of the Set `t' from the Set `=3-`t''") ytitle("Score `t'") xtitle("Score `=3-`t''") ylabel(0(1)`scoremaxset`t'') xlabel(0(1)`scoremaxset`=3-`t''') name(eq`t'to`=3-`t'')
+ *twoway (line score2 score1 if scoreset1!=.) (line score2 score1 if scoreset1m!=.) (line score2 score1 if scoreset1p!=.), name(eq6)
+ }
+ }
+ *save prout, replace
+ *clear
+
+ qui use `fileeq',clear
+}
+
+
+/*************************************************************************************************************
+RETOUR AU FICHIER INITIAL ET SAUVEGARDE DES NOUVELLES VARIABLES
+*************************************************************************************************************/
+if "`visit'"!="" {
+ tempfile sauv
+ set trace on
+ *tempname corrlatent corrbilatent
+ qui keep `latent'* `selatent'* `id' `visit'
+ qui reshape wide , i(`id') j(`visit')
+ qui sort `id'
+ qui save `sauv', replace
+ restore,preserve
+ if "`replace'"!=""&("`genlt'"!=""|"`geninf'"!="") {
+ capture drop `genlt'
+ capture drop `genlt'_se
+ capture drop `geninf'
+ capture drop `genlt'_corr
+ capture drop `genlt'_opt
+ capture drop `genlt'_opt_se
+ }
+ *su
+ tempname idorder
+ qui gen `idorder'=_n
+ qui sort `id'
+ qui merge 1:1 `id' using `sauv'
+
+ qui sort `idorder'
+ qui drop `idorder'
+}
+else {
+*set trace on
+*set tracedepth 1
+ if "`genlt'"!="" {
+ qui gen `genlt'_corr=.
+ forvalues s=0/`scoremax' {
+ qui replace `genlt'_corr=`estlt`s'' if `score'==`s'
+ }
+ forvalues g=1/`nbgroups' {
+ qui replace `genlt'_corr=`clt`g'' if `group'==`g'&`genlt'_corr==.
+ }
+ tempvar tmpitem mean nbnonmiss
+ forvalues i=1/`nbitems' {
+ qui gen `tmpitem'_`i'=.
+ forvalues k=0/`modamax' {
+ qui replace `tmpitem'_`i'=`bestest'[`i',`=`k'+1'] if ``i''==`k'
+ }
+ }
+ *su
+ qui egen `genlt'_opt=rowmean(`tmpitem'_*)
+ qui egen `genlt'_opt_se=rowsd(`tmpitem'_*)
+ qui egen `nbnonmiss'=rownonmiss(`tmpitem'_*)
+ qui replace `genlt'_opt_se=sqrt((`genlt'_opt_se^2+`resvar')/`nbnonmiss')
+ }
+ restore,not
+}
+
+/*************************************************************************************************************
+CREATION DU DOCX
+*************************************************************************************************************/
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("General informations") , bold underline font(,14) smallcaps
+ putdocx paragraph
+ putdocx text ("Number of individuals: `nbobs'")
+ putdocx paragraph
+ putdocx text ("Number of complete individuals: `nbobsssmd'")
+ putdocx paragraph
+ putdocx text ("Number of items: `nbitems'")
+ putdocx paragraph
+ putdocx text ("List of items: `varlist'")
+ putdocx paragraph
+ putdocx text ("Date: $S_DATE, $S_TIME")
+ putdocx paragraph
+ local model Partial Credit Model (PCM)
+ if "`rsm'"!="" {
+ local model Rating Scale Model (RSM)
+ }
+ putdocx text ("Model: `model'")
+ putdocx paragraph
+ putdocx text ("Marginal log-likelihood: `ll'")
+
+ putdocx paragraph
+ putdocx text ("Estimation of the parameters") , bold underline font(,14) smallcaps
+ putdocx table tablename = matrix(`diff') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ qui putdocx table tablename = matrix(`covariates') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ putdocx paragraph
+ putdocx text ("Fit indexes for items") , bold underline font(,14) smallcaps
+ qui putdocx table tablename = matrix(`fit') , nformat(%9.3f) rownames colnames border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
+ local extension png
+}
+
+/*************************************************************************************************************
+SAUVEGARDE DES GRAPHIQUES
+*************************************************************************************************************/
+
+*set trace on
+if "`filesave'"!="" {
+ if "`graphs'"!="" {
+ if "`docx'"!="" {
+ putdocx pagebreak
+ putdocx paragraph
+ putdocx text ("General graphs") , bold underline font(,14) smallcaps
+ }
+ foreach i in TCC TCCeo TIC IIC map {
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`i'.`extension'", replace name(`i')
+ }
+ *graph display `i'
+ *qui graph save "`dirsave'//`i'", replace
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`i'.png", height(10cm)
+ }
+ }
+ *discard
+ if "`graphitems'"=="" {
+ forvalues i=1/`nbitems' {
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("Graphs for ``i''") , bold underline font(,14) smallcaps
+ }
+ foreach j in CCC ICC residuals {
+ *graph display `j'``i''
+ *qui graph save "`dirsave'//`j'_``i''", replace
+
+ if "`extension'"!="" {
+ qui graph export "`dirsave'//`j'_``i''.`extension'", replace name(`j'``i'')
+ }
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx image "`dirsave'//`j'_``i''.png" , height(10cm)
+ }
+ }
+ }
+ }
+ }
+}
+if "`docx'"!="" {
+ putdocx save "`dirsave'//`docx'.docx", replace
+}
+
+
+/*************************************************************************************************************
+RETURNS
+*************************************************************************************************************/
+
+
+matrix colnames `diff'=Estimate "s.e." z p lb ul
+matrix colnames `covariates'=Estimate "s.e." z p lb ul
+matrix rownames `diff'=`diffname'
+matrix rownames `covariates'=Variance `continuous' `catname'
+return matrix difficulties=`diff'
+return matrix covariates=`covariates'
+return matrix matscorelt=`matscorelt'
+return matrix bestest=`bestest'
+capture restore, not
+end
diff --git a/Modules/ado/personal/p/pcmodel.hlp b/Modules/ado/personal/p/pcmodel.hlp
new file mode 100644
index 0000000..59db43f
--- /dev/null
+++ b/Modules/ado/personal/p/pcmodel.hlp
@@ -0,0 +1,126 @@
+{smcl}
+{* Mars 2012}{...}
+{hline}
+help for {hi:pcmodel}{right:JFH}
+{hline}
+
+{title:Estimation of the parameters of a Partial Credit Model}
+
+{p 8 14 2}{cmd:pcmodel} (varlist) [{cmd:if} {it:exp}],
+[{cmdab:qual:itatives}({it:varlist})
+{cmdab:quant:itatives}({it:varlist})
+{cmdab:dif:ficulties}({it:matrix list})
+{cmdab:it:erate}(#)
+{cmdab:ad:apt}
+{cmdab:ro:bust}
+{cmdab:f:rom}(matrix)]
+
+{title:Description}
+
+{p 8 14 2}{cmd:pcmodel} allows estimating the parameters of a random effect
+ partial credit model (the item difficulties, and the potential covariates
+ that may influence the considered latent trait are considered as fixed effects.
+ The individual latent traits are considered as a normally distributed
+ random effect){p_end}
+{p 14 14 2}Two situations are possible:{p_end}
+{p 14 14 2}- The item difficulties can be
+ considered as already known. They do not have to be estimated during the
+ analysis.{p_end}
+{p 14 14 2}- The difficulties are considered as unknowns, and then require
+ to be estimated during the analysis. {p_end}
+{p 14 14 2}It is possible to include covariates (that can possibly influence
+ the individual latent traits) in the partial credit model. These covariates
+ can either be qualitative or quantitative. {p_end}
+{p 14 14 2}{cmd:pcmodel} provides assistance for interpreting the estimated
+ effects of covariates (estimation of the type III sum of squares, percentage
+ of variance explained with the introduction of each covariates). {p_end}
+{p 14 14 2}It is finally possible to thest the fit using {cmd:pcmtest} after
+ estimating parameters of the model with {cmd:pcmodel}
+
+{title:Options}
+
+{p 4 8 2}{cmdab:qual:itatives} List of the categorical covariates included in
+ the partial credit model
+
+{p 4 8 2}{cmdab:quant:itatives} List of the continuous covariates included in
+ the partial credit model
+
+{p 4 8 2}{cmd:difficulties} Row vectors containing the considered known values
+ of each item difficulty. A row vector must match with each item, and have the
+ same name as the corresponding item. The item difficulties should be known for
+ all the items. If {cmd:difficulties} is not filled, the dificulties are
+ considered as unknown, and are estimated during the analysis.
+
+{p 4 8 2}{cmd:iterate} specifies the (maximum) number of iterations. With the
+ adapt option, use of the iterate(#) option will cause pcmodel to skip the
+ "Newton Raphson" iterations usually performed at the end without updating
+ the quadrature locations.
+
+
+{p 4 8 2}{cmd:adapt} causes adaptive quadrature to be used instead of
+ ordinary quadrature.
+
+{p 4 8 2}{cmd:robust} specifies that the Huber/White/sandwich estimator of the
+ covariance matrix of the parameter estimates is to be used.
+
+
+{p 4 8 2}{cmd:from} specifies a row vector to be used for the initial values.
+ Note that the column-names and equation-names do not have to be correct. This
+ line vector must have exactly the number of parameters to be estimated,
+ starting with the difficulties parameters, then the parameters associated
+ with the covariates, and finishing with the estimated standard deviation
+ of the latent trait.
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:e(lll)}: (marginal) log-likelihood
+
+{p 4 8 2}{cmd:e(cn)}: Condition number
+
+{p 4 8 2}{cmd:e(N)}: Number of observations
+
+{p 4 8 2}{cmd:e(Nit)}: Number of items
+
+{p 4 8 2}{cmd:e(Nqual)}: Number of qualitative covariates
+
+{p 4 8 2}{cmd:e(Nquant)}: Number of quantitative covariates
+
+{p 4 8 2}{cmd:e(items)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(itest)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(datatest)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(mugauss)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(sdgauss)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(cmd)}: program used to implement {cmdpcmtest}
+
+{p 4 8 2}{cmd:e(sigma)}: Estimated standard deviation of the latent trait
+
+{p 4 8 2}{cmd:e(Varsigma)}: Variance of the estimated standard deviation of
+ the latent trait
+
+{p 4 8 2}{cmd:e(b)}: coefficient vector of the parameters associated with
+ the latent trait covariates (if no covariate is included in the model, value
+ of the average latent trait).
+
+{p 4 8 2}{cmd:e(V)}: Covariance matrix for the latent trait covariates.
+
+{p 4 8 2}{cmd:e(delta)}: Estimated difficulty parameters
+
+{p 4 8 2}{cmd:e(Vardelta)}: Covariance matrix for the estimated difficulty
+ parameters
+
+
+{title:Author}
+
+{p 4 8 2}Jean-François HAMEL{p_end}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help pcmtest}, {help gllamm}, {help simirt},
+ {help raschtest}.{p_end}
+
+
diff --git a/Modules/ado/personal/p/pcmodel.sthlp b/Modules/ado/personal/p/pcmodel.sthlp
new file mode 100644
index 0000000..f9b887c
--- /dev/null
+++ b/Modules/ado/personal/p/pcmodel.sthlp
@@ -0,0 +1,194 @@
+{smcl}
+{* Mars 2012}{...}
+{hline}
+help for {hi:pcmodel}
+{hline}
+
+
+{title:Estimation of the parameters of a Partial Credit Model}
+
+{p 8 14 2}{cmd:pcmodel} (varlist) [{help if} {help in}],
+[{cmdab:cat:egorical}({it:varlist})
+{cmdab:cont:inuous}({it:varlist})
+{cmdab:dif:ficulties}({it:matrix list})
+{cmdab:it:erate}(#)
+{cmdab:ad:apt}
+{cmdab:ro:bust}
+{cmdab:f:rom}(matrix)
+{cmdab:rsm:}
+{cmdab:nip:}
+{cmdab:tr:ace}
+{cmdab:est:imateonly}
+{cmdab:l:evel}(#)]
+
+
+{title:Description}
+
+{p 8 14 2}{cmd:pcmodel} allows estimating the parameters of a random effect
+ partial credit model or a random effect rating scale model
+ (the item difficulties, and the covariates
+ that may influence the considered latent trait are considered as fixed
+effects, and the individual latent traits are considered as a normally distributed
+ random effect){p_end}
+{p 14 14 2}Two situations are possible:{p_end}
+{p 16 18 2}- The item difficulties can be considered as already known
+(for example provided by the scale developer).
+In this case, they do not have to be estimated during the analysis.{p_end}
+{p 16 18 2}- The difficulties are considered as unknowns and will
+ be estimated during the analysis. {p_end}
+
+{p 14 14 2}{cmd:pcmodel} allows including covariates that
+can possibly influence the individual latent traits in the considered model
+(partial credit or rating scale). These covariates
+ can either be categorical or continuous. {p_end}
+
+{p 14 14 2}{cmd:pcmodel} provides assistance for interpreting both the quality
+of model fit (by estimating the marginal McFadden's pseudo R2) and the
+ contribution of covariates to the model
+ (by estimating the the type III sum of squares, the percentage
+ of variance explained with the introduction of each covariates and the percentage
+ of McFadden's pseudo R2 explained with the introduction of each
+ covariate). {p_end}
+
+{p 14 14 2}It is finally possible to test the fit using {cmd:pcmtest} after
+ estimating parameters of the model with {cmd:pcmodel}
+
+
+{title:Options}
+
+{p 4 8 2}{cmd:categorical} List of the categorical covariates included in
+ the Partial Credit model or the Rating Scale model.
+
+{p 4 8 2}{cmd:continuous} List of the continuous covariates included in
+ the Partial Credit model or the Rating Scale model.
+
+{p 4 8 2}{cmd:difficulties} Row vectors containing the known values
+ of each item difficulty (if they are known).
+ A row vector must match with each item, and have the
+ same name as the corresponding item. If the option {cmd:difficulties}
+ is not filled, the item difficulties are
+ considered as unknown, and they are estimated during the analysis.
+ (this option cannot be used with the {cmd:rsm} option
+
+{p 4 8 2}{cmd:iterate} specifies the (maximum) number of iterations. With the
+ adapt option, use of the iterate(#) option will cause pcmodel to skip the
+ "Newton Raphson" iterations usually performed at the end without updating
+ the quadrature locations.
+
+{p 4 8 2}{cmd:adapt} causes adaptive quadrature to be used instead of
+ ordinary quadrature.
+
+{p 4 8 2}{cmd:robust} specifies that the Huber/White/sandwich estimator of the
+ covariance matrix of the parameter estimates is to be used.
+
+{p 4 8 2}{cmd:from} specifies a row vector to be used for the initial values.
+ It is not necessary to specify column-names or equation-names for this line vector,
+ but this vector must have exactly the number of parameters to be estimated,
+ starting with the difficulties parameters, the parameters associated
+ with the covariates, and ending with the estimated standard deviation
+ of the latent trait.
+
+{p 4 8 2}{cmd:rsm} performs a Rating Scale model instead of a Partial Credit model.
+
+{p 4 8 2}{cmd:estimateonly} Do not perform the Marginal McFadden's pseudo R2
+nor the type III sums of square computations
+
+{p 4 8 2}{cmd:nip} specifies the number of integration points to be used for each
+integral or summation. Only the following degrees are available: 5, 7, 9, 11, 15.
+
+{p 4 8 2}{cmd:trace} causes more output to be displayed. Before estimation begins,
+details of the specified model are displayed. In addition, a detailed iteration
+log is shown including parameter estimates and log-likelihood values for each iteration.
+
+{p 4 8 2}{cmd:level} set confidence level; default is level(95)
+
+
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:e(ll)}: marginal log-likelihood
+
+{p 4 8 2}{cmd:e(cn)}: Condition number
+
+{p 4 8 2}{cmd:e(N)}: Number of observations
+
+{p 4 8 2}{cmd:e(Nit)}: Number of items
+
+{p 4 8 2}{cmd:e(Ncat)}: Number of categorical covariates
+
+{p 4 8 2}{cmd:e(Ncont)}: Number of continuous covariates
+
+{p 4 8 2}{cmd:e(sigma)}: Estimated standard deviation of the latent trait
+
+{p 4 8 2}{cmd:e(Varsigma)}: Variance of the estimated standard deviation of
+ the latent trait
+
+{p 4 8 2}{cmd:e(theta)}: Coefficient vector of the parameters associated with the latent trait covariates (if no covariate is included in the model, value of the average latent trait)
+
+{p 4 8 2}{cmd:e(Vartheta)}: Covariance matrix for the latent trait covariates.
+
+{p 4 8 2}{cmd:e(delta)}: Estimated difficulty parameters
+
+{p 4 8 2}{cmd:e(Vardelta)}: Covariance matrix for the estimated difficulty parameters
+
+{p 4 8 2}{cmd:e(b)}: Overall estimated parameters of the PCM (or RSM)
+
+{p 4 8 2}{cmd:e(V)}: Covariance matrix for the overall estimated parameters
+
+{marker example}{...}
+{title:Example}
+
+{pstd}
+Simulation of the data (using {help simirt}):
+
+ . {cmd:simirt, nbobs(200) dim(5) rsm1(0.2) group(0.5) deltagroup(0.4) clear}{right:(1) }
+
+{pstd}
+Estimating a Partial Credit Model with {cmd:pcmodel}:
+
+ . {cmd:pcmodel item*}{right:(2) }
+
+{pstd}
+Estimating a Rating Sacle Model with {cmd:pcmodel}:
+
+ . {cmd:pcmodel item*, rsm}{right:(3) }
+
+{pstd}
+Testing the fit of the previously performed model with {help pcmtest}:
+
+ . {cmd:pcmtest, si }{right:(4) }
+
+{pstd}
+Estimating a Partial Credit Model with {cmd:pcmodel}, considering that the item difficulties
+are provided by the scale developer (-1 & -0.8 for item1, -0.5 & -0.3 for item2, 0 & 0.2 for
+item3, 0.5 & 0.7 for item4 and 1 & 1.2 for item5) and that the {it:group} covariate may
+influence the individual latent trait:
+
+{p 6 9 2}
+1/ Defining the row vectors containing the known values of each item difficulty, with the
+same name as the corresponding item:
+
+ . {cmd:matrix item1=(-1,-0.8)}{right:(5) }
+ . {cmd:matrix item2=(-0.5,-0.3)}{right:(6) }
+ . {cmd:matrix item3=(0,0.2)}{right:(7) }
+ . {cmd:matrix item4=(0.5,0.7)}{right:(8) }
+ . {cmd:matrix item5=(1,1.2)}{right:(9) }
+
+{p 6 9 2}
+2/ Estimating the Partial Credit Model with item difficulties already known, including
+the {it:group} covariate as a categorical covariate:
+
+ . {cmd:pcmodel item*, difficulties(item1 item2 item3 item4 item5) cat(group)}{right:(10) }
+
+
+{title:Author}
+
+{p 4 8 2}Jean-François Hamel{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jeanfrancois.hamel@chu-angers.fr":jeanfrancois.hamel@chu-angers.fr}{p_end}
+
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help pcmtest}, {help gllamm}, {help simirt},
+ {help raschtest}.{p_end}
diff --git a/Modules/ado/personal/p/pcmodel22.ado b/Modules/ado/personal/p/pcmodel22.ado
new file mode 100644
index 0000000..3228fd1
--- /dev/null
+++ b/Modules/ado/personal/p/pcmodel22.ado
@@ -0,0 +1,1140 @@
+/********************************************************************************/
+/* v1.1 : Bug fixed regarding the estimation of the latent trait standard error */
+/* v2 : Bugs with temporary names fixed, New options have been added, */
+/* modifications of the output */
+/********************************************************************************/
+
+program define pcmodel, eclass
+version 11.0
+syntax [varlist] [if] [in] [, CATegorical(string) CONTinuous(string) DIFficulties(string) ITerate(string) ADapt RObust From(string) RSM ESTimateonly nip(string) TRace Level(string)]
+
+preserve
+tempfile bddinip
+qui save `bddinip',replace
+local Cond=0
+
+if "`level'"==""{
+ local level=c(level)
+}
+
+
+if replay() {
+ capture local cmdavant=e(cmd)
+ if _rc!=0 | "`cmdavant'"!="pcmodel"{
+ noi di in red "pcmodel was not the last command"
+ error 100
+ }
+ if "`categorical'`continuous'`difficulties'`iterate'`adapt'`robust'`from'`rsm'`estimateonly'`nip'"==""{
+ local rsm=e(rsm)
+ local LLfull=e(ll)
+ local estimateonly=e(estimateonly)
+ local R2Nag=e(r2)
+ local Nbid=e(N)
+ local nbit=e(Nit)
+ local categorical=e(categorical)
+ local continuous=e(continuous)
+ if "`continuous'"=="."{
+ local continuous=""
+ }
+ if "`categorical'"=="."{
+ local categorical=""
+ }
+ local nbcov: word count `categorical'
+ local nbcovquant: word count `continuous'
+ local varlist=e(items)
+ tokenize `varlist' `categorical' `continuous'
+ local difficulties=e(difficulties)
+ local contrR=e(constr)
+ tempname eB eV VarExpSS
+ matrix `eB'=e(b)
+ matrix `eV'=e(V)
+ matrix `VarExpSS'=e(VarExpSS)
+ local nbc=colsof(`eB')
+ local nbdifftotbis=e(ndtb)
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ``i''_m=e(``i'')
+ local k=1
+ local nbModCov`=`i'-`nbit''=wordcount("```i''_m'")
+ foreach m in ```i''_m'{
+ local ident`=`i'-`nbit''_`k'=`m'
+ local k=`k'+1
+ }
+ }
+ }
+ if "`rsm'"!="."{
+ di in gr "Model : " in ye "Rating Scale Model"
+ }
+ else{
+ di in gr "Model : " in ye "Partial Credit Model"
+ }
+ di in gr ""
+ di in gr " log likelihood: " in ye %-18.3f `LLfull'
+ if "`estimateonly'"=="."{
+ di in gr " Marginal McFadden's pseudo R2: " in ye %-4.1f `=`R2Nag'*100' "%"
+ }
+ di in gr " Number of individuals: "in ye "`Nbid'"
+ di in gr " Number of items: "in ye "`nbit'"
+ if `=`nbcov'+`nbcovquant''!=0{
+ di in gr " Number of covariates: "in ye "`=`nbcov'+`nbcovquant''"
+ }
+ di in gr ""
+ di ""
+ di in gr "Parameters of the Latent trait distribution:"
+ di ""
+ if "`difficulties'"=="."{
+ di in gr " Identifiability constraint: `contrR'set to 0"
+ }
+ di in gr " Variance of the Latent trait: SigmaÂČ=" in ye %-8.3f (`=`=`eB'[1,`nbc']'')^2 in gr " (SE:"in ye %-8.3f `= sqrt((2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']' )' in gr ")"
+ local varTheta=(`=`=`eB'[1,`nbc']'')^2
+ local Varvartheta=(2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']'
+ di ""
+ if `nbcov'+`nbcovquant'!=0{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 66}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]"
+ di in gr "{hline 66}"
+ local compteur=1
+ if "`difficulties'"=="."{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if "`difficulties'"!="."{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 66}"
+ }
+ if "`estimateonly'"=="."{
+ di ""
+ di "Proportion of latent trait variance explained by covariates"
+ di ""
+ di in gr "{hline 53}"
+ di _col(23) in gr "SS.III" _col(34) in gr "df" _col(38) in gr "V.exp." _col(47) in gr "R2.exp."
+ di in gr "{hline 53}"
+ local compteur=1
+ if "`difficulties'"=="."{
+ local compteur=`nbdifftotbis'
+ }
+ local compte=1
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=`VarExpSS'[`compte',1]
+ local df=`VarExpSS'[`compte',2]
+ local vexp=`VarExpSS'[`compte',3]
+ local r2exp=`VarExpSS'[`compte',4]
+ local compteur=`compteur'+1
+ local compte=`compte'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=`VarExpSS'[`compte',1]
+ local df=`VarExpSS'[`compte',2]
+ local vexp=`VarExpSS'[`compte',3]
+ local r2exp=`VarExpSS'[`compte',4]
+ local compteur=`compteur'+1
+ local compte=`compte'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ di in gr "{hline 53}"
+ local sssc=`VarExpSS'[`=`compte'',1]
+ local dfsc=`VarExpSS'[`=`compte'',2]
+ local ssac=`VarExpSS'[`=`compte'+1',1]
+ local dfac=`VarExpSS'[`=`compte'+1',2]
+ di _col(23) in gr "SS.res" _col(34) in gr "df"
+ di _col(1) in gr "Model without cov." _col(22) in ye %6.3f `sssc' _col(31) in ye %5.0f `dfsc'
+ di _col(1) in gr "Full model" _col(22) in ye %6.3f `ssac' _col(31) in ye %5.0f `dfac'
+ di in gr "{hline 53}"
+ di ""
+ }
+ }
+ else if "`difficulties'"!="."{
+ di in gr "Latent trait distribution"
+ di in gr "{hline 80}"
+ di _col(18) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "z" _col(52) in gr "P>|z|" _col(61) in gr "[`level'% Conf. Interval]"
+ di in gr "{hline 80}"
+ di _col(1) in gr "Mu" _col(15) in ye %8.5f `=`eB'[1,1]' _col(27) in ye %8.5f `=sqrt(`eV'[1,1]) ' _col(39) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) '' _col(51) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) ')))' _col(61) in ye %8.5f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) '' _col(73) in ye %8.5f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) ''
+
+ di _col(1) in gr "Sigma" _col(15) in ye %8.5f `=abs(`eB'[1,`nbc'])' _col(27) in ye %8.5f `=sqrt(`=`eV'[`nbc',`nbc']')' _col(39) in ye %5.2f `=`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']')' _col(51) in ye %6.3f `=2*(1-normal(abs(`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']'))))' _col(61) in ye %8.5f `=`eB'[1,`nbc']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')' _col(73) in ye %8.5f `=`eB'[1,`nbc']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')'
+ di in gr "{hline 80}"
+ di ""
+ }
+ if "`difficulties'"=="."{
+ di in gr "Items difficulty parameters:"
+ di ""
+ di in gr "{hline 52}"
+ di _col(1) in gr "Item" _col(21) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "[`level'% C.I.]" _col(66)
+ di in gr "{hline 52}"
+ local compteur=1
+ if "`rsm'"=="."{
+ forvalues i=1/`nbit'{
+
+ tempname rep__`i'
+ qui tab ``i'', matrow(`rep__`i'')
+ local moda`i'=`=r(r)'
+ di _col(1) in gr "``i'':"
+ forvalues g=1/`=`moda`i''-1'{
+ di _col(4) in gr "response: " in ye %-6.2g `=`rep__`i''[`=`g'+1',1]' _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+1
+ }
+ di in gr "{hline 52}"
+ }
+ di ""
+ }
+ else{
+ tempname tau
+ matrix `tau'=e(Tau)
+ forvalues i=1/`nbit'{
+ tempname rep__`i'
+ qui tab ``i'', matrow(`rep__`i'')
+ local moda`i'=`=r(r)'
+ di _col(1) in gr "``i'':" _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+`=`moda1'-1'
+ }
+ di in gr "{hline 52}"
+ forvalues i=2/`=`moda1'-1'{
+ di _col(1) in gr "tau`=`i'-1':" _col(20) in ye %6.3f `=`tau'[1,`i']' _col(29) in ye %6.3f `=`tau'[2,`i']' _col(38) in ye %6.3f `=`=`tau'[1,`i']'-`=(1+`level'/100)/2'*`=`tau'[2,`i']'' _col(47) in ye %6.3f `=`=`tau'[1,`i']'+`=(1+`level'/100)/2'*`=`tau'[2,`i']''
+ }
+ di in gr "{hline 52}"
+ }
+ }
+ else{
+ di in gr "Items difficulty parameters: fixed for the analysis"
+ }
+ }
+ else{
+ local Cond=1
+ local varlist=e(items)
+ if "`categorical'"=="" & "`=e(categorical)'"!="."{
+ local categorical=e(categorical)
+ }
+ if "`continuous'"=="" & "`=e(continuous)'"!="."{
+ local continuous=e(continuous)
+ }
+ if "`difficulties'"=="" & "`=e(difficulties)'"!="."{
+ local difficulties=e(difficulties)
+ }
+ if "`iterate'"=="" & "`=e(iterate)'"!="."{
+ local iterate=e(iterate)
+ }
+ if "`adapt'"=="" & "`=e(adapt)'"!="."{
+ local adapt=e(adapt)
+ }
+ if "`robust'"=="" & "`=e(robust)'"!="."{
+ local robust=e(robust)
+ }
+ if "`from'"=="" & "`=e(from)'"!="."{
+ local from=e(from)
+ }
+ if "`rsm'"=="" & "`=e(rsm)'"!="."{
+ local rsm=e(rsm)
+ }
+ if "`estimateonly'"=="" & "`=e(estimateonly)'"!="."{
+ local estimateonly=e(estimateonly)
+ }
+ }
+}
+else{
+ local Cond=1
+}
+if `Cond'==1{
+ tokenize `varlist' `categorical' `continuous'
+ local nbit: word count `varlist'
+ local nbcov: word count `categorical'
+ local nbcovquant: word count `continuous'
+ local nbit2:word count `difficulties'
+ local NIP ""
+ if "`nip'"!=""{
+ local NIP "nip(`nip')"
+ }
+ tempname nom val
+ if `nbit2'==0{
+ local itest=1
+ }
+ else{
+ local itest=0
+ }
+ if "`from'"!=""{
+ local verifFrom=colsof(`from')
+ }
+ tempfile bddini bddinib
+ qui{
+ marksample touse,novarlist
+ keep if `touse'
+ local ordre=0
+ forvalues i=1/`nbit'{
+ tempname rep__`i'
+ tab ``i'', matrow(`rep__`i'')
+ local ordre=`ordre'+`=rowsof(`rep__`i'')'-1
+ forvalues j=1/`=rowsof(`rep__`i'')'{
+ replace ``i''=`j'-1 if ``i''==`rep__`i''[`j',1]
+ }
+ }
+ save `bddinib',replace
+ q memory
+ }
+ local matsizeini=r(matsize)
+ if "`rsm'"!=""{
+ local nbtotmodait=rowsof(`rep__1')
+ forvalues i=2/`nbit'{
+ if `=rowsof(`rep__`i'')'!=`nbtotmodait'{
+ noi di in red "The number of item response categories must be equal for each item when using Rating Scale models"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ if "`difficulties'"!=""{
+ noi di in red "RSM option only available for unknow difficulties"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ if "`from'"!=""{
+ if "`difficulties'"!=""{
+ noi di in red "From option only available for unknow difficulties"
+ use `bddinip',replace
+ error 100
+ }
+ if "`rsm'"!=""{
+ noi di in red "From option only available for the Partial Credit model"
+ use `bddinip',replace
+ error 100
+ }
+ }
+
+ /*************************************/
+ /* Verifications */
+ /*************************************/
+
+ if "`iterate'"==""{
+ local it=""
+ }
+ else{
+ local iterateII="it(`iterate')"
+ }
+ tempvar one id item reponse obs wt x choix it covariable covverytemp
+ qui save `bddinib', replace
+ if "`difficulties'"!=""{
+ if `nbit2'!=`nbit'{
+ noi di in red "Not the same number of difficulty vectors and of items"
+ use `bddinip',replace
+ error 100
+ }
+ forvalues i=1/`nbit'{
+ if strpos("`varlist'",word("`difficulties'",`i'))==0{
+ noi di in red "The item difficulty vectors must have the same names than the item variables"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ }
+ /*************************************/
+ /* Estimation of the parameters */
+ /*************************************/
+ local nbtotmodacov=0
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ qui tab ``=`nbit'+`i''', matrow(`nom') matcell(`val')
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ local valmod`k'cov`i'=`nom'[`k',1]
+ local nbmod`k'cov`i'=`val'[`k',1]
+ }
+ local nbtotmodacov=`nbtotmodacov'+`nbModCov`i''
+ if `nbModCov`i''>15{
+ noi di in ye "Are you sure that ``=`nbit'+`i''' is a categorical variable? (``=`nbit'+`i''' has `nbModCov`i'' categories)"
+ noi di in gr ""
+ }
+ local tot`i'=r(N)
+ forvalues k=1/`nbModCov`i''{
+ local sum=0
+ forvalues k2=1/`nbModCov`i''{
+ if `k2'!=`k'{
+ local sum=`sum'+`val'[`k2',1]
+ }
+ }
+ local a`i'_`k'=round((`sum'-`tot`i'')/`tot`i'',0.01)
+ local b`i'_`k'=round((`sum')/`tot`i'',0.01)
+ }
+ }
+ }
+ local nbparcov=`nbtotmodacov'+`nbcovquant'
+ qui{
+ keep `varlist' `categorical' `continuous'
+ local nbdifftotbis=0
+ local nbdifftot=0
+ if "`difficulties'"=="" & "`rsm'"==""{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ tab `reponse'`i'
+ local moda`i'=`=r(r)'
+ local nbdifftot=`nbdifftot'+`moda`i''-1
+ local nbdifftotbis=`nbdifftotbis'+`moda`i''-1
+ }
+ }
+ else if "`difficulties'"=="" & "`rsm'"!=""{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ tab `reponse'`i'
+ local moda`i'=`=r(r)'
+ local nbdifftot=`nbdifftot'+1
+ local nbdifftotbis=`nbdifftotbis'+`moda`i''-1
+ }
+ local nbdifftot=`nbdifftot'+`nbtotmodait'-2
+ }
+ else{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ local moda`i'=colsof(``i'')+1
+ }
+ }
+ if "`from'"!=""{
+ if `nbcov'!=0{
+ if `verifFrom'!=`nbtotmodacov'-`nbcov'+1+`nbdifftot'+`nbcovquant'{
+ noi di in red "Mismatch between the number of parameters to estimate and the number of provided parameters"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ else{
+ if `verifFrom'!=1+`nbdifftot'+`nbcovquant'{
+ noi di in red "Mismatch between the number of parameters to estimate and the number of provided parameters"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ }
+ gen `one'=1
+ su `one'
+ local Nbid=r(N)
+ collapse (sum) `wt'2=`one', by(`reponse'1-`reponse'`nbit' `categorical' `continuous')
+ gen `id'=_n
+ reshape long `reponse', i(`id') j(`item')
+ drop if `reponse'==.
+ ologit `reponse' [fweight=`wt'2]
+ local LLL00=e(ll)
+ tempname eBLLL00
+ matrix `eBLLL00'=e(b)
+ gen `obs'=_n
+ su `wt'2
+ local ddlssIII=r(sum)-1
+ forvalues i=1/`nbit'{
+ expand `moda`i'' if `item'==`i'
+ }
+ by `obs', sort: gen `x'=_n-1
+ gen `choix'=`reponse'==`x'
+ tab `item', gen(`it')
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ gen d_``i''_`g'=(-1)*`it'`i'*(`x'>=`g')
+ }
+ }
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ capture gen __dd_`g'=0
+ }
+ }
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace __dd_`g'=(-1)*`it'`i'*(`x'>=`g') if ((-1)*`it'`i'*(`x'>=`g'))<__dd_`g'
+ }
+ }
+ if "`difficulties'"!=""{
+ gen difficulties=0
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace difficulties=difficulties+``i''[1,`g']*d_``i''_`g'
+ }
+ }
+ }
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ gen `covverytemp'=``=`nbit'+`i'''
+ drop ``=`nbit'+`i'''
+ rename `covverytemp' ``=`nbit'+`i'''
+ tab ``=`nbit'+`i''', gen(``=`nbit'+`i'''__) matrow(`nom')
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ gen ``=`nbit'+`i'''__`k'_old=``=`nbit'+`i'''__`k'
+ order ``=`nbit'+`i'''__`k'_old, first
+ replace ``=`nbit'+`i'''__`k'=``=`nbit'+`i'''__`k'*`x'
+ local ident`i'_`k'=`nom'[`k',1]
+ if `k'==1 & `i'==1{
+ local ident1=`ident`i'_`k''
+ }
+ rename ``=`nbit'+`i'''__`k' ``=`nbit'+`i'''_`ident`i'_`k''
+ }
+ }
+ forvalues i=1/`nbcov'{
+ drop ``=`nbit'+`i'''
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=1/`nbcovquant'{
+ gen `covverytemp'=``=`nbit'+`nbcov'+`i'''*`x'
+ rename ``=`nbit'+`nbcov'+`i''' ``=`nbit'+`nbcov'+`i'''_old
+ rename `covverytemp' ``=`nbit'+`nbcov'+`i'''
+ }
+ }
+ rename `id' theta
+ rename `x' estimates
+ }
+ eq slope:estimates
+ gen obs=`obs'
+ gen choix=`choix'
+ gen wt=`wt'
+ local contrainte ""
+ local contrainteit ""
+ if "`rsm'"!="" & "`difficulties'"==""{
+ forvalues i=2/`nbit'{
+ forvalues j=2/`=`nbtotmodait'-1'{
+ constraint free
+ local con=r(free)
+ local contrainteit "`contrainteit' `con'"
+ constraint `con' d_`1'_`j'-d_`1'_1=d_``i''_`j'-d_``i''_1
+ }
+ }
+ }
+ local offset "offset(difficulties)"
+ local covariablesit ""
+ if "`difficulties'"==""{
+ local covariablesit "d_`1'_1-d_``nbit''_`=`moda`nbit''-1'"
+ local offset ""
+ }
+ local nbitdiffpara=0
+ forvalues i=1/`nbit'{
+ forvalues j=1/`=`moda`nbit''-1'{
+ local nbitdiffpara=`nbitdiffpara'+1
+ }
+ }
+ local covariables ""
+ if `nbcov'!=0{
+ local covariables "`covariables' ``=`nbit'+1''_`ident1'-``=`nbit'+`nbcov'''_`ident`nbcov'_`nbModCov`nbcov'''"
+ forvalues i=1/`nbcov'{
+ constraint free
+ local con=r(free)
+ local contrainte "`contrainte' `con'"
+ constraint `con' ``=`nbit'+`i'''_`ident`i'_1'=0
+ }
+ }
+ if `nbcovquant'!=0{
+ local covariables "`covariables' ``=`nbit'+`nbcov'+1''-``=`nbit'+`nbcov'+`nbcovquant'''"
+ }
+ tempname a
+ matrix `a'=(0,0)
+ local skipcopy "skip"
+ if "`difficulties'"==""{
+ if "`from'"!=""{
+ matrix `a'=`from'
+ local skipcopy "copy"
+ }
+ }
+ gen cons=estimates
+ local varcons ""
+ if "`difficulties'"!=""{
+ local varcons "cons"
+ }
+ /**********************/
+ /*Estimation du modĂšle*/
+ /**********************/
+
+ unab vars : `covariables' , min(0)
+ local _c1= `: word count `vars''
+ local _c2= `: word count `contrainte''
+ gllamm estimates `varcons' `covariablesit' `covariables' , `offset' i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' nodis constraint(`contrainteit' `contrainte') from(`a') `skipcopy' `NIP' `trace'
+ local convergeance=e(converged)
+ tempname eB eV
+ matrix `eB'=e(b)
+ local nbc=colsof(`eB')
+ matrix `eV'=e(V)
+ local nbpar=e(k)
+ local nbN=e(N)
+ local LLfull=e(ll)
+ local ccnn=e(cn)
+ local dfree_ModComp=`ddlssIII'-`=colsof(`eB')'+ wordcount("`contrainteit' `contrainte'")
+ local SS_ModComp=(`eB'[1,`=colsof(`eB')']^2)*`dfree_ModComp'
+ local dfree_ModSsCov=`dfree_ModComp'+`nbparcov'- wordcount("`contrainte'")
+ local ordre=`ordre'- wordcount("`contrainteit'")+1
+ if "`rsm'"!=""{
+ tempname tau
+ matrix `tau'=J(2,`=`moda1'-1',.)
+ forvalues i=2/`=`moda1'-1'{
+ qui lincom d_`1'_`i'-d_`1'_1
+ local tau`i'=r(estimate)
+ local setau`i'=r(se)
+ matrix `tau'[1,`i']=`tau`i''
+ matrix `tau'[2,`i']=`setau`i''
+ }
+ }
+
+ qui{
+ capture su difficulties
+ if _rc==0{
+ gen difficultiespost=difficulties
+ }
+ else{
+ gen difficultiespost=0
+ local indent=1
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace difficultiespost=difficultiespost+`eB'[1,`indent']*d_``i''_`g'
+ local indent=1+`indent'
+ }
+ }
+ }
+ /* Commande GLLAMM qui est responsable de génération de matrices résiduelles */
+ qui gllamm estimates cons , offset(difficultiespost) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons from(`eB') skip `NIP'
+ tempname eB_tot
+ matrix `eB_tot'=e(b)
+ local SS_ModSsCov=(`eB_tot'[1,`=colsof(`eB_tot')']^2)*`dfree_ModSsCov'
+ }
+ local mugauss=`eB_tot'[1,1]
+ local sdgauss=abs(`eB_tot'[1,2])
+ if "`estimateonly'"==""{
+ noi di in gr " "
+ if `nbcov'+`nbcovquant'!=0{
+ noi di "McFadden's pseudo R square and type III Sums of squares computation"
+ }
+ else{
+ noi di "McFadden's pseudo R square computation"
+ }
+
+ /**********************************************************/
+ /* ModÚle nul (juste intercept et effets aléatoires -> R2 */
+ /**********************************************************/
+
+ qui gllamm estimates __dd_* , i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' from(`a') skip `NIP'
+ local LLinterSS=e(ll)
+ tempname eB4
+ matrix `eB4'=e(b)
+ local R2Nag=1-(`LLfull'/`LLinterSS')
+
+ /*****************/
+ /* Calcul des SS */
+ /*****************/
+ qui{
+ local covariables2 ""
+ forvalues covs=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local covariables2 "`covariables2' ``covs''_`ident`=`covs'-`nbit''_1'-``covs''_`ident`=`covs'-`nbit''_`nbModCov`=`covs'-`nbit''''"
+ }
+ forvalues covs=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local covariables2 "`covariables2' ``covs''"
+ }
+ if `nbcov'+`nbcovquant'!=0{
+ forvalues covs=`=`nbit'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ noi di " for " in ye "``covs''" in gr " covariate"
+ if strpos("`categorical'","``covs''")!=0 & "``covs''"!=""{
+ local covsans= subinword("`covariables2'","``covs''_`ident`=`covs'-`nbit''_1'-``covs''_`ident`=`covs'-`nbit''_`nbModCov`=`covs'-`nbit''''","",.)
+ local dfree_Mss``covs''=`dfree_ModComp'+ `nbModCov`=`covs'-`nbit'''-1
+ }
+ else{
+ local covsans= subinword("`covariables2'","``covs''","",.)
+ local dfree_Mss``covs''=`dfree_ModComp'+1
+ }
+ capture constraint drop `contrainterep'
+ local contrainterep ""
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ if `=`nbit'+`i''!=`covs'{
+ constraint free
+ local con=r(free)
+ local contrainterep "`contrainterep' `con'"
+ constraint `con' ``=`nbit'+`i'''_`ident`i'_1'=0
+ }
+ }
+ }
+ gllamm estimates cons `covsans' , offset(difficultiespost) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' constraint(`contrainterep') from(`eB') skip `NIP'
+ tempname eB``covs''
+ matrix `eB``covs'''=e(b)
+ local SS_Mss``covs''=(`eB``covs'''[1,`=colsof(`eB``covs''')']^2)*`dfree_Mss``covs'''
+ local LLfullmoin=e(ll)
+ tempname eB4
+ matrix `eB4'=e(b)
+ local R2N_``covs''=1-(`LLfullmoin'/`LLinterSS')
+ tempname eB2
+ matrix `eB2'=e(b)
+ local nbpar2=e(k)
+ }
+ }
+ }
+ noi di in gr " "
+ }
+ di in gr ""
+ if "`rsm'"!=""{
+ di in gr "Model : " in ye "Rating Scale Model"
+ }
+ else{
+ di in gr "Model : " in ye "Partial Credit Model"
+ }
+ di in gr ""
+ di in gr " log likelihood: " in ye %-18.3f `LLfull'
+ local lll=e(ll)
+ if "`estimateonly'"==""{
+ di in gr " Marginal McFadden's pseudo R2: " in ye %-4.1f `=`R2Nag'*100' "%"
+ }
+ di in gr " Number of individuals: "in ye "`Nbid'"
+ di in gr " Number of items: "in ye "`nbit'"
+ if `=`nbcov'+`nbcovquant''!=0{
+ di in gr " Number of covariates: "in ye "`=`nbcov'+`nbcovquant''"
+ }
+ di in gr ""
+ di ""
+ di in gr "Parameters of the Latent trait distribution:"
+ di ""
+ local contrR ""
+ if "`difficulties'"==""{
+ if `=`nbcov'+`nbcovquant''!=0{
+ local subgroup0 ""
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ local subgroup0 "`subgroup0'``=`nbit'+`i''' = `ident`i'_1', "
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=1/`nbcovquant'{
+ local subgroup0 "`subgroup0'``=`nbit'+`nbcov'+`i''' = 0, "
+ }
+ }
+ local subgroup0b "`=reverse(subinstr(reverse("`subgroup0'"), ",", ":", 1))'"
+ local contrR "latent trait for `subgroup0b'"
+ }
+ else{
+
+ local contrR "overall latent trait mean "
+ }
+ di in gr " Identifiability constraint: `contrR'set to 0"
+ }
+ di in gr " Variance of the Latent trait: SigmaÂČ=" in ye %-8.3f (`=`=`eB'[1,`nbc']'')^2 in gr " (SE:"in ye %-8.3f `= sqrt((2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']' )' in gr ")"
+ local varTheta=(`=`=`eB'[1,`nbc']'')^2
+ local Varvartheta=(2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']'
+ di ""
+ if `nbcov'+`nbcovquant'!=0{
+ if "`estimateonly'"=="" & `=`nbcov'+`nbcovquant''>0 {
+ tempname VarExpSS
+ matrix `VarExpSS'=J(`=`nbcov'+`nbcovquant'+2',4,.)
+ local compte=1
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ matrix `VarExpSS'[`compte',1]=`SS_Mss``i'''-`SS_ModComp'
+ matrix `VarExpSS'[`compte',2]=`dfree_Mss``i'''-`dfree_ModComp'
+ matrix `VarExpSS'[`compte',3]=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ matrix `VarExpSS'[`compte',4]=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compte=`compte'+1
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ matrix `VarExpSS'[`compte',1]=`SS_Mss``i'''-`SS_ModComp'
+ matrix `VarExpSS'[`compte',2]=`dfree_Mss``i'''-`dfree_ModComp'
+ matrix `VarExpSS'[`compte',3]=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ matrix `VarExpSS'[`compte',4]=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compte=`compte'+1
+ }
+ }
+ matrix `VarExpSS'[`=`compte'',1]=`SS_ModSsCov'
+ matrix `VarExpSS'[`=`compte'',2]=`dfree_ModSsCov'
+ matrix `VarExpSS'[`=`compte'+1',1]=`SS_ModComp'
+ matrix `VarExpSS'[`=`compte'+1',2]=`dfree_ModComp'
+ }
+ if c(linesize)>=101{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 101}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]" _col(73) in gr "SS.III" _col(81) in gr "df" _col(85) in gr "V.exp." _col(95) in gr "R2.exp."
+ di in gr "{hline 101}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=.
+ local df=.
+ local vexp=.
+ local r2exp=.
+ if "`estimateonly'"==""{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ }
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':" _col(72) in ye %6.3f `ss3' _col(81) in ye %2.0f `df' _col(84) in ye %6.1f `vexp' "%" _col(94) in ye %6.1f `r2exp' "%"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 101}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=.
+ local df=.
+ local vexp=.
+ local r2exp=.
+ if "`estimateonly'"==""{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ }
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e'' _col(72) in ye %6.3f `ss3' _col(81) in ye %2.0f `df' _col(84) in ye %6.1f `vexp' "%" _col(94) in ye %6.1f `r2exp' "%"
+ }
+ di in gr "{hline 101}"
+ }
+ }
+ if "`difficulties'"!=""{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 101}"
+ }
+ local sssc=.
+ local dfsc=.
+ local ssac=.
+ local dfac=.
+ if "`estimateonly'"==""{
+ local sssc=`SS_ModSsCov'
+ local dfsc=`dfree_ModSsCov'
+ local ssac=`SS_ModComp'
+ local dfac=`dfree_ModComp'
+ }
+ di _col(73) in gr "SS.res" _col(84) in gr "df"
+ di _col(45) in gr "Model without covariates" _col(72) in ye %6.3f `sssc' _col(81) in ye %5.0f `dfsc'
+ di _col(59) in gr "Full model" _col(72) in ye %6.3f `ssac' _col(81) in ye %5.0f `dfac'
+ di in gr "{hline 101}"
+ di ""
+ }
+ else{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 66}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]"
+ di in gr "{hline 66}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if "`difficulties'"!=""{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 66}"
+ }
+ if "`estimateonly'"==""{
+ di ""
+ di "Proportion of latent trait variance explained by covariates"
+ di ""
+ di in gr "{hline 53}"
+ di _col(23) in gr "SS.III" _col(34) in gr "df" _col(38) in gr "V.exp." _col(47) in gr "R2.exp."
+ di in gr "{hline 53}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compteur=`compteur'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compteur=`compteur'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ di in gr "{hline 53}"
+ local sssc=`SS_ModSsCov'
+ local dfsc=`dfree_ModSsCov'
+ local ssac=`SS_ModComp'
+ local dfac=`dfree_ModComp'
+ di _col(23) in gr "SS.res" _col(34) in gr "df"
+ di _col(1) in gr "Model without cov." _col(22) in ye %6.3f `sssc' _col(31) in ye %5.0f `dfsc'
+ di _col(1) in gr "Full model" _col(22) in ye %6.3f `ssac' _col(31) in ye %5.0f `dfac'
+ di in gr "{hline 53}"
+ di ""
+ }
+ }
+ }
+ else if "`difficulties'"!=""{
+ di in gr "Latent trait distribution"
+ di in gr "{hline 80}"
+ di _col(18) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "z" _col(52) in gr "P>|z|" _col(61) in gr "[`level'% Conf. Interval]"
+ di in gr "{hline 80}"
+ di _col(1) in gr "Mu" _col(15) in ye %8.5f `=`eB'[1,1]' _col(27) in ye %8.5f `=sqrt(`eV'[1,1]) ' _col(39) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) '' _col(51) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) ')))' _col(61) in ye %8.5f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) '' _col(73) in ye %8.5f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) ''
+
+ di _col(1) in gr "Sigma" _col(15) in ye %8.5f `=abs(`eB'[1,`nbc'])' _col(27) in ye %8.5f `=sqrt(`=`eV'[`nbc',`nbc']')' _col(39) in ye %5.2f `=`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']')' _col(51) in ye %6.3f `=2*(1-normal(abs(`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']'))))' _col(61) in ye %8.5f `=`eB'[1,`nbc']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')' _col(73) in ye %8.5f `=`eB'[1,`nbc']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')'
+ di in gr "{hline 80}"
+ di ""
+ }
+ if "`difficulties'"==""{
+ di in gr "Items difficulty parameters:"
+ di ""
+ di in gr "{hline 52}"
+ di _col(1) in gr "Item" _col(21) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "[`level'% C.I.]" _col(66)
+ di in gr "{hline 52}"
+ local compteur=1
+ if "`rsm'"==""{
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'':"
+ forvalues g=1/`=`moda`i''-1'{
+ di _col(4) in gr "response: " in ye %-6.2g `=`rep__`i''[`=`g'+1',1]' _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+1
+ }
+ di in gr "{hline 52}"
+ }
+ di ""
+ }
+ else{
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'':" _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+`=`moda1'-1'
+ }
+ di in gr "{hline 52}"
+ forvalues i=2/`=`moda1'-1'{
+ di _col(1) in gr "tau`=`i'-1':" _col(20) in ye %6.3f `tau`i'' _col(29) in ye %6.3f `setau`i'' _col(38) in ye %6.3f `=`tau`i''-`=(1+`level'/100)/2'*`setau`i''' _col(47) in ye %6.3f `=`tau`i''+`=(1+`level'/100)/2'*`setau`i'''
+ }
+ di in gr "{hline 52}"
+ }
+ }
+ else{
+ di in gr "Items difficulty parameters: fixed for the analysis"
+ }
+
+ /*************************************/
+ /* ereturn */
+ /*************************************/
+
+ qui{
+ if "`difficulties'"==""{
+ tempname Varbeta Vardelta beta delta Vartheta theta
+ matrix `Varbeta'=`eV'
+ local Varsigma=`Varbeta'[`=colsof(`Varbeta')',`=colsof(`Varbeta')']
+ matrix `Vardelta'=`Varbeta'[1..`nbdifftotbis',1..`nbdifftotbis']
+ matrix `beta'=`eB'
+ local sigma=abs(`beta'[1,`=colsof(`beta')'])
+ matrix `delta'=`beta'[1,1..`nbdifftotbis']
+ if `=`nbcov'+`nbcovquant''!=0{
+ matrix `Vartheta'=`Varbeta'[`=`nbdifftotbis'+1'..`=colsof(`Varbeta')-1',`=`nbdifftotbis'+1'..`=colsof(`Varbeta')-1']
+ matrix `theta'=`beta'[1,`=`nbdifftotbis'+1'..`=colsof(`beta')-1']
+ }
+ else{
+ local thetas=0
+ local Varthetas=0
+ }
+ }
+ else{
+ if `=`nbcov'+`nbcovquant''!=0{
+ tempname Vartheta theta
+ matrix `Vartheta'=`eV'
+ local Varsigma=`Vartheta'[`=colsof(`Vartheta')',`=colsof(`Vartheta')']
+ matrix `Vartheta'=`Vartheta'[1..`=colsof(`Vartheta')-1',1..`=colsof(`Vartheta')-1']
+ matrix `theta'=`eB'
+ local sigma=abs(`theta'[1,`=colsof(`theta')'])
+ matrix `theta'=`theta'[1,1..`=colsof(`theta')-1']
+ }
+ else{
+ tempname theta Vtheta
+ matrix `theta'=`eB'
+ local sigma=abs(`theta'[1,`=colsof(`theta')'])
+ matrix `Vtheta'=`eV'
+ local Varsigma=`Vtheta'[`=colsof(`Vtheta')',`=colsof(`Vtheta')']
+ local thetas=`theta'[1,1]
+ local varthetas=`Vtheta'[1,1]
+ }
+ }
+ ereturn clear
+ if `=`nbcov'+`nbcovquant''!=0{
+ matrix b=`eB'
+ matrix V=`eV'
+ ereturn post b V, depname(theta)
+ ereturn matrix theta=`theta'
+ ereturn matrix Vartheta=`Vartheta'
+ }
+ else{
+ if "`difficulties'"==""{
+ matrix V=`eV'
+ tempname thetatemp Varthetatemp
+ matrix `thetatemp'=(0)
+ matrix `Varthetatemp'=(0)
+ matrix coleq `Varthetatemp'=estimates
+ matrix coln `Varthetatemp'=mu
+ matrix roweq `Varthetatemp'=estimates
+ matrix rown `Varthetatemp'=mu
+ matrix b=`eB'
+ matrix coleq `thetatemp'=estimates
+ matrix coln `thetatemp'=mu
+ matrix rown `thetatemp'=y1
+ ereturn post b V, depname(theta)
+ ereturn matrix theta=`thetatemp'
+ ereturn matrix Vartheta=`Varthetatemp'
+ }
+ else{
+ tempname thetatemp Varthetatemp
+ matrix `Varthetatemp'=(`varthetas')
+ matrix coleq `Varthetatemp'=estimates
+ matrix coln `Varthetatemp'=mu
+ matrix roweq `Varthetatemp'=estimates
+ matrix rown `Varthetatemp'=mu
+ matrix `thetatemp'=(`thetas')
+ matrix coleq `thetatemp'=estimates
+ matrix coln `thetatemp'=mu
+ matrix rown `thetatemp'=y1
+ matrix V=`eV'
+ matrix b=`eB'
+ ereturn post b V, depname(theta)
+ tempname vvvt vvvVt
+ matrix `vvvt'=(`thetas')
+ matrix `vvvVt'=(`varthetas')
+ ereturn matrix theta=`vvvt'
+ ereturn matrix Vartheta=`vvvVt'
+ }
+ }
+ ereturn scalar ll=`LLfull'
+ ereturn scalar cn=`ccnn'
+ ereturn scalar r2=`R2Nag'
+ ereturn scalar N=`Nbid'
+ ereturn scalar Nit=`nbit'
+ ereturn scalar converged=`convergeance'
+ ereturn scalar ndtb=`nbdifftotbis'
+ ereturn scalar mugauss=`mugauss'
+ ereturn scalar sdgauss=`sdgauss'
+ if "`nip'"!=""{
+ ereturn scalar nip=`nip'
+ }
+ ereturn local items `varlist'
+ ereturn local categorical `categorical'
+ ereturn local continuous `continuous'
+ ereturn local estimateonly `estimateonly'
+ ereturn local constr `contrR'
+ ereturn local difficulties `difficulties'
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ``i''_m ""
+ forvalues k=1/`nbModCov`=`i'-`nbit'''{
+ local ``i''_m "```i''_m' `ident`=`i'-`nbit''_`k''"
+ ereturn local ``i'' ```i''_m'
+ }
+ }
+ }
+ ereturn local rsm `rsm'
+ ereturn local from `from'
+ ereturn local robust `robust'
+ ereturn local adapt `adapt'
+ ereturn local iterate `iterate'
+ ereturn local itest `itest'
+ ereturn local datatest `bddinib'
+ ereturn local if `if'
+ ereturn local in `in'
+ ereturn local cmd "pcmodel"
+ ereturn scalar order=`ordre'
+ if `=`nbcov'+`nbcovquant''!=0{
+ ereturn scalar Ncat=`nbcov'
+ ereturn scalar Ncont=`nbcovquant'
+ }
+ if "`difficulties'"==""{
+ ereturn matrix Vardelta=`Vardelta'
+ ereturn matrix delta=`delta'
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ if "`rsm'"!=""{
+ ereturn matrix Tau=`tau'
+ }
+ }
+ else{
+ if `=`nbcov'+`nbcovquant''!=0{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ }
+ else{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varvartheta'
+ }
+ }
+ if "`estimateonly'"=="" & `=`nbcov'+`nbcovquant''>0 {
+ ereturn matrix VarExpSS `VarExpSS'
+ }
+ }
+use `bddinip', replace
+}
+restore
+end
diff --git a/Modules/ado/personal/p/pcmodel_v.ado b/Modules/ado/personal/p/pcmodel_v.ado
new file mode 100644
index 0000000..3228fd1
--- /dev/null
+++ b/Modules/ado/personal/p/pcmodel_v.ado
@@ -0,0 +1,1140 @@
+/********************************************************************************/
+/* v1.1 : Bug fixed regarding the estimation of the latent trait standard error */
+/* v2 : Bugs with temporary names fixed, New options have been added, */
+/* modifications of the output */
+/********************************************************************************/
+
+program define pcmodel, eclass
+version 11.0
+syntax [varlist] [if] [in] [, CATegorical(string) CONTinuous(string) DIFficulties(string) ITerate(string) ADapt RObust From(string) RSM ESTimateonly nip(string) TRace Level(string)]
+
+preserve
+tempfile bddinip
+qui save `bddinip',replace
+local Cond=0
+
+if "`level'"==""{
+ local level=c(level)
+}
+
+
+if replay() {
+ capture local cmdavant=e(cmd)
+ if _rc!=0 | "`cmdavant'"!="pcmodel"{
+ noi di in red "pcmodel was not the last command"
+ error 100
+ }
+ if "`categorical'`continuous'`difficulties'`iterate'`adapt'`robust'`from'`rsm'`estimateonly'`nip'"==""{
+ local rsm=e(rsm)
+ local LLfull=e(ll)
+ local estimateonly=e(estimateonly)
+ local R2Nag=e(r2)
+ local Nbid=e(N)
+ local nbit=e(Nit)
+ local categorical=e(categorical)
+ local continuous=e(continuous)
+ if "`continuous'"=="."{
+ local continuous=""
+ }
+ if "`categorical'"=="."{
+ local categorical=""
+ }
+ local nbcov: word count `categorical'
+ local nbcovquant: word count `continuous'
+ local varlist=e(items)
+ tokenize `varlist' `categorical' `continuous'
+ local difficulties=e(difficulties)
+ local contrR=e(constr)
+ tempname eB eV VarExpSS
+ matrix `eB'=e(b)
+ matrix `eV'=e(V)
+ matrix `VarExpSS'=e(VarExpSS)
+ local nbc=colsof(`eB')
+ local nbdifftotbis=e(ndtb)
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ``i''_m=e(``i'')
+ local k=1
+ local nbModCov`=`i'-`nbit''=wordcount("```i''_m'")
+ foreach m in ```i''_m'{
+ local ident`=`i'-`nbit''_`k'=`m'
+ local k=`k'+1
+ }
+ }
+ }
+ if "`rsm'"!="."{
+ di in gr "Model : " in ye "Rating Scale Model"
+ }
+ else{
+ di in gr "Model : " in ye "Partial Credit Model"
+ }
+ di in gr ""
+ di in gr " log likelihood: " in ye %-18.3f `LLfull'
+ if "`estimateonly'"=="."{
+ di in gr " Marginal McFadden's pseudo R2: " in ye %-4.1f `=`R2Nag'*100' "%"
+ }
+ di in gr " Number of individuals: "in ye "`Nbid'"
+ di in gr " Number of items: "in ye "`nbit'"
+ if `=`nbcov'+`nbcovquant''!=0{
+ di in gr " Number of covariates: "in ye "`=`nbcov'+`nbcovquant''"
+ }
+ di in gr ""
+ di ""
+ di in gr "Parameters of the Latent trait distribution:"
+ di ""
+ if "`difficulties'"=="."{
+ di in gr " Identifiability constraint: `contrR'set to 0"
+ }
+ di in gr " Variance of the Latent trait: SigmaÂČ=" in ye %-8.3f (`=`=`eB'[1,`nbc']'')^2 in gr " (SE:"in ye %-8.3f `= sqrt((2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']' )' in gr ")"
+ local varTheta=(`=`=`eB'[1,`nbc']'')^2
+ local Varvartheta=(2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']'
+ di ""
+ if `nbcov'+`nbcovquant'!=0{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 66}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]"
+ di in gr "{hline 66}"
+ local compteur=1
+ if "`difficulties'"=="."{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if "`difficulties'"!="."{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 66}"
+ }
+ if "`estimateonly'"=="."{
+ di ""
+ di "Proportion of latent trait variance explained by covariates"
+ di ""
+ di in gr "{hline 53}"
+ di _col(23) in gr "SS.III" _col(34) in gr "df" _col(38) in gr "V.exp." _col(47) in gr "R2.exp."
+ di in gr "{hline 53}"
+ local compteur=1
+ if "`difficulties'"=="."{
+ local compteur=`nbdifftotbis'
+ }
+ local compte=1
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=`VarExpSS'[`compte',1]
+ local df=`VarExpSS'[`compte',2]
+ local vexp=`VarExpSS'[`compte',3]
+ local r2exp=`VarExpSS'[`compte',4]
+ local compteur=`compteur'+1
+ local compte=`compte'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=`VarExpSS'[`compte',1]
+ local df=`VarExpSS'[`compte',2]
+ local vexp=`VarExpSS'[`compte',3]
+ local r2exp=`VarExpSS'[`compte',4]
+ local compteur=`compteur'+1
+ local compte=`compte'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ di in gr "{hline 53}"
+ local sssc=`VarExpSS'[`=`compte'',1]
+ local dfsc=`VarExpSS'[`=`compte'',2]
+ local ssac=`VarExpSS'[`=`compte'+1',1]
+ local dfac=`VarExpSS'[`=`compte'+1',2]
+ di _col(23) in gr "SS.res" _col(34) in gr "df"
+ di _col(1) in gr "Model without cov." _col(22) in ye %6.3f `sssc' _col(31) in ye %5.0f `dfsc'
+ di _col(1) in gr "Full model" _col(22) in ye %6.3f `ssac' _col(31) in ye %5.0f `dfac'
+ di in gr "{hline 53}"
+ di ""
+ }
+ }
+ else if "`difficulties'"!="."{
+ di in gr "Latent trait distribution"
+ di in gr "{hline 80}"
+ di _col(18) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "z" _col(52) in gr "P>|z|" _col(61) in gr "[`level'% Conf. Interval]"
+ di in gr "{hline 80}"
+ di _col(1) in gr "Mu" _col(15) in ye %8.5f `=`eB'[1,1]' _col(27) in ye %8.5f `=sqrt(`eV'[1,1]) ' _col(39) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) '' _col(51) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) ')))' _col(61) in ye %8.5f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) '' _col(73) in ye %8.5f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) ''
+
+ di _col(1) in gr "Sigma" _col(15) in ye %8.5f `=abs(`eB'[1,`nbc'])' _col(27) in ye %8.5f `=sqrt(`=`eV'[`nbc',`nbc']')' _col(39) in ye %5.2f `=`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']')' _col(51) in ye %6.3f `=2*(1-normal(abs(`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']'))))' _col(61) in ye %8.5f `=`eB'[1,`nbc']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')' _col(73) in ye %8.5f `=`eB'[1,`nbc']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')'
+ di in gr "{hline 80}"
+ di ""
+ }
+ if "`difficulties'"=="."{
+ di in gr "Items difficulty parameters:"
+ di ""
+ di in gr "{hline 52}"
+ di _col(1) in gr "Item" _col(21) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "[`level'% C.I.]" _col(66)
+ di in gr "{hline 52}"
+ local compteur=1
+ if "`rsm'"=="."{
+ forvalues i=1/`nbit'{
+
+ tempname rep__`i'
+ qui tab ``i'', matrow(`rep__`i'')
+ local moda`i'=`=r(r)'
+ di _col(1) in gr "``i'':"
+ forvalues g=1/`=`moda`i''-1'{
+ di _col(4) in gr "response: " in ye %-6.2g `=`rep__`i''[`=`g'+1',1]' _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+1
+ }
+ di in gr "{hline 52}"
+ }
+ di ""
+ }
+ else{
+ tempname tau
+ matrix `tau'=e(Tau)
+ forvalues i=1/`nbit'{
+ tempname rep__`i'
+ qui tab ``i'', matrow(`rep__`i'')
+ local moda`i'=`=r(r)'
+ di _col(1) in gr "``i'':" _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+`=`moda1'-1'
+ }
+ di in gr "{hline 52}"
+ forvalues i=2/`=`moda1'-1'{
+ di _col(1) in gr "tau`=`i'-1':" _col(20) in ye %6.3f `=`tau'[1,`i']' _col(29) in ye %6.3f `=`tau'[2,`i']' _col(38) in ye %6.3f `=`=`tau'[1,`i']'-`=(1+`level'/100)/2'*`=`tau'[2,`i']'' _col(47) in ye %6.3f `=`=`tau'[1,`i']'+`=(1+`level'/100)/2'*`=`tau'[2,`i']''
+ }
+ di in gr "{hline 52}"
+ }
+ }
+ else{
+ di in gr "Items difficulty parameters: fixed for the analysis"
+ }
+ }
+ else{
+ local Cond=1
+ local varlist=e(items)
+ if "`categorical'"=="" & "`=e(categorical)'"!="."{
+ local categorical=e(categorical)
+ }
+ if "`continuous'"=="" & "`=e(continuous)'"!="."{
+ local continuous=e(continuous)
+ }
+ if "`difficulties'"=="" & "`=e(difficulties)'"!="."{
+ local difficulties=e(difficulties)
+ }
+ if "`iterate'"=="" & "`=e(iterate)'"!="."{
+ local iterate=e(iterate)
+ }
+ if "`adapt'"=="" & "`=e(adapt)'"!="."{
+ local adapt=e(adapt)
+ }
+ if "`robust'"=="" & "`=e(robust)'"!="."{
+ local robust=e(robust)
+ }
+ if "`from'"=="" & "`=e(from)'"!="."{
+ local from=e(from)
+ }
+ if "`rsm'"=="" & "`=e(rsm)'"!="."{
+ local rsm=e(rsm)
+ }
+ if "`estimateonly'"=="" & "`=e(estimateonly)'"!="."{
+ local estimateonly=e(estimateonly)
+ }
+ }
+}
+else{
+ local Cond=1
+}
+if `Cond'==1{
+ tokenize `varlist' `categorical' `continuous'
+ local nbit: word count `varlist'
+ local nbcov: word count `categorical'
+ local nbcovquant: word count `continuous'
+ local nbit2:word count `difficulties'
+ local NIP ""
+ if "`nip'"!=""{
+ local NIP "nip(`nip')"
+ }
+ tempname nom val
+ if `nbit2'==0{
+ local itest=1
+ }
+ else{
+ local itest=0
+ }
+ if "`from'"!=""{
+ local verifFrom=colsof(`from')
+ }
+ tempfile bddini bddinib
+ qui{
+ marksample touse,novarlist
+ keep if `touse'
+ local ordre=0
+ forvalues i=1/`nbit'{
+ tempname rep__`i'
+ tab ``i'', matrow(`rep__`i'')
+ local ordre=`ordre'+`=rowsof(`rep__`i'')'-1
+ forvalues j=1/`=rowsof(`rep__`i'')'{
+ replace ``i''=`j'-1 if ``i''==`rep__`i''[`j',1]
+ }
+ }
+ save `bddinib',replace
+ q memory
+ }
+ local matsizeini=r(matsize)
+ if "`rsm'"!=""{
+ local nbtotmodait=rowsof(`rep__1')
+ forvalues i=2/`nbit'{
+ if `=rowsof(`rep__`i'')'!=`nbtotmodait'{
+ noi di in red "The number of item response categories must be equal for each item when using Rating Scale models"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ if "`difficulties'"!=""{
+ noi di in red "RSM option only available for unknow difficulties"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ if "`from'"!=""{
+ if "`difficulties'"!=""{
+ noi di in red "From option only available for unknow difficulties"
+ use `bddinip',replace
+ error 100
+ }
+ if "`rsm'"!=""{
+ noi di in red "From option only available for the Partial Credit model"
+ use `bddinip',replace
+ error 100
+ }
+ }
+
+ /*************************************/
+ /* Verifications */
+ /*************************************/
+
+ if "`iterate'"==""{
+ local it=""
+ }
+ else{
+ local iterateII="it(`iterate')"
+ }
+ tempvar one id item reponse obs wt x choix it covariable covverytemp
+ qui save `bddinib', replace
+ if "`difficulties'"!=""{
+ if `nbit2'!=`nbit'{
+ noi di in red "Not the same number of difficulty vectors and of items"
+ use `bddinip',replace
+ error 100
+ }
+ forvalues i=1/`nbit'{
+ if strpos("`varlist'",word("`difficulties'",`i'))==0{
+ noi di in red "The item difficulty vectors must have the same names than the item variables"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ }
+ /*************************************/
+ /* Estimation of the parameters */
+ /*************************************/
+ local nbtotmodacov=0
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ qui tab ``=`nbit'+`i''', matrow(`nom') matcell(`val')
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ local valmod`k'cov`i'=`nom'[`k',1]
+ local nbmod`k'cov`i'=`val'[`k',1]
+ }
+ local nbtotmodacov=`nbtotmodacov'+`nbModCov`i''
+ if `nbModCov`i''>15{
+ noi di in ye "Are you sure that ``=`nbit'+`i''' is a categorical variable? (``=`nbit'+`i''' has `nbModCov`i'' categories)"
+ noi di in gr ""
+ }
+ local tot`i'=r(N)
+ forvalues k=1/`nbModCov`i''{
+ local sum=0
+ forvalues k2=1/`nbModCov`i''{
+ if `k2'!=`k'{
+ local sum=`sum'+`val'[`k2',1]
+ }
+ }
+ local a`i'_`k'=round((`sum'-`tot`i'')/`tot`i'',0.01)
+ local b`i'_`k'=round((`sum')/`tot`i'',0.01)
+ }
+ }
+ }
+ local nbparcov=`nbtotmodacov'+`nbcovquant'
+ qui{
+ keep `varlist' `categorical' `continuous'
+ local nbdifftotbis=0
+ local nbdifftot=0
+ if "`difficulties'"=="" & "`rsm'"==""{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ tab `reponse'`i'
+ local moda`i'=`=r(r)'
+ local nbdifftot=`nbdifftot'+`moda`i''-1
+ local nbdifftotbis=`nbdifftotbis'+`moda`i''-1
+ }
+ }
+ else if "`difficulties'"=="" & "`rsm'"!=""{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ tab `reponse'`i'
+ local moda`i'=`=r(r)'
+ local nbdifftot=`nbdifftot'+1
+ local nbdifftotbis=`nbdifftotbis'+`moda`i''-1
+ }
+ local nbdifftot=`nbdifftot'+`nbtotmodait'-2
+ }
+ else{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ local moda`i'=colsof(``i'')+1
+ }
+ }
+ if "`from'"!=""{
+ if `nbcov'!=0{
+ if `verifFrom'!=`nbtotmodacov'-`nbcov'+1+`nbdifftot'+`nbcovquant'{
+ noi di in red "Mismatch between the number of parameters to estimate and the number of provided parameters"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ else{
+ if `verifFrom'!=1+`nbdifftot'+`nbcovquant'{
+ noi di in red "Mismatch between the number of parameters to estimate and the number of provided parameters"
+ use `bddinip',replace
+ error 100
+ }
+ }
+ }
+ gen `one'=1
+ su `one'
+ local Nbid=r(N)
+ collapse (sum) `wt'2=`one', by(`reponse'1-`reponse'`nbit' `categorical' `continuous')
+ gen `id'=_n
+ reshape long `reponse', i(`id') j(`item')
+ drop if `reponse'==.
+ ologit `reponse' [fweight=`wt'2]
+ local LLL00=e(ll)
+ tempname eBLLL00
+ matrix `eBLLL00'=e(b)
+ gen `obs'=_n
+ su `wt'2
+ local ddlssIII=r(sum)-1
+ forvalues i=1/`nbit'{
+ expand `moda`i'' if `item'==`i'
+ }
+ by `obs', sort: gen `x'=_n-1
+ gen `choix'=`reponse'==`x'
+ tab `item', gen(`it')
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ gen d_``i''_`g'=(-1)*`it'`i'*(`x'>=`g')
+ }
+ }
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ capture gen __dd_`g'=0
+ }
+ }
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace __dd_`g'=(-1)*`it'`i'*(`x'>=`g') if ((-1)*`it'`i'*(`x'>=`g'))<__dd_`g'
+ }
+ }
+ if "`difficulties'"!=""{
+ gen difficulties=0
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace difficulties=difficulties+``i''[1,`g']*d_``i''_`g'
+ }
+ }
+ }
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ gen `covverytemp'=``=`nbit'+`i'''
+ drop ``=`nbit'+`i'''
+ rename `covverytemp' ``=`nbit'+`i'''
+ tab ``=`nbit'+`i''', gen(``=`nbit'+`i'''__) matrow(`nom')
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ gen ``=`nbit'+`i'''__`k'_old=``=`nbit'+`i'''__`k'
+ order ``=`nbit'+`i'''__`k'_old, first
+ replace ``=`nbit'+`i'''__`k'=``=`nbit'+`i'''__`k'*`x'
+ local ident`i'_`k'=`nom'[`k',1]
+ if `k'==1 & `i'==1{
+ local ident1=`ident`i'_`k''
+ }
+ rename ``=`nbit'+`i'''__`k' ``=`nbit'+`i'''_`ident`i'_`k''
+ }
+ }
+ forvalues i=1/`nbcov'{
+ drop ``=`nbit'+`i'''
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=1/`nbcovquant'{
+ gen `covverytemp'=``=`nbit'+`nbcov'+`i'''*`x'
+ rename ``=`nbit'+`nbcov'+`i''' ``=`nbit'+`nbcov'+`i'''_old
+ rename `covverytemp' ``=`nbit'+`nbcov'+`i'''
+ }
+ }
+ rename `id' theta
+ rename `x' estimates
+ }
+ eq slope:estimates
+ gen obs=`obs'
+ gen choix=`choix'
+ gen wt=`wt'
+ local contrainte ""
+ local contrainteit ""
+ if "`rsm'"!="" & "`difficulties'"==""{
+ forvalues i=2/`nbit'{
+ forvalues j=2/`=`nbtotmodait'-1'{
+ constraint free
+ local con=r(free)
+ local contrainteit "`contrainteit' `con'"
+ constraint `con' d_`1'_`j'-d_`1'_1=d_``i''_`j'-d_``i''_1
+ }
+ }
+ }
+ local offset "offset(difficulties)"
+ local covariablesit ""
+ if "`difficulties'"==""{
+ local covariablesit "d_`1'_1-d_``nbit''_`=`moda`nbit''-1'"
+ local offset ""
+ }
+ local nbitdiffpara=0
+ forvalues i=1/`nbit'{
+ forvalues j=1/`=`moda`nbit''-1'{
+ local nbitdiffpara=`nbitdiffpara'+1
+ }
+ }
+ local covariables ""
+ if `nbcov'!=0{
+ local covariables "`covariables' ``=`nbit'+1''_`ident1'-``=`nbit'+`nbcov'''_`ident`nbcov'_`nbModCov`nbcov'''"
+ forvalues i=1/`nbcov'{
+ constraint free
+ local con=r(free)
+ local contrainte "`contrainte' `con'"
+ constraint `con' ``=`nbit'+`i'''_`ident`i'_1'=0
+ }
+ }
+ if `nbcovquant'!=0{
+ local covariables "`covariables' ``=`nbit'+`nbcov'+1''-``=`nbit'+`nbcov'+`nbcovquant'''"
+ }
+ tempname a
+ matrix `a'=(0,0)
+ local skipcopy "skip"
+ if "`difficulties'"==""{
+ if "`from'"!=""{
+ matrix `a'=`from'
+ local skipcopy "copy"
+ }
+ }
+ gen cons=estimates
+ local varcons ""
+ if "`difficulties'"!=""{
+ local varcons "cons"
+ }
+ /**********************/
+ /*Estimation du modĂšle*/
+ /**********************/
+
+ unab vars : `covariables' , min(0)
+ local _c1= `: word count `vars''
+ local _c2= `: word count `contrainte''
+ gllamm estimates `varcons' `covariablesit' `covariables' , `offset' i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' nodis constraint(`contrainteit' `contrainte') from(`a') `skipcopy' `NIP' `trace'
+ local convergeance=e(converged)
+ tempname eB eV
+ matrix `eB'=e(b)
+ local nbc=colsof(`eB')
+ matrix `eV'=e(V)
+ local nbpar=e(k)
+ local nbN=e(N)
+ local LLfull=e(ll)
+ local ccnn=e(cn)
+ local dfree_ModComp=`ddlssIII'-`=colsof(`eB')'+ wordcount("`contrainteit' `contrainte'")
+ local SS_ModComp=(`eB'[1,`=colsof(`eB')']^2)*`dfree_ModComp'
+ local dfree_ModSsCov=`dfree_ModComp'+`nbparcov'- wordcount("`contrainte'")
+ local ordre=`ordre'- wordcount("`contrainteit'")+1
+ if "`rsm'"!=""{
+ tempname tau
+ matrix `tau'=J(2,`=`moda1'-1',.)
+ forvalues i=2/`=`moda1'-1'{
+ qui lincom d_`1'_`i'-d_`1'_1
+ local tau`i'=r(estimate)
+ local setau`i'=r(se)
+ matrix `tau'[1,`i']=`tau`i''
+ matrix `tau'[2,`i']=`setau`i''
+ }
+ }
+
+ qui{
+ capture su difficulties
+ if _rc==0{
+ gen difficultiespost=difficulties
+ }
+ else{
+ gen difficultiespost=0
+ local indent=1
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace difficultiespost=difficultiespost+`eB'[1,`indent']*d_``i''_`g'
+ local indent=1+`indent'
+ }
+ }
+ }
+ /* Commande GLLAMM qui est responsable de génération de matrices résiduelles */
+ qui gllamm estimates cons , offset(difficultiespost) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons from(`eB') skip `NIP'
+ tempname eB_tot
+ matrix `eB_tot'=e(b)
+ local SS_ModSsCov=(`eB_tot'[1,`=colsof(`eB_tot')']^2)*`dfree_ModSsCov'
+ }
+ local mugauss=`eB_tot'[1,1]
+ local sdgauss=abs(`eB_tot'[1,2])
+ if "`estimateonly'"==""{
+ noi di in gr " "
+ if `nbcov'+`nbcovquant'!=0{
+ noi di "McFadden's pseudo R square and type III Sums of squares computation"
+ }
+ else{
+ noi di "McFadden's pseudo R square computation"
+ }
+
+ /**********************************************************/
+ /* ModÚle nul (juste intercept et effets aléatoires -> R2 */
+ /**********************************************************/
+
+ qui gllamm estimates __dd_* , i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' from(`a') skip `NIP'
+ local LLinterSS=e(ll)
+ tempname eB4
+ matrix `eB4'=e(b)
+ local R2Nag=1-(`LLfull'/`LLinterSS')
+
+ /*****************/
+ /* Calcul des SS */
+ /*****************/
+ qui{
+ local covariables2 ""
+ forvalues covs=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local covariables2 "`covariables2' ``covs''_`ident`=`covs'-`nbit''_1'-``covs''_`ident`=`covs'-`nbit''_`nbModCov`=`covs'-`nbit''''"
+ }
+ forvalues covs=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local covariables2 "`covariables2' ``covs''"
+ }
+ if `nbcov'+`nbcovquant'!=0{
+ forvalues covs=`=`nbit'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ noi di " for " in ye "``covs''" in gr " covariate"
+ if strpos("`categorical'","``covs''")!=0 & "``covs''"!=""{
+ local covsans= subinword("`covariables2'","``covs''_`ident`=`covs'-`nbit''_1'-``covs''_`ident`=`covs'-`nbit''_`nbModCov`=`covs'-`nbit''''","",.)
+ local dfree_Mss``covs''=`dfree_ModComp'+ `nbModCov`=`covs'-`nbit'''-1
+ }
+ else{
+ local covsans= subinword("`covariables2'","``covs''","",.)
+ local dfree_Mss``covs''=`dfree_ModComp'+1
+ }
+ capture constraint drop `contrainterep'
+ local contrainterep ""
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ if `=`nbit'+`i''!=`covs'{
+ constraint free
+ local con=r(free)
+ local contrainterep "`contrainterep' `con'"
+ constraint `con' ``=`nbit'+`i'''_`ident`i'_1'=0
+ }
+ }
+ }
+ gllamm estimates cons `covsans' , offset(difficultiespost) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' constraint(`contrainterep') from(`eB') skip `NIP'
+ tempname eB``covs''
+ matrix `eB``covs'''=e(b)
+ local SS_Mss``covs''=(`eB``covs'''[1,`=colsof(`eB``covs''')']^2)*`dfree_Mss``covs'''
+ local LLfullmoin=e(ll)
+ tempname eB4
+ matrix `eB4'=e(b)
+ local R2N_``covs''=1-(`LLfullmoin'/`LLinterSS')
+ tempname eB2
+ matrix `eB2'=e(b)
+ local nbpar2=e(k)
+ }
+ }
+ }
+ noi di in gr " "
+ }
+ di in gr ""
+ if "`rsm'"!=""{
+ di in gr "Model : " in ye "Rating Scale Model"
+ }
+ else{
+ di in gr "Model : " in ye "Partial Credit Model"
+ }
+ di in gr ""
+ di in gr " log likelihood: " in ye %-18.3f `LLfull'
+ local lll=e(ll)
+ if "`estimateonly'"==""{
+ di in gr " Marginal McFadden's pseudo R2: " in ye %-4.1f `=`R2Nag'*100' "%"
+ }
+ di in gr " Number of individuals: "in ye "`Nbid'"
+ di in gr " Number of items: "in ye "`nbit'"
+ if `=`nbcov'+`nbcovquant''!=0{
+ di in gr " Number of covariates: "in ye "`=`nbcov'+`nbcovquant''"
+ }
+ di in gr ""
+ di ""
+ di in gr "Parameters of the Latent trait distribution:"
+ di ""
+ local contrR ""
+ if "`difficulties'"==""{
+ if `=`nbcov'+`nbcovquant''!=0{
+ local subgroup0 ""
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ local subgroup0 "`subgroup0'``=`nbit'+`i''' = `ident`i'_1', "
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=1/`nbcovquant'{
+ local subgroup0 "`subgroup0'``=`nbit'+`nbcov'+`i''' = 0, "
+ }
+ }
+ local subgroup0b "`=reverse(subinstr(reverse("`subgroup0'"), ",", ":", 1))'"
+ local contrR "latent trait for `subgroup0b'"
+ }
+ else{
+
+ local contrR "overall latent trait mean "
+ }
+ di in gr " Identifiability constraint: `contrR'set to 0"
+ }
+ di in gr " Variance of the Latent trait: SigmaÂČ=" in ye %-8.3f (`=`=`eB'[1,`nbc']'')^2 in gr " (SE:"in ye %-8.3f `= sqrt((2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']' )' in gr ")"
+ local varTheta=(`=`=`eB'[1,`nbc']'')^2
+ local Varvartheta=(2*`=`eB'[1,`nbc']')^2 *`=`eV'[`nbc',`nbc']'
+ di ""
+ if `nbcov'+`nbcovquant'!=0{
+ if "`estimateonly'"=="" & `=`nbcov'+`nbcovquant''>0 {
+ tempname VarExpSS
+ matrix `VarExpSS'=J(`=`nbcov'+`nbcovquant'+2',4,.)
+ local compte=1
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ matrix `VarExpSS'[`compte',1]=`SS_Mss``i'''-`SS_ModComp'
+ matrix `VarExpSS'[`compte',2]=`dfree_Mss``i'''-`dfree_ModComp'
+ matrix `VarExpSS'[`compte',3]=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ matrix `VarExpSS'[`compte',4]=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compte=`compte'+1
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ matrix `VarExpSS'[`compte',1]=`SS_Mss``i'''-`SS_ModComp'
+ matrix `VarExpSS'[`compte',2]=`dfree_Mss``i'''-`dfree_ModComp'
+ matrix `VarExpSS'[`compte',3]=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ matrix `VarExpSS'[`compte',4]=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compte=`compte'+1
+ }
+ }
+ matrix `VarExpSS'[`=`compte'',1]=`SS_ModSsCov'
+ matrix `VarExpSS'[`=`compte'',2]=`dfree_ModSsCov'
+ matrix `VarExpSS'[`=`compte'+1',1]=`SS_ModComp'
+ matrix `VarExpSS'[`=`compte'+1',2]=`dfree_ModComp'
+ }
+ if c(linesize)>=101{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 101}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]" _col(73) in gr "SS.III" _col(81) in gr "df" _col(85) in gr "V.exp." _col(95) in gr "R2.exp."
+ di in gr "{hline 101}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=.
+ local df=.
+ local vexp=.
+ local r2exp=.
+ if "`estimateonly'"==""{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ }
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':" _col(72) in ye %6.3f `ss3' _col(81) in ye %2.0f `df' _col(84) in ye %6.1f `vexp' "%" _col(94) in ye %6.1f `r2exp' "%"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 101}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=.
+ local df=.
+ local vexp=.
+ local r2exp=.
+ if "`estimateonly'"==""{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ }
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e'' _col(72) in ye %6.3f `ss3' _col(81) in ye %2.0f `df' _col(84) in ye %6.1f `vexp' "%" _col(94) in ye %6.1f `r2exp' "%"
+ }
+ di in gr "{hline 101}"
+ }
+ }
+ if "`difficulties'"!=""{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 101}"
+ }
+ local sssc=.
+ local dfsc=.
+ local ssac=.
+ local dfac=.
+ if "`estimateonly'"==""{
+ local sssc=`SS_ModSsCov'
+ local dfsc=`dfree_ModSsCov'
+ local ssac=`SS_ModComp'
+ local dfac=`dfree_ModComp'
+ }
+ di _col(73) in gr "SS.res" _col(84) in gr "df"
+ di _col(45) in gr "Model without covariates" _col(72) in ye %6.3f `sssc' _col(81) in ye %5.0f `dfsc'
+ di _col(59) in gr "Full model" _col(72) in ye %6.3f `ssac' _col(81) in ye %5.0f `dfac'
+ di in gr "{hline 101}"
+ di ""
+ }
+ else{
+ di in gr "Latent trait group effect:"
+ di ""
+ di in gr "{hline 66}"
+ di _col(20) in gr "Coef." _col(30) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(57) in gr "[`level'% C.I.]"
+ di in gr "{hline 66}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``i'':"
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_1'" _col(24) in ye "0" _col(33) in ye "." _col(41) in ye "." _col(49) in ye "." _col(57) in ye "." _col(66) in ye "."
+ }
+ forvalues k=2/`nbModCov`=`i'-`nbit'''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "`=abbrev("``i''",10)':" in ye " `ident`=`i'-`nbit''_`k''" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local compteur=`compteur'+1
+ local estimate_e=`eB'[1,`compteur']
+ local se_e=sqrt(`=`eV'[`compteur',`compteur']')
+ noi{
+ di _col(1) in gr "``i'':" _col(19) in ye %6.3f `estimate_e' _col(28) in ye %6.3f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %6.3f `=`estimate_e'-`=(1+`level'/100)/2'*`se_e'' _col(61) in ye %6.3f `=`estimate_e'+`=(1+`level'/100)/2'*`se_e''
+ }
+ di in gr "{hline 66}"
+ }
+ }
+ if "`difficulties'"!=""{
+ di _col(1) in gr "_Cons" _col(19) in ye %6.3f `=`eB'[1,1]' _col(28) in ye %6.3f `=sqrt(`eV'[1,1])' _col(37) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1])'' _col(44) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1])')))' _col(52) in ye %6.3f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])'' _col(61) in ye %6.3f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1])''
+ di in gr "{hline 66}"
+ }
+ if "`estimateonly'"==""{
+ di ""
+ di "Proportion of latent trait variance explained by covariates"
+ di ""
+ di in gr "{hline 53}"
+ di _col(23) in gr "SS.III" _col(34) in gr "df" _col(38) in gr "V.exp." _col(47) in gr "R2.exp."
+ di in gr "{hline 53}"
+ local compteur=1
+ if "`difficulties'"==""{
+ local compteur=`nbdifftotbis'
+ }
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compteur=`compteur'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ if `nbcovquant'!=0{
+ forvalues i=`=`nbit'+`nbcov'+1'/`=`nbit'+`nbcov'+`nbcovquant''{
+ local ss3=`SS_Mss``i'''-`SS_ModComp'
+ local df=`dfree_Mss``i'''-`dfree_ModComp'
+ local vexp=(`SS_Mss``i'''-`SS_ModComp')/`SS_Mss``i'''*100
+ local r2exp=(`R2Nag'-`R2N_``i''')/`R2Nag'*100
+ local compteur=`compteur'+1
+ noi di _col(1) in gr "``i'':" _col(22) in ye %6.3f `ss3' _col(34) in ye %2.0f `df' _col(37) in ye %6.1f `vexp' "%" _col(46) in ye %6.1f `r2exp' "%"
+ }
+ }
+ di in gr "{hline 53}"
+ local sssc=`SS_ModSsCov'
+ local dfsc=`dfree_ModSsCov'
+ local ssac=`SS_ModComp'
+ local dfac=`dfree_ModComp'
+ di _col(23) in gr "SS.res" _col(34) in gr "df"
+ di _col(1) in gr "Model without cov." _col(22) in ye %6.3f `sssc' _col(31) in ye %5.0f `dfsc'
+ di _col(1) in gr "Full model" _col(22) in ye %6.3f `ssac' _col(31) in ye %5.0f `dfac'
+ di in gr "{hline 53}"
+ di ""
+ }
+ }
+ }
+ else if "`difficulties'"!=""{
+ di in gr "Latent trait distribution"
+ di in gr "{hline 80}"
+ di _col(18) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "z" _col(52) in gr "P>|z|" _col(61) in gr "[`level'% Conf. Interval]"
+ di in gr "{hline 80}"
+ di _col(1) in gr "Mu" _col(15) in ye %8.5f `=`eB'[1,1]' _col(27) in ye %8.5f `=sqrt(`eV'[1,1]) ' _col(39) in ye %5.2f `=`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) '' _col(51) in ye %6.3f `=2*(1-normal(abs(`=`eB'[1,1]'/`=sqrt(`eV'[1,1]) ')))' _col(61) in ye %8.5f `=`=`eB'[1,1]'-`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) '' _col(73) in ye %8.5f `=`=`eB'[1,1]'+`=(1+`level'/100)/2'*`=sqrt(`eV'[1,1]) ''
+
+ di _col(1) in gr "Sigma" _col(15) in ye %8.5f `=abs(`eB'[1,`nbc'])' _col(27) in ye %8.5f `=sqrt(`=`eV'[`nbc',`nbc']')' _col(39) in ye %5.2f `=`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']')' _col(51) in ye %6.3f `=2*(1-normal(abs(`eB'[1,`nbc']/sqrt(`=`eV'[`nbc',`nbc']'))))' _col(61) in ye %8.5f `=`eB'[1,`nbc']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')' _col(73) in ye %8.5f `=`eB'[1,`nbc']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`nbc',`nbc']')'
+ di in gr "{hline 80}"
+ di ""
+ }
+ if "`difficulties'"==""{
+ di in gr "Items difficulty parameters:"
+ di ""
+ di in gr "{hline 52}"
+ di _col(1) in gr "Item" _col(21) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "[`level'% C.I.]" _col(66)
+ di in gr "{hline 52}"
+ local compteur=1
+ if "`rsm'"==""{
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'':"
+ forvalues g=1/`=`moda`i''-1'{
+ di _col(4) in gr "response: " in ye %-6.2g `=`rep__`i''[`=`g'+1',1]' _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+1
+ }
+ di in gr "{hline 52}"
+ }
+ di ""
+ }
+ else{
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'':" _col(20) in ye %6.3f `=`eB'[1,`compteur']' _col(29) in ye %6.3f `=sqrt(`=`eV'[`compteur',`compteur']')' _col(38) in ye %6.3f `=`eB'[1,`compteur']-`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')' _col(47) in ye %6.3f `=`eB'[1,`compteur']+`=(1+`level'/100)/2'*sqrt(`=`eV'[`compteur',`compteur']')'
+ local compteur=`compteur'+`=`moda1'-1'
+ }
+ di in gr "{hline 52}"
+ forvalues i=2/`=`moda1'-1'{
+ di _col(1) in gr "tau`=`i'-1':" _col(20) in ye %6.3f `tau`i'' _col(29) in ye %6.3f `setau`i'' _col(38) in ye %6.3f `=`tau`i''-`=(1+`level'/100)/2'*`setau`i''' _col(47) in ye %6.3f `=`tau`i''+`=(1+`level'/100)/2'*`setau`i'''
+ }
+ di in gr "{hline 52}"
+ }
+ }
+ else{
+ di in gr "Items difficulty parameters: fixed for the analysis"
+ }
+
+ /*************************************/
+ /* ereturn */
+ /*************************************/
+
+ qui{
+ if "`difficulties'"==""{
+ tempname Varbeta Vardelta beta delta Vartheta theta
+ matrix `Varbeta'=`eV'
+ local Varsigma=`Varbeta'[`=colsof(`Varbeta')',`=colsof(`Varbeta')']
+ matrix `Vardelta'=`Varbeta'[1..`nbdifftotbis',1..`nbdifftotbis']
+ matrix `beta'=`eB'
+ local sigma=abs(`beta'[1,`=colsof(`beta')'])
+ matrix `delta'=`beta'[1,1..`nbdifftotbis']
+ if `=`nbcov'+`nbcovquant''!=0{
+ matrix `Vartheta'=`Varbeta'[`=`nbdifftotbis'+1'..`=colsof(`Varbeta')-1',`=`nbdifftotbis'+1'..`=colsof(`Varbeta')-1']
+ matrix `theta'=`beta'[1,`=`nbdifftotbis'+1'..`=colsof(`beta')-1']
+ }
+ else{
+ local thetas=0
+ local Varthetas=0
+ }
+ }
+ else{
+ if `=`nbcov'+`nbcovquant''!=0{
+ tempname Vartheta theta
+ matrix `Vartheta'=`eV'
+ local Varsigma=`Vartheta'[`=colsof(`Vartheta')',`=colsof(`Vartheta')']
+ matrix `Vartheta'=`Vartheta'[1..`=colsof(`Vartheta')-1',1..`=colsof(`Vartheta')-1']
+ matrix `theta'=`eB'
+ local sigma=abs(`theta'[1,`=colsof(`theta')'])
+ matrix `theta'=`theta'[1,1..`=colsof(`theta')-1']
+ }
+ else{
+ tempname theta Vtheta
+ matrix `theta'=`eB'
+ local sigma=abs(`theta'[1,`=colsof(`theta')'])
+ matrix `Vtheta'=`eV'
+ local Varsigma=`Vtheta'[`=colsof(`Vtheta')',`=colsof(`Vtheta')']
+ local thetas=`theta'[1,1]
+ local varthetas=`Vtheta'[1,1]
+ }
+ }
+ ereturn clear
+ if `=`nbcov'+`nbcovquant''!=0{
+ matrix b=`eB'
+ matrix V=`eV'
+ ereturn post b V, depname(theta)
+ ereturn matrix theta=`theta'
+ ereturn matrix Vartheta=`Vartheta'
+ }
+ else{
+ if "`difficulties'"==""{
+ matrix V=`eV'
+ tempname thetatemp Varthetatemp
+ matrix `thetatemp'=(0)
+ matrix `Varthetatemp'=(0)
+ matrix coleq `Varthetatemp'=estimates
+ matrix coln `Varthetatemp'=mu
+ matrix roweq `Varthetatemp'=estimates
+ matrix rown `Varthetatemp'=mu
+ matrix b=`eB'
+ matrix coleq `thetatemp'=estimates
+ matrix coln `thetatemp'=mu
+ matrix rown `thetatemp'=y1
+ ereturn post b V, depname(theta)
+ ereturn matrix theta=`thetatemp'
+ ereturn matrix Vartheta=`Varthetatemp'
+ }
+ else{
+ tempname thetatemp Varthetatemp
+ matrix `Varthetatemp'=(`varthetas')
+ matrix coleq `Varthetatemp'=estimates
+ matrix coln `Varthetatemp'=mu
+ matrix roweq `Varthetatemp'=estimates
+ matrix rown `Varthetatemp'=mu
+ matrix `thetatemp'=(`thetas')
+ matrix coleq `thetatemp'=estimates
+ matrix coln `thetatemp'=mu
+ matrix rown `thetatemp'=y1
+ matrix V=`eV'
+ matrix b=`eB'
+ ereturn post b V, depname(theta)
+ tempname vvvt vvvVt
+ matrix `vvvt'=(`thetas')
+ matrix `vvvVt'=(`varthetas')
+ ereturn matrix theta=`vvvt'
+ ereturn matrix Vartheta=`vvvVt'
+ }
+ }
+ ereturn scalar ll=`LLfull'
+ ereturn scalar cn=`ccnn'
+ ereturn scalar r2=`R2Nag'
+ ereturn scalar N=`Nbid'
+ ereturn scalar Nit=`nbit'
+ ereturn scalar converged=`convergeance'
+ ereturn scalar ndtb=`nbdifftotbis'
+ ereturn scalar mugauss=`mugauss'
+ ereturn scalar sdgauss=`sdgauss'
+ if "`nip'"!=""{
+ ereturn scalar nip=`nip'
+ }
+ ereturn local items `varlist'
+ ereturn local categorical `categorical'
+ ereturn local continuous `continuous'
+ ereturn local estimateonly `estimateonly'
+ ereturn local constr `contrR'
+ ereturn local difficulties `difficulties'
+ if `nbcov'!=0{
+ forvalues i=`=`nbit'+1'/`=`nbit'+`nbcov''{
+ local ``i''_m ""
+ forvalues k=1/`nbModCov`=`i'-`nbit'''{
+ local ``i''_m "```i''_m' `ident`=`i'-`nbit''_`k''"
+ ereturn local ``i'' ```i''_m'
+ }
+ }
+ }
+ ereturn local rsm `rsm'
+ ereturn local from `from'
+ ereturn local robust `robust'
+ ereturn local adapt `adapt'
+ ereturn local iterate `iterate'
+ ereturn local itest `itest'
+ ereturn local datatest `bddinib'
+ ereturn local if `if'
+ ereturn local in `in'
+ ereturn local cmd "pcmodel"
+ ereturn scalar order=`ordre'
+ if `=`nbcov'+`nbcovquant''!=0{
+ ereturn scalar Ncat=`nbcov'
+ ereturn scalar Ncont=`nbcovquant'
+ }
+ if "`difficulties'"==""{
+ ereturn matrix Vardelta=`Vardelta'
+ ereturn matrix delta=`delta'
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ if "`rsm'"!=""{
+ ereturn matrix Tau=`tau'
+ }
+ }
+ else{
+ if `=`nbcov'+`nbcovquant''!=0{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ }
+ else{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varvartheta'
+ }
+ }
+ if "`estimateonly'"=="" & `=`nbcov'+`nbcovquant''>0 {
+ ereturn matrix VarExpSS `VarExpSS'
+ }
+ }
+use `bddinip', replace
+}
+restore
+end
diff --git a/Modules/ado/personal/p/pcmodelplus.ado b/Modules/ado/personal/p/pcmodelplus.ado
new file mode 100644
index 0000000..0abfbb2
--- /dev/null
+++ b/Modules/ado/personal/p/pcmodelplus.ado
@@ -0,0 +1,1196 @@
+program define pcmodelplus, eclass
+syntax varlist [, COVariates(string) DIFficulties(string) ITerate(string) Group(string) adapt robust nodis]
+/* syntaxe : liste des variables correspondant aux items, cov(liste des covariables de groupe, qualitatives codĂ©es numĂ©riquement), dif(liste de vecteurs lignes ayant le mĂȘme nom que les variables d'items, correspondant aux difficultĂ©s des modalitĂ©s d'items) it(nombre d'itĂ©rations maximum pour la procĂ©dure d'estimation par convergeance) adapt : utilisation de quadratures "adaptative" robust : utilisation de l'estimateur de Huber/White/sandwich pour la matrice de covariance */
+preserve
+tokenize `varlist' `covariates'
+local nbit: word count `varlist'
+local nbcov: word count `covariates'
+local nbit2:word count `difficulties'
+tempfile bddini
+qui q memory
+local matsizeini=r(matsize)
+
+ /*************************************/
+ /* Verifications */
+/*************************************/
+
+if "`iterate'"==""{
+ local it=""
+}
+else{
+ local iterateII="it(`iterate')"
+}
+tempvar one id item reponse obs wt x choix it covariable covverytemp
+qui save `bddini', replace
+if "`difficulties'"!=""{
+ if `nbit2'!=`nbit'{
+ noi di in red "Not the same number of difficuly vectors and of items, Grrr!"
+ use `bddini',replace
+ error 100
+ }
+ forvalues i=1/`nbit'{
+ if strpos("`varlist'",word("`difficulties'",`i'))==0{
+ noi di in red "The item difficulty vectors must have the same names than the item variables, Grrr! be carefull please!!!"
+ use `bddini',replace
+ error 100
+ }
+ }
+}
+
+
+
+
+ /*************************************/
+ /* Estimation of the parameters */
+/*************************************/
+
+
+if `nbcov'!=0{
+ local nbtotmodacov=0
+ forvalues i=1/`nbcov'{
+ qui tab ``=`nbit'+`i''', matrow(nom) matcell(val)
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ local valmod`k'cov`i'=nom[`k',1]
+ local nbmod`k'cov`i'=val[`k',1]
+ }
+ local nbtotmodacov=`nbtotmodacov'+`nbModCov`i''
+ if `nbModCov`i''>10{
+ noi di in red "``=`nbit'+`i''' has too much modalities (>10). Hey, why not a continuous variable, while you are at it?"
+ use `bddini',replace
+ error 100
+ }
+ local tot`i'=r(N)
+ forvalues k=1/`nbModCov`i''{
+ local sum=0
+ forvalues k2=1/`nbModCov`i''{
+ if `k2'!=`k'{
+ local sum=`sum'+val[`k2',1]
+ }
+ }
+ local a`i'_`k'=round((`sum'-`tot`i'')/`tot`i'',0.01)
+ local b`i'_`k'=round((`sum')/`tot`i'',0.01)
+ }
+ }
+}
+qui{
+ keep `varlist' `covariates'
+ local nbdifftot=0
+ if "`difficulties'"==""{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ su `reponse'`i'
+ local moda`i'=`=r(max)+1'
+ local nbdifftot=`nbdifftot'+`moda`i''-1
+ }
+ }
+ else{
+ forvalues i=1/`nbit'{
+ gen `reponse'`i' = ``i''
+ drop ``i''
+ local moda`i'=colsof(``i'')+1
+ }
+ }
+ gen `one'=1
+ su `one'
+ local Nbid=r(N)
+ collapse (sum) `wt'2=`one', by(`reponse'1-`reponse'`nbit' `covariates')
+ gen `id'=_n
+ reshape long `reponse', i(`id') j(`item')
+ drop if `reponse'==.
+ gen `obs'=_n
+ local ddlssIII=_N-1
+ forvalues i=1/`nbit'{
+ expand `moda`i'' if `item'==`i'
+ }
+ by `obs', sort: gen `x'=_n-1
+ gen `choix'=`reponse'==`x'
+ tab `item', gen(`it')
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ gen d_``i''_`g'=(-1)*`it'`i'*(`x'>=`g')
+ }
+ }
+ if "`difficulties'"!=""{
+ gen difficulties=0
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`moda`i''-1'{
+ replace difficulties=difficulties+``i''[1,`g']*d_``i''_`g'
+ }
+ }
+ }
+ if `nbcov'!=0{
+ forvalues i=1/`nbcov'{
+ gen `covverytemp'=``=`nbit'+`i'''
+ drop ``=`nbit'+`i'''
+ rename `covverytemp' ``=`nbit'+`i'''
+ tab ``=`nbit'+`i''', gen(``=`nbit'+`i'''__) matrow(nom)
+ local nbModCov`i'=r(r)
+ forvalues k=1/`nbModCov`i''{
+ replace ``=`nbit'+`i'''__`k'=``=`nbit'+`i'''__`k'*`x'
+ local ident`i'_`k'=nom[`k',1]
+ if `k'==1 & `i'==1{
+ local ident1=`ident`i'_`k''
+ }
+ rename ``=`nbit'+`i'''__`k' ``=`nbit'+`i'''_`ident`i'_`k''
+ }
+ }
+ forvalues i=1/`nbcov'{
+ drop ``=`nbit'+`i'''
+ }
+ }
+ rename `id' theta
+ rename `x' estimates
+}
+eq slope:estimates
+gen obs=`obs'
+gen choix=`choix'
+gen wt=`wt'
+if `nbcov'!=0{
+ if "`difficulties'"==""{
+/* Recherche de valeurs initiales */
+ matrix a0=J(1,`=`nbdifftot'+`nbtotmodacov'-`nbcov'',0)
+
+ qui{
+ tempfile bddencours
+ save `bddencours', replace
+ use `bddini', replace
+ local countdif=1
+ forvalues i=1/`nbit'{
+ ologit ``i''
+ matrix ttt=e(b)
+ matrix a0[1,`countdif']=ttt/2
+ local countdif=`countdif'+e(k)
+ }
+ use `bddencours', replace
+ }
+
+ local colnom ""
+ forvalues i=1/`nbit'{
+ forvalues j=1/`=`moda`i''-1'{
+ local colnom "`colnom' d_``i''_`j'"
+ }
+ }
+ }
+ constraint drop _all
+ local contrainte ""
+ local subgroup0 "``=`nbit'+1'':`ident1_1'"
+ forvalues i=1/`nbcov'{
+ local contrainte "`contrainte' `i'"
+
+ constraint `i' ``=`nbit'+`i'''_`ident`i'_1'=0
+ if "`difficulties'"==""{
+ forvalues j=2/`nbModCov`i''{
+ local colnom "`colnom' ``=`nbit'+`i'''_`ident`i'_`j''"
+ }
+ }
+ }
+ if `nbcov'>1{
+ forvalues i=2/`nbcov'{
+ local subgroup0 "`subgroup0', ``=`nbit'+`i''':`ident`i'_1'"
+ }
+ }
+ if "`difficulties'"==""{
+ if wordcount("`colnom'")!=`=`nbdifftot'+`nbtotmodacov'-`nbcov''{
+ di in red "ERRUER MAJEUR!!! (trop de covariables, d'items, longueur de nom des variables d'items ou de covariable trop longs... bref, réduire le nombre de caractÚres)"
+ use `bddini',replace
+ error 100
+ }
+ matrix coln a0=`colnom'
+ matrix coleq a0=estimates
+ matrix a1=J(1,1,0)
+ matrix coln a1=estimates
+ matrix coleq a1=theta1_1
+ matrix a=a0,a1
+ }
+ if "`difficulties'"!=""{
+ gen cons=estimates
+ }
+ ereturn clear
+ if "`difficulties'"==""{
+ gllamm estimates d_`1'_1-d_``nbit''_`=`moda`nbit''-1' ``=`nbit'+1''_`ident1'-``=`nbit'+`nbcov'''_`ident`nbcov'_`nbModCov`nbcov''', i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `adapt' `robust' nocons `iterateII' nodis from(a) constraint(`contrainte') copy
+ matrix estimations = e(b)
+ local sdmu=estimations[1,`=colsof(estimations)']
+ }
+ else{
+ gllamm estimates cons ``=`nbit'+1''_`ident1'-``=`nbit'+`nbcov'''_`ident`nbcov'_`nbModCov`nbcov''', offset(difficulties) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `iterateII' `adapt' `robust' nocons nodis constraint(`contrainte')
+ }
+ matrix eB=e(b)
+ local nbc=colsof(eB)
+ matrix eV=e(V)
+/* SS type III*/
+ tempfile bddencours
+ qui save `bddencours', replace
+ qui use `bddini', replace
+ local varianceRes=eB[1,`=colsof(eB)']^2
+ qui{
+ local contv=1
+ local ddlssIIIc=`ddlssIII'
+ forvalues c=`=1+`nbit''/`=`nbcov'+`nbit''{
+ local ddlssIIIc=`ddlssIIIc'-(`nbModCov`=`c'-`nbit'''-1)
+ tab ``c'', matcell(cell) matrow(row)
+ local muG=0
+ local denommuG=0
+ local muGcarre=0
+ if "`difficulties'"==""{
+ forvalues cm=1/`nbModCov`=`c'-`nbit'''{
+ local muG=`muG'+cell[`cm',1]*eB[1,`=`nbdifftot'+`contv'']
+ local denommuG=`denommuG'+cell[`cm',1]
+ local muGcarre=`muGcarre'+(`varianceRes'+eB[1,`=`nbdifftot'+`contv'']^2)*cell[`cm',1]
+ local contv=`contv'+1
+ }
+ }
+ else{
+ forvalues cm=1/`nbModCov`=`c'-`nbit'''{
+ local muG=`muG'+cell[`cm',1]*eB[1,`=1+`contv'']
+ local denommuG=`denommuG'+cell[`cm',1]
+ local muGcarre=`muGcarre'+(`varianceRes'+eB[1,`=1+`contv'']^2)*cell[`cm',1]
+ local contv=`contv'+1
+ }
+ }
+ local Var_`c'=(`muGcarre'/`denommuG') - (`muG'/`denommuG')^2
+ }
+ local contv=1
+ local Varttot=`varianceRes'
+ forvalues c=`=1+`nbit''/`=`nbcov'+`nbit''{
+ local ddlssIIIs`c'=`ddlssIIIc'+(`nbModCov`=`c'-`nbit'''-1)
+ tab ``c'', matcell(cell) matrow(row)
+ local muG=0
+ local denommuG=0
+ local muGcarre=0
+ if "`difficulties'"==""{
+ forvalues cm=1/`nbModCov`=`c'-`nbit'''{
+ local muG=`muG'+cell[`cm',1]*eB[1,`=`nbdifftot'+`contv'']
+ local denommuG=`denommuG'+cell[`cm',1]
+ local muGcarre=`muGcarre'+(`Varttot'+eB[1,`=`nbdifftot'+`contv'']^2)*cell[`cm',1]
+ local contv=`contv'+1
+ local Varttot=(`muGcarre'/`denommuG') - (`muG'/`denommuG')^2
+ }
+ }
+ else{
+ forvalues cm=1/`nbModCov`=`c'-`nbit'''{
+ local muG=`muG'+cell[`cm',1]*eB[1,`=1+`contv'']
+ local denommuG=`denommuG'+cell[`cm',1]
+ local muGcarre=`muGcarre'+(`Varttot'+eB[1,`=1+`contv'']^2)*cell[`cm',1]
+ local contv=`contv'+1
+ local Varttot=(`muGcarre'/`denommuG') - (`muG'/`denommuG')^2
+ }
+ }
+ }
+ forvalues c=`=1+`nbit''/`=`nbcov'+`nbit''{
+ local sst3_`c'=(`Var_`c''*`ddlssIIIs`c''-`varianceRes'*`ddlssIIIc')
+ local VarExp_`c'=(`Var_`c''*`ddlssIIIs`c''-`varianceRes'*`ddlssIIIc')/(`Varttot'*`ddlssIII')
+ local df_`c'=`nbModCov`=`c'-`nbit'''-1
+ }
+ local contv=1
+ forvalues c=`=1+`nbit''/`=`nbcov'+`nbit''{
+ if "`difficulties'"==""{
+ forvalues cc=1/`nbModCov`=`c'-`nbit'''{
+ if `cc'==1{
+ local contv=`contv'+1
+ }
+ else{
+ local ESit`c'mod`cc' = `=eB[1,`=`nbdifftot'+`contv'']/sqrt(`Varttot')'
+ local contv=`contv'+1
+ }
+ noi di in gr ""
+ }
+ }
+ else{
+ forvalues cc=1/`nbModCov`=`c'-`nbit'''{
+ if `cc'==1{
+ local contv=`contv'+1
+ }
+ else{
+ /*
+ noi di `contv'
+ noi matrix list eB
+ */
+ local ESit`c'mod`cc' = `=eB[1,`=1+`contv'']/sqrt(`Varttot')'
+ local contv=`contv'+1
+ }
+ noi di in gr ""
+ }
+ }
+ }
+ }
+ qui use `bddencours', replace
+}
+else{
+ ereturn clear
+ if "`difficulties'"==""{
+ matrix a0=J(1,`nbdifftot',0)
+ qui{
+ tempfile bddencours
+ save `bddencours', replace
+ use `bddini', replace
+ local countdif=1
+ forvalues i=1/`nbit'{
+ ologit ``i''
+ matrix ttt=e(b)
+ matrix a0[1,`countdif']=ttt/2
+ local countdif=`countdif'+e(k)
+ }
+ use `bddencours', replace
+ }
+ local colnom ""
+ forvalues i=1/`nbit'{
+ forvalues j=1/`=`moda`i''-1'{
+ local colnom "`colnom' d_``i''_`j'"
+ }
+ }
+ matrix coln a0=`colnom'
+ matrix coleq a0=estimates
+ matrix a1=J(1,1,0)
+ matrix coln a1=estimates
+ matrix coleq a1=theta1_1
+ matrix a=a0,a1
+ gllamm estimates d_`1'_1-d_``nbit''_`=`moda`nbit''-1', i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `iterateII' `adapt' `robust' nocons nodis from(a) copy
+ matrix estimations = e(b)
+ local sdmu=estimations[1,`=colsof(estimations)']
+ }
+ else{
+ gen cons=estimates
+ gllamm estimates cons, offset(difficulties) i(theta) eqs(slope) link(mlogit) expand(`obs' `choix' o) weight(`wt') `iterateII' `adapt' `robust' nocons nodis
+ }
+ matrix eB=e(b)
+ local nbc=colsof(eB)
+ matrix eV=e(V)
+}
+clear
+use `bddini'
+
+
+
+if "`difficulties'"==""{
+ /*************************************/
+ /* test R1m */
+/*************************************/
+ noi di in gr "Performing R1m test"
+ qui{
+ set matsize `matsizeini'
+ tempfile matU
+ tempname dm cell row
+ egen `dm'=rowmiss(`varlist')
+ replace `dm'=`dm'>0
+ tab `dm',matcell(`cell') matrow(`row')
+ local nbmissing=`cell'[2,1]
+ local percentmissing=`cell'[2,1]/(`cell'[1,1]+`cell'[2,1])
+ if `nbmissing'==.{
+ local nbmissing=0
+ local percentmissing=0
+ }
+ keep if `dm'==0
+ drop `dm'
+ keep `varlist' `covariates'
+ if `nbcov'!=0{
+ local mumodifie=0
+ local compteuri=`nbdifftot'
+ forvalues c=1/`nbcov'{
+ forvalues m=1/`nbModCov`c''{
+ local compteuri=`compteuri'+1
+ local mumodifie=`mumodifie'+(`nbmod`m'cov`c''/`Nbid')*estimations[1,`compteuri']
+ }
+ }
+ drop `covariates'
+ }
+ forvalues i=1/`nbit'{
+ rename ``i'' pre_``i''
+ }
+ forvalues i=1/`nbit'{
+ gen it`i'=pre_``i''
+ drop pre_``i''
+ }
+ forvalues i=1/`nbit'{
+ qui tab it`i'
+ local nbmoda_`i'=r(r)
+ }
+ local score "it1"
+ forvalues i=2/`nbit'{
+ local score "`score'+it`i'"
+ }
+ gen score=`score'
+ save `bddini'_se, replace
+ local N=_N
+
+/* autogroup */
+ if "`group'"==""{
+ tab score, matcell(freq) matrow(val)
+ if r(N)<60{
+ di in red "Pas assez d'individus pour grouper de façon automatique"
+ }
+ local nbscore=r(r)
+ local ini=0
+ local pb=1
+ local list ""
+ forvalues i=1/`nbscore'{
+ local ini=`ini'+freq[`i',1]
+ if `ini'<30{
+ local lim`i'=""
+ local pb=1
+ }
+ else{
+ local lim`i'=" `=val[`i',1]'"
+ local ini=0
+ local pb=0
+ }
+ local list "`list' `lim`i''"
+ }
+ local list "`=itrim("`list'")'"
+ if `pb'==1{
+ local list "`=subinword("`list'",word("`list'",-1),"",.)'"
+ local list "`=itrim("`list' `=val[`nbscore',1]'")'"
+ }
+ if wordcount("`list'")<2{
+ di in red "Autogroup impossible : pas de possibilité de constituer plusieurs groupes de plus de 30 individus à partir du score"
+ }
+ local nbgroup=wordcount("`list'")
+ }
+ else{
+ local list "`group'"
+ local nbgroup=wordcount("`list'")
+ tab score, matcell(freq) matrow(val)
+ local nbscore=r(r)
+ }
+ local nbmodagpe=0
+ forvalues i=1/`nbit'{
+ local nbmodagpe=`nbmodagpe'+`nbmoda_`i''
+ }
+ gen g=.
+ local liminf1=-1
+ forvalues i=1/`nbgroup'{
+ local limsup`i'=real("`=word("`list'",`i')'")
+ if `i'>1{
+ local liminf`i'=real("`=word("`list'",`=`i'-1')'")
+ }
+ replace g=`i' if score<=`limsup`i'' & score>`liminf`i''
+ }
+ forvalues i=1/`nbgroup'{
+ su score if g==`i'
+ local N`i'=r(N)
+ }
+ save `bddini'_se, replace
+ save `bddini'_se_g, replace
+ use `bddini'_se, replace
+ local count=0
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ if `j'==1{
+ local diffest`i'_`j'=0
+ }
+ else{
+ local count=`count'+1
+ local diffest`i'_`j'=round(estimations[1,`count'],0.001)+`diffest`i'_`=`j'-1''
+ }
+ local num`i'_`j' "exp(`=`j'-1'*x-`diffest`i'_`j'')"
+ if `j'==1{
+ local denom`i' "1"
+ }
+ else{
+ local denom`i' "`denom`i''+`num`i'_`j''"
+ }
+ }
+ forvalues j=1/`nbmoda_`i''{
+ local PCM`i'_`j' "(`num`i'_`j'')/(`denom`i'')"
+ }
+ }
+ local nbcomb=1
+ forvalues i=1/`nbit'{
+ local nbcomb=`nbcomb'*`nbmoda_`i''
+ }
+ clear
+ set obs `nbcomb'
+ local facteur=1
+ gen score=0
+ local order "score"
+ forvalues i=1/`nbit'{
+ gen it`i'=floor(mod(_n/`facteur',`nbmoda_`i''))
+ local facteur=`facteur'*`nbmoda_`i''
+ replace score=score+it`i'
+ tab it`i', gen(i`i'c)
+ local order "`order' it`i'"
+ }
+ order `order', first
+ sort score
+
+/* Probabilité des paterns de réponse */
+ tab score, gen(score)
+ local nbscore=r(r)
+ gen P=1
+ local gdN=_N
+ forvalues l=1/`gdN'{
+ local exp ""
+ forvalues i=1/`nbit'{
+ forvalues m=1/`nbmoda_`i''{
+ if i`i'c`m'[`l']==1{
+ if "`exp'"==""{
+ local exp "`PCM`i'_`m''"
+ }
+ else{
+ local exp "`exp'*`PCM`i'_`m''"
+ }
+ }
+ }
+ }
+ if `nbcov'==0{
+ gausshermite `exp' , sigma(`sdmu') mu(0) display
+ }
+ else{
+ local sdgauss=sqrt(`Varttot')
+ gausshermite `exp' , sigma(`sdgauss') mu(`mumodifie') display
+ }
+ replace P=r(int) if _n==`l'
+ di "`exp'"
+ }
+ tab score
+ local Pscoresl=r(r)
+ matrix Pscores=J(`Pscoresl',2,.)
+ forvalues i=1/`Pscoresl'{
+ su P if score==`=`i'-1'
+ matrix Pscores[`i',2]=r(sum)
+ matrix Pscores[`i',1]=`i'-1
+ }
+ save `matU'_2, replace
+ local sort "score"
+ forvalues i=1/`nbit'{
+ local sort "`sort' it`i'"
+ forvalues j=1/`nbmoda_`i''{
+ replace i`i'c`j'=i`i'c`j'*P
+ }
+ }
+ forvalues i=1/`nbscore'{
+ replace score`i'=score`i'*P
+ }
+ save `matU'_1, replace
+/* Matrices U */
+ local order ""
+ forvalues i=1/`=wordcount("`list'")'{
+ local nbscoreg`i'= `nbscore'
+ forvalues j=0/`=`nbscore'-1'{
+ if `j'>`limsup`i'' | `j'<=`liminf`i''{
+ local nbscoreg`i'=`nbscoreg`i''-1
+ capture drop s`=`j'+1'g`i'
+ }
+ }
+ local order "`order' *g`i'"
+ use `matU'_1, replace
+ keep if score<=`limsup`i'' & score>`liminf`i''
+ gen g=`i'
+ forvalues a=1/`nbit'{
+ forvalues b=1/`nbmoda_`a''{
+ capture rename i`a'c`b' i`a'c`b'g`i'
+ }
+ }
+ forvalues a=1/`nbscore'{
+ capture rename score`a' s`a'g`i'
+ forvalues j=1/`=wordcount("`list'")'{
+ if `=`a'-1'>`limsup`i'' | `=`a'-1' <= `liminf`i''{
+ capture drop s`a'g`j'
+ }
+ }
+ }
+ tempfile bloc`i'
+ sort `sort'
+ save `bloc`i''_1, replace
+ }
+ local order ""
+ forvalues i=1/`=wordcount("`list'")'{
+ local order "`order' *g`i'"
+ use `matU'_2, replace
+ keep if score<=`limsup`i'' & score>`liminf`i''
+ gen g=`i'
+ forvalues a=1/`nbit'{
+ forvalues b=1/`nbmoda_`a''{
+ capture rename i`a'c`b' i`a'c`b'g`i'b
+ }
+ }
+ forvalues a=1/`nbscore'{
+ capture rename score`a' s`a'g`i'b
+ forvalues j=1/`=wordcount("`list'")'{
+
+ if `=`a'-1'>`limsup`i'' | `=`a'-1' <= `liminf`i''{
+ capture drop s`a'g`j'
+ }
+ }
+ }
+ sort `sort'
+ save `bloc`i''_2, replace
+ describe
+ local mat_`i'=r(k)-3-`nbit'
+ }
+
+/* Matrice W */
+ local nbscoreg0=0
+ forvalues g=1/`nbgroup'{
+ qui q memory
+ if `mat_`g''>r(matsize) & `mat_`g''<=r(m_matsize){
+ set matsize `mat_`g''
+ }
+ if `mat_`g''>r(m_matsize){
+ di in red "Error, not enought memory to allocate to the W matrix calculation"
+ }
+ matrix W_`g'=J(`mat_`g'',`mat_`g'',.)
+ use `bloc`g''_2, replace
+ local count=1
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ rename i`i'c`j'g`g'b v`count'b
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename s`s'g`g'b v`count'b
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ local Ncol_`g'_=`count'-1
+ save `bloc`g''_2b, replace
+ use `bloc`g''_1, replace
+ local count=1
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ rename i`i'c`j'g`g' v`count'
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename s`s'g`g' v`count'
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ local Ncol_`g'__=`count'-1
+ forvalues i=1/`=`count'-1'{
+ replace v`i'=P if round(v`i',0.000001)!=round(0,0.000001)
+ }
+ local countW_`g'=`count'-1
+ save `bloc`g''_1b, replace
+ merge `sort' using `bloc`g''_2b
+ drop _merge
+ forvalues i=1/`mat_`g''{
+ forvalues j=1/`mat_`g''{
+ gen prod=v`i'*v`j'b
+ qui su prod
+ matrix W_`g'[`i',`j']=r(sum)
+ drop prod
+ }
+ }
+ capture matrix W_`g'i=invsym(W_`g')
+ if _rc!=0{
+ capture matrix W_`g'i=inv(W_`g')
+ }
+ if _rc!=0{
+ di in red "Error while computing the Wg matrix"
+ }
+ mata: A=J(1,1,.)
+ mata: A[1,1]=rank(st_matrix("W_`g'"))
+ mata: st_matrix("rank_",A)
+ local rank`g'=rank_[1,1]
+ }
+
+/* Matrice poid */
+ forvalues g=1/`nbgroup'{
+ use `bddini'_se_g, replace
+ keep if g==`g'
+ gen Pd=1
+ collapse (sum) nb=Pd, by(`sort')
+ sort `sort'
+ save `bddini'_se_`g'obs, replace
+ use `bloc`g''_2b, replace
+ sort `sort'
+ merge `sort' using `bddini'_se_`g'obs
+ drop _merge
+ replace nb=0 if nb==.
+ gen nbth=P*`N'
+ gen Di=(nb-nbth)/sqrt(`N')
+ sort `sort'
+ save `bloc`g''_2bgi, replace
+ if `countW_`g''>10{
+ set matsize `countW_`g''
+ }
+ else{
+ set matsize 10
+ }
+ matrix deviation_`g'=J(`countW_`g'',1,.)
+ use `bloc`g''_2bgi, replace
+ gen Pobs=nb/`N'
+ gen Diff=Pobs-P
+ forvalues j=1/`countW_`g''{
+ replace v`j'b=v`j'b*Diff
+ su v`j'b
+ matrix deviation_`g'[`j', 1]=r(sum)*sqrt(`N')
+ }
+ }
+ local sum=0
+ local ddl=0
+ local rank ""
+ qui q memory
+ if `matsizeini'>r(matsize) & 10000 > r(m_matsize){
+ set matsize `matsizeini'
+ }
+ else{
+ set matsize 10000
+ }
+ forvalues g=1/`nbgroup'{
+ capture matrix G_`g'=deviation_`g''*W_`g'i*deviation_`g'
+ if _rc!=0{
+ noi di in red "Error, not enought memory to allocate to the W matrix calculation
+ }
+ local sum=`sum'+G_`g'[1,1]
+ local ddl=`ddl'+`rank`g''
+ local rank "`rank'`rank`g'' "
+ }
+ local ddl=`ddl'-`nbmodagpe'+`nbit'-2
+ set matsize `matsizeini'
+ }
+ local R1m_group "`list'"
+ local R1m_Rank `rank'
+ local R1M_ddl=`ddl'
+ local R1M_stat=`sum'
+ local R1M_p=`=1-chi2(`ddl', `sum')'
+
+
+ /*************************************/
+ /* tests Si */
+/*************************************/
+
+ qui{
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ }
+ matrix DGibase=J(6,`countbase',.)
+ use `bddini'_se_g, replace
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ tab it`ii', gen(i`ii'c)
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ matrix DGibase[2,`countbase']=`ii'
+ matrix DGibase[3,`countbase']=`j'
+ su i`ii'c`j'
+ matrix DGibase[4,`countbase']=r(sum)
+ }
+ drop i`ii'c*
+ }
+ tab score, gen(s)
+ forvalues s=1/`nbscore'{
+ capture su s`s'
+ if _rc!=0{
+ gen s`s'=0
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ matrix DGibase[2,`countbase']=`s'
+ su s`s'
+ matrix DGibase[4,`countbase']=r(sum)
+ }
+ use `matU'_2, replace
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ su P if i`ii'c`j'==1
+ matrix DGibase[5,`countbase']=r(sum)*`N'
+ matrix DGibase[6,`countbase']=(DGibase[4,`countbase']-DGibase[5,`countbase'])/sqrt(`N')
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ su P if score`s'==1
+ matrix DGibase[5,`countbase']=r(sum)*`N'
+ matrix DGibase[6,`countbase']=(DGibase[4,`countbase']-DGibase[5,`countbase'])/sqrt(`N')
+ }
+ local colbase=`countbase'
+ }
+ forvalues i=1/`nbit'{
+ qui{
+ use `matU'_2, replace
+ gen g=.
+ local liminf1=-1
+ forvalues g=1/`nbgroup'{
+ replace g=`g' if score<=`limsup`g'' & score>`liminf`g''
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ gen testi`i'c`j'g`g'=0
+ replace testi`i'c`j'g`g'=i`i'c`j' if g==`g'
+ }
+ }
+ local count=1
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ rename i`ii'c`j' v`count'b
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename score`s' v`count'b
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ rename testi`i'c`j'g`g' v`count'b
+ local count=`count'+1
+ }
+ }
+ local nbarrive`i'=`count'-1
+ sort `sort'
+ save `matU'_2i`i', replace
+ use `matU'_1, replace
+ gen g=.
+ local liminf1=-1
+ forvalues g=1/`nbgroup'{
+ replace g=`g' if score<=`limsup`g'' & score>`liminf`g''
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ gen testi`i'c`j'g`g'=0
+ replace testi`i'c`j'g`g'=i`i'c`j' if g==`g'
+ }
+ }
+ local count=1
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ rename i`ii'c`j' v`count'
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename score`s' v`count'
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ rename testi`i'c`j'g`g' v`count'
+ local count=`count'+1
+ }
+ }
+ sort `sort'
+ save `matU'_1i`i', replace
+ merge `sort' using `matU'_2i`i'
+ drop _merge
+ if `nbarrive`i''>r(matsize) & `nbarrive`i''<=r(m_matsize){
+ set matsize `nbarrive`i''
+ }
+ if `nbarrive`i''>r(m_matsize){
+ di in red "Error, not enought memory to allocate to the W matrix calculation"
+ }
+ matrix i`i'W=J(`nbarrive`i'',`nbarrive`i'',.)
+ forvalues ii=1/`nbarrive`i''{
+ forvalues j=1/`nbarrive`i''{
+ gen prod=v`ii'*v`j'b
+ qui su prod
+ matrix i`i'W[`ii',`j']=r(sum)
+ drop prod
+ }
+ }
+ capture matrix i`i'Wi=invsym(i`i'W)
+ if _rc!=0{
+ capture matrix i`i'Wi=inv(i`i'W)
+ }
+ if _rc!=0{
+ di in red "Error while computing the Wg matrix"
+ }
+ mata: A=J(1,1,.)
+ mata: A[1,1]=rank(st_matrix("i`i'W"))
+ mata: st_matrix("rank_",A)
+ local i`i'rank=rank_[1,1]
+ matrix plus`i'=J(6,`=`nbarrive`i''-`colbase'',.)
+ matrix DGi_`i'=DGibase,plus`i'
+ save `matU'_i`i', replace
+ local count=`colbase'
+ use `bddini'_se_g, replace
+ tab it`i', gen(i`i'c)
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ local count=`count'+1
+ matrix DGi_`i'[2,`count']=`i'
+ matrix DGi_`i'[3,`count']=`j'
+ matrix DGi_`i'[1,`count']=`g'
+ su i`i'c`j' if g==`g'
+ matrix DGi_`i'[4,`count']=r(sum)
+ }
+ }
+ use `matU'_i`i', replace
+ forvalues t=`=`colbase'+1'/`nbarrive`i''{
+ su P if v`t'b==1
+ matrix DGi_`i'[5,`t']=r(sum)*`N'
+ matrix DGi_`i'[6,`t']=(DGi_`i'[4,`t']-DGi_`i'[5,`t'])/sqrt(`N')
+ }
+ set matsize `matsizeini'
+ matrix tDGi_`i'=DGi_`i'[6,1..`=colsof(DGi_`i')']'
+ matrix G=tDGi_`i''*i`i'Wi*tDGi_`i'
+ local sum=G[1,1]
+ local ddl=`i`i'rank'
+ local ddl=`ddl'-`nbmodagpe'+`nbit'-2
+ local rank "`i`i'rank'"
+ }
+ local S`i'_rank=`rank'
+ local S`i'_ddl=`ddl'
+ local S`i'_stat=`sum'
+ local S`i'_p=`=1-chi2(`ddl', `sum')'
+ }
+}
+
+ /*************************************/
+ /* print */
+/*************************************/
+
+
+
+di in gr ""
+di in gr " log likelihood : " in ye "`=e(ll)'"
+local lll=e(ll)
+local ccnn=e(cn)
+di in gr " Condition number : " in ye "`=e(cn)'"
+di in gr " Number of individuals : "in ye "`Nbid'"
+di in gr " Number of items : "in ye "`nbit'"
+if `nbcov'!=0{
+ di in gr " Number of covariates : "in ye "`nbcov'"
+}
+di in gr ""
+di ""
+if "`difficulties'"==""{
+ di in gr "Global tests of the fit : test R1m"
+ di in gr " groups : " in ye "`R1m_group'"
+ di in gr " Number of individuals with missing data : " in ye "`nbmissing' " in gr "(" in ye "`=round(`=`percentmissing'*100',0.01)'%" in gr ")"
+ di ""
+ di in gr "{hline 46}"
+ di _col(22) in gr "test value" _col(35) in gr "df" _col(40) in gr "p-value"
+ di in gr "{hline 46}"
+ di _col(3) in gr "R1m" _col(24) in ye %8.5f `R1M_stat' _col(33) in ye %4.0f `R1M_ddl' _col(39) in ye %8.5f `R1M_p'
+ di in gr "{hline 46}"
+ di in gr ""
+ di ""
+ matrix globalFit=(`R1M_stat',`R1M_ddl',`R1M_p')
+ matrix coln globalFit=R1m df p
+ matrix rown globalFit=Global
+
+}
+else{
+ di in gr "Tests of the fit (tests R1m and Si) not performed when difficulties are fixed"
+ di ""
+}
+di in gr "Parameters of the Latent trait distribution :"
+di ""
+if "`difficulties'"==""{
+ if `nbcov'!=0{
+ di in gr " Latent trait mean in the subgroup `subgroup0' : fixed to 0"
+ }
+ else{
+ di in gr " Overall latent trait mean : fixed to 0"
+ }
+}
+di in gr " Variance of the Latent trait : SigmaÂČ=" in ye %8.5f (`=`=eB[1,`nbc']'')^2 in gr " (SE:"in ye %8.5f `= sqrt((2*`=eB[1,`nbc']')^2 *`=eV[`nbc',`nbc']' )' in gr ")"
+local varTheta=(`=`=eB[1,`nbc']'')^2
+local Varvartheta=(2*`=eB[1,`nbc']')^2 *`=eV[`nbc',`nbc']'
+
+di ""
+if `nbcov'!=0{
+ di in gr "Latent trait group effect :"
+ di ""
+ di in gr "{hline 101}"
+ if "`difficulties'"==""{
+ local compteur=`nbdifftot'
+ di _col(21) in gr "Coef." _col(31) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(58) in gr "[95% C.I.]" _col(71) in gr "D.St." _col(83) in gr "SS.III" _col(91) in gr "df" _col(95) in gr "V.expl."
+ di in gr "{hline 101}"
+ }
+ else{
+ di _col(22) in gr "Coef." _col(31) in gr "S.E." _col(41) in gr "z" _col(45) in gr "P>|z|" _col(58) in gr "[95% C.I.]" _col(71) in gr "D.St." _col(83) in gr "SS.III" _col(91) in gr "df" _col(95) in gr "V.expl."
+ di in gr "{hline 101}"
+ di _col(1) in gr "_cons" _col(19) in ye %7.4f `=eB[1,1]' _col(28) in ye %7.4f `=sqrt(eV[1,1])' _col(37) in ye %5.2f `=eB[1,1]/sqrt(eV[1,1])' _col(44) in ye %6.3f `=2*(1-normal(abs(eB[1,1]/sqrt(eV[1,1]))))' _col(52) in ye %7.4f `=eB[1,1]-1.96*sqrt(eV[1,1])' _col(61) in ye %7.4f `=eB[1,1]+1.96*sqrt(eV[1,1])' _col(75) in ye "."
+ di in gr "{hline 101}"
+ local compteur=1
+ }
+ forvalues i=1/`nbcov'{
+ local compteur=`compteur'+1
+ noi{
+ di _col(1) in gr "``=`nbit'+`i''' :" _col(82) in ye %6.3f `sst3_`=`i'+`nbit''' _col(91) in ye %2.0f `df_`=`i'+`nbit''' _col(95) in ye %6.3f `=`VarExp_`=`i'+`nbit'''*100' "%"
+
+ di _col(4) in gr "``=`nbit'+`i''' :" in ye " `ident`i'_1'" _col(25) in ye "0" _col(34) in ye "." _col(41) in ye "." _col(49) in ye "." _col(58) in ye "." _col(67) in ye "." _col(75) in ye "."
+ }
+ forvalues k=2/`nbModCov`i''{
+ local compteur=`compteur'+1
+ local estimate_e=eB[1,`compteur']
+ local se_e=sqrt(`=eV[`compteur',`compteur']')
+ noi{
+ di _col(4) in gr "``=`nbit'+`i''' :" in ye " `ident`i'_`k''" _col(19) in ye %7.4f `estimate_e' _col(28) in ye %7.4f `se_e' _col(37) in ye %5.2f `=`estimate_e'/`se_e'' _col(44) in ye %6.3f `=2*(1-normal(abs(`estimate_e'/`se_e')))' _col(52) in ye %7.4f `=`estimate_e'-1.96*`se_e'' _col(61) in ye %7.4f `=`estimate_e'+1.96*`se_e'' _col(70) in ye %6.3f `ESit`=`i'+`nbit''mod`k''
+ }
+ }
+ di in gr "{hline 101}"
+ }
+ di ""
+}
+else if "`difficulties'"!=""{
+ di in gr "Latent trait distribution"
+ di in gr "{hline 85}"
+ di _col(23) in gr "Coef." _col(36) in gr "S.E." _col(48) in gr "z" _col(57) in gr "P>|z|" _col(66) in gr "[95% Conf. Interval]"
+ di in gr "{hline 85}"
+ di _col(1) in gr "Mu" _col(20) in ye %8.5f `=eB[1,1]' _col(32) in ye %8.5f `=sqrt(eV[1,1]) ' _col(44) in ye %5.2f `=`=eB[1,1]'/`=sqrt(eV[1,1]) '' _col(56) in ye %6.3f `=2*(1-normal(abs(`=eB[1,1]'/`=sqrt(eV[1,1]) ')))' _col(66) in ye %8.5f `=`=eB[1,1]'-1.96*`=sqrt(eV[1,1]) '' _col(78) in ye %8.5f `=`=eB[1,1]'+1.96*`=sqrt(eV[1,1]) ''
+
+ di _col(1) in gr "Sigma" _col(20) in ye %8.5f `=eB[1,`nbc']' _col(32) in ye %8.5f `=sqrt(`=eV[`nbc',`nbc']')' _col(44) in ye %5.2f `=eB[1,`nbc']/sqrt(`=eV[`nbc',`nbc']')' _col(56) in ye %6.3f `=2*(1-normal(abs(eB[1,`nbc']/sqrt(`=eV[`nbc',`nbc']'))))' _col(66) in ye %8.5f `=eB[1,`nbc']-1.96*sqrt(`=eV[`nbc',`nbc']')' _col(78) in ye %8.5f `=eB[1,`nbc']+1.96*sqrt(`=eV[`nbc',`nbc']')'
+ di in gr "{hline 85}"
+ di ""
+}
+if "`difficulties'"==""{
+
+ matrix itemFit=J(`nbit',3,.)
+ local itemFitname ""
+ matrix coln itemFit=R1m df p
+ matrix rown globalFit=Global
+
+
+
+ di in gr "Items difficulty parameters :"
+ di ""
+ di in gr "{hline 80}"
+ di _col(1) in gr "Item" _col(21) in gr "Coef." _col(31) in gr "S.E." _col(43) in gr "[95% C.I.]" _col(66) in gr"Si" _col(70) in gr "df" _col(74) in gr "p-value"
+ di in gr "{hline 80}"
+ local compteur=1
+ forvalues i=1/`nbit'{
+ local itemFitname "`itemFitname' ``i'' "
+ di _col(1) in gr "``i'' :" _col(60) in ye %8.5f `S`i'_stat' _col(65) in ye %4.0f `S`i'_ddl' _col(73) in ye %8.5f `S`i'_p'
+ matrix itemFit[`i',1]=`S`i'_stat'
+ matrix itemFit[`i',2]=`S`i'_ddl'
+ matrix itemFit[`i',3]=`S`i'_p'
+ forvalues g=1/`=`moda`i''-1'{
+ di _col(4) in gr "modality :" in ye "`g'" _col(19) in ye %7.4f `=eB[1,`compteur']' _col(28) in ye %7.4f `=sqrt(`=eV[`compteur',`compteur']')' _col(37) in ye %7.4f `=eB[1,`compteur']-1.96*sqrt(`=eV[`compteur',`compteur']')' _col(46) in ye %7.4f `=eB[1,`compteur']+1.96*sqrt(`=eV[`compteur',`compteur']')'
+ local compteur=`compteur'+1
+ }
+ di in gr "{hline 80}"
+ }
+ matrix rown itemFit=`itemFitname'
+ di ""
+}
+else{
+ di in gr "Items difficulty parameters : fixed for the analysis"
+}
+
+
+ /*************************************/
+ /* ereturn */
+/*************************************/
+
+if "`difficulties'"==""{
+ matrix Varbeta=e(V)
+ local Varsigma=Varbeta[`=colsof(Varbeta)',`=colsof(Varbeta)']
+ matrix Varbeta=Varbeta[1..`nbit',1..`nbit']
+ matrix beta=e(b)
+ local sigma=beta[1,`=colsof(beta)']
+ matrix beta=beta[1,1..`nbit']
+ if `nbcov'!=0{
+ matrix Vartheta=e(b)
+ matrix Vartheta=beta[`nbit'..`=colsof(Vartheta)-1',`nbit'..`=colsof(Vartheta)-1']
+ matrix theta=e(b)
+ matrix theta=beta[1,`nbit'..`=colsof(theta)-1']
+ }
+ else{
+ local theta=0
+ local Vartheta=0
+ }
+}
+else{
+ if `nbcov'!=0{
+ matrix Vartheta=e(V)
+ local Varsigma=Vartheta[`=colsof(Vartheta)',`=colsof(Vartheta)']
+ matrix Vartheta=Vartheta[1..`=colsof(Vartheta)-1',1..`=colsof(Vartheta)-1']
+ matrix theta=e(b)
+ local sigma=theta[1,`=colsof(theta)']
+ matrix theta=theta[1,1..`=colsof(theta)-1']
+ }
+ else{
+ matrix theta=e(b)
+ local sigma=theta[1,`=colsof(theta)']
+ matrix Vtheta=e(b)
+ local Varsigma=Vtheta[`=colsof(Vtheta)',`=colsof(Vtheta)']
+ local theta=theta[1,1]
+ local vartheta=Vtheta[1,1]
+ }
+}
+
+
+
+ereturn clear
+ereturn scalar lll=`lll'
+ereturn scalar cn=`ccnn'
+ereturn scalar N=`Nbid'
+ereturn scalar Nit=`nbit'
+if `nbcov'!=0{
+ ereturn scalar Ncov=`nbcov'
+}
+
+if "`difficulties'"==""{
+ ereturn matrix Varbeta=Varbeta
+ ereturn matrix beta=beta
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ if `nbcov'!=0{
+ ereturn matrix Vartheta=Vartheta
+ ereturn matrix theta=theta
+ }
+ else{
+ matrix Vartheta=(0)
+ matrix coleq Vartheta=estimates
+ matrix coln Vartheta=mu
+ matrix roweq Vartheta=estimates
+ matrix rown Vartheta=mu
+ matrix theta=(0)
+ matrix coleq theta=estimates
+ matrix coln theta=mu
+ matrix rown theta=y1
+ ereturn matrix Vartheta=Vartheta
+ ereturn matrix theta=theta
+ }
+ ereturn matrix itemFit=itemFit
+ ereturn matrix globalFit=globalFit
+}
+else{
+ if `nbcov'!=0{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varsigma'
+ ereturn matrix Vartheta=Vartheta
+ ereturn matrix theta=theta
+ }
+ else{
+ ereturn scalar sigma=`sigma'
+ ereturn scalar Varsigma=`Varvartheta'
+ matrix Vartheta=(`vartheta')
+ matrix coleq Vartheta=estimates
+ matrix coln Vartheta=mu
+ matrix roweq Vartheta=estimates
+ matrix rown Vartheta=mu
+ ereturn matrix Vartheta=Vartheta
+ matrix theta=(`theta')
+ matrix coleq theta=estimates
+ matrix coln theta=mu
+ matrix rown theta=y1
+ ereturn matrix theta=theta
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+use `bddini', replace
+restore
+end
diff --git a/Modules/ado/personal/p/pcmold.ado b/Modules/ado/personal/p/pcmold.ado
new file mode 100644
index 0000000..0674bce
--- /dev/null
+++ b/Modules/ado/personal/p/pcmold.ado
@@ -0,0 +1,283 @@
+*! Version 2.3 10april2014
+************************************************************************************************************
+* Stata program : pcm
+* Estimate the parameters of the Partial Credit Model
+* Version 1 : December 17, 2007
+* Version 2 : July 15, 2011
+* Version 2.1 : October 18th, 2011 : -fixedvar- option, new presentation
+* Version 2.2 : October 23rd, 2013 : correction of -fixedvar- option
+* Version 2.3 : April 10th, 2014 : correction of -fixedvar- option
+*
+* Jean-benoit Hardouin, EA4275 Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* Faculties of Pharmaceutical Sciences & Medicine - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007-2014 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 pcmold,eclass
+version 8.0
+syntax varlist(min=3 numeric) [if] [in] [,rsm fixed(string) fixedvar(real -1) fixedmu short COVariates(varname) fixedvargroupc(string) vargroupc]
+preserve
+tempfile pcmfile
+qui save `pcmfile',replace
+
+if "`fixedmu'"!=""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the mean (fixedmu option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+if "`fixed'"!=""&"`fixedmu'"==""&`fixedvar'!=-1&"`covariates'"=="" {
+ di in red "You cannot fix in the same time the difficulties (fixed option) and the variance (fixedvar option) of the latent trait without covariables"
+ error 184
+}
+
+/*******************************************************************************
+ESTIMATION OF THE PARAMETERS
+********************************************************************************/
+
+marksample touse
+qui keep if `touse'
+qui count
+local N=r(N)
+tokenize `varlist'
+local nbitems : word count `varlist'
+
+if "`rsm'"=="" {
+ di in gr "Model: " in ye "Partial Credit Model"
+}
+else {
+ di in gr "Model: " in ye "Rating Scale Model"
+}
+
+tempname one var w id item it obs x chosen d score
+qui gen `one'=1
+qui gen `id'=_n
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui rename ``i'' `var'`i'
+ qui su `var'`i'
+ local moda`i'=`r(max)'
+ if `modamax'<`r(max)' {
+ local modamax=r(max)
+ }
+}
+qui genscore `var'1-`var'`nbitems' ,score(`score')
+qui collapse (sum) `w'=`one',by(`var'1-`var'`nbitems' `covariates')
+qui gen `id'=_n
+qui reshape long `var',i(`id') j(`item')
+qui drop if `var'==.
+qui gen `obs'=_n
+qui expand `=`modamax'+1'
+qui sort `id' `item' `obs'
+by `obs', sort: gen `x'=_n-1
+
+qui gen `chosen'=`var'==`x'
+qui tab `item', gen(`it')
+forvalues i=1/`nbitems' {
+ forvalues g=1/`modamax' {
+ qui gen `d'`i'_`g'=-1*`it'`i'*(`x'>=`g')
+ }
+}
+qui rename `w' `w'2
+bysort `id':egen score=sum(`x'*`chosen')
+qui su score
+local maxscore=r(max)
+
+
+if "`covariates'"!="" {
+ qui gen covw=`covariates'*`x'
+ local listcov covw
+}
+else {
+ local listcov
+}
+if `fixedvar'!=-1 {
+ local tmp=sqrt(`fixedvar')
+ constraint 1 `x'=`tmp'
+ local listconstr "constraints(1)"
+ local eq "eqs(slope) nrf(1)"
+}
+local eq "eqs(slope) nrf(1)"
+*set trace on
+if "`rsm'"=="" { /*PARTIAL CREDIT MODEL*/
+ *di "cas 1"
+ if "`fixed'"!="" { /*FIXED ITEMS DIFFICULTIES*/
+ *di "cas 2"
+ qui gen offset=0
+ local l=1
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ qui replace offset=offset+`fixed'[1,`l']*`d'`i'_`mi'
+ local ++l
+ }
+ }
+ if "`fixedmu'"!="" {
+ local mu
+ }
+ else {
+ local mu "`x'"
+ }
+*set trace on
+ if "`fixedvargroupc'"!=""|"`vargroupc'"!="" {/*INEQUAL VARIANCES*/
+ local var0: word 1 of `fixedvargroupc'
+ local var1: word 2 of `fixedvargroupc'
+ tempvar G0 G1
+ qui gen `G0'=groupc<0
+ qui gen `G1'=groupc>0
+ qui replace `G0'=`G0'*`x'
+ qui replace `G1'=`G1'*`x'
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`fixedvargroupc'"!="" {/*FIXED INEQUAL VARIANCES*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ local listconstr "constraints(1 2 3)"
+ }
+ else { /*FREE INEQUAL VARIANCE*/
+ local listconstr "constraints(1)"
+ }
+ local eq "eqs(B0 B1) nrf(2)"
+ }
+ eq slope:`x'
+ su
+ tab covw
+ di "ICI*******************jb"
+ di "`x' : x"
+ di "`listcov' : listcov"
+ di "`mu' : mu"
+ noi di "gllamm `x' `listcov' `mu',offset(offset) `listconstr' nocons i(`id') link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace `eq'"
+*set trace on
+ noi gllamm `x' `listcov' `mu' ,offset(offset) `listconstr' nocons i(`id') link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace `eq' iterate(100)
+ }
+ else if "`short'"!="" {
+ *di "cas 3"
+ eq slope:`x'
+ qui gllamm `x' `d'1_1-`d'`nbitems'_`modamax',i(`id') eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons init iterate(100)
+ tempname bsave Vsave
+ matrix `bsave'=e(b)
+ matrix `Vsave'=e(V)
+ restore
+ qui pcm `varlist' , fixed(`bsave')
+ }
+ else {
+ *di "cas 4"
+ di "no short"
+ eq slope:`x'
+ qui gen i=`id'
+ constraint 1 `x'=1
+ gllamm `x' `d'1_1-`d'`nbitems'_`modamax' `listcov',i(i) `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons iterate(100)
+ }
+}
+else {
+ *di "cas 5"
+
+ tempname step n
+ forvalues i=2/`modamax' {
+ qui gen `step'`i'=-1*(`x'>=`i')
+ }
+ forvalues i=1/`nbitems' {
+ qui gen `n'`var'`i'=(-1)*(`it'`i')*(`x')
+ }
+ qui sort `id' `item' `x'
+ eq slope:`x'
+ gllamm `x' `n'`var'1-`n'`var'`nbitems' `step'2-`step'`modamax' `listcov', i(`id') `listconstr' eqs(slope) link(mlogit) expand(`obs' `chosen' o) weight(`w') adapt trace nocons iterate(100)
+}
+
+tempname b V chol
+matrix b=e(b)
+matrix V=e(V)
+local ll=e(ll)
+matrix chol=e(chol)
+
+
+if "`rsm'"=="" {
+ di
+ di in gr "Number of observations: " in ye `N'
+ di in gr "Number of items: " in ye `nbitems'
+ di in gr "Number of parameters: " in ye `=`nbitems'*`modamax'+1'
+ di in gr "Log-likelihood: " in ye `ll'
+ di
+ di
+ di in gr "{hline 100}"
+ di in gr "Item" _col(10) "Modality" _col(20) "Parameter" _col(30) "Std Error"
+ di in gr "{hline 100}"
+ if "`fixed'"=="" {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ if "`short'"!="" {
+ di in ye _col(17) `j' _col(20) %9.6f `bsave'[1,`k'] in ye _col(30) %9.6f (`Vsave'[`k',`k'])^.5
+ }
+ else {
+ di in ye _col(17) `j' _col(20) %9.6f b[1,`k'] in ye _col(30) %9.6f (V[`k',`k'])^.5
+ }
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ else {
+ forvalues i=1/`nbitems' {
+ forvalues j=1/`modamax' {
+ if `j'==1 {
+ di in ye "``i''" _cont
+ }
+ local k=(`i'-1)*`modamax'+`j'
+ di in ye _col(17) `j' _col(20) %9.6f `fixed'[1,`k'] in ye _col(32) "(fixed)"
+ }
+ di in gr "{dup 100:-}"
+ }
+ }
+ if "`fixed'"==""&"`short'"=="" {
+ local k=`nbitems'*`modamax'+1
+ }
+ else if "`fixed'"!=""&"`fixedmu'"=="" {
+ di in ye "Mu" in ye _col(20) %9.6f b[1,1] _col(29) %10.6f (V[1,1])^.5
+ local k=2
+ }
+ else if "`fixed'"!=""&"`fixedmu'"!="" {
+ di in ye "Mu" in ye _col(20) %9.6f 0 _col(32) %10.6f "(fixed)"
+ local k=1
+ }
+ else {
+ local k=1
+ }
+ if "`covariates'"!="" {
+ di in ye "`covariates'" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ local k=`k'+1
+ }
+ if `fixedvar'==-1 {
+ di in ye "Sigma" in ye _col(20) %9.6f b[1,`k'] _col(29) %10.6f (V[`k',`k'])^.5
+ di in ye "Variance" in ye _col(20) %9.6f b[1,`k']^2 _col(29) %10.6f 2*(V[`k',`k'])^.5*b[1,`k']
+ }
+ else {
+ di in ye "Sigma" in ye _col(20) %9.6f `fixedvar'^.5 _col(32) %10.6f "(fixed)"
+ di in ye "Variance" in ye _col(20) %9.6f `fixedvar' _col(32) %10.6f "(fixed)"
+ }
+ di in gr "{hline 100}"
+ di
+ di
+}
+
+end
diff --git a/Modules/ado/personal/p/pcmtest.ado b/Modules/ado/personal/p/pcmtest.ado
new file mode 100644
index 0000000..6b9bce3
--- /dev/null
+++ b/Modules/ado/personal/p/pcmtest.ado
@@ -0,0 +1,1502 @@
+/********************************************************************************/
+/* v1.1 : Modified for being used after irt pcm and irt rsm */
+/********************************************************************************/
+* Needed modules :
+* gausshermite (http://www.freeirt.org)
+* gllamm version 2.3.14 (ssc describe gllamm)
+
+program define pcmtest, rclass
+version 11.0
+syntax [, APproximation NEw Group(string) NFit(string) Power(string) Alpha(string) GRAPHics FILEgraph(string) Sitest]
+preserve
+qui{
+tempfile bddtravail
+save `bddtravail', replace
+
+
+tempname x w val freq
+capture local cmdavant=e(cmd)
+if _rc!=0 | "`cmdavant'"!="pcmodel"{
+ capture local cmdavant=e(model1)
+ local condition ="`cmdavant'"=="pcm" | "`cmdavant'"=="rsm"
+ if _rc!=0 | `condition'!=1{
+ noi di in red "Please use pcmtest only after pcmodel, irt pcm or irt rsm"
+ error 100
+ }
+ else{
+ local testIrtPcm=1
+ }
+ if "`cmdavant'"=="rsm"{
+ local RSMtest=1
+ }
+}
+if "`graphics'"!=""{
+ if "`filegraph'"!=""{
+ local ReplaceGr2=0
+ local ReplaceGr=strpos("`filegraph'",",")
+ if `ReplaceGr'!=0{
+ local ReplaceGr=strpos(reverse("`filegraph'"),",")
+ local ReplaceGr2=strpos( substr("`filegraph'", strpos("`filegraph'",","), .), "r")!=0
+ local filegraphOld="`filegraph'"
+ local filegraph=rtrim(reverse(substr(reverse("`filegraph'"),`=`ReplaceGr'+1',.)))
+ }
+ if `ReplaceGr2'==0{
+ capture graph use "`filegraph'_LT_Sc", nodraw
+ if _rc==0{
+ noi di in red "`filegraph'_LT_Sc already exists (use option replace for replacing it)"
+ error 100
+ }
+ capture graph use "`filegraph'_MAP", nodraw
+ if _rc==0{
+ noi di in red "`filegraph'_MAP already exists (use option replace for replacing it)"
+ error 100
+ }
+ capture graph use "`filegraph'_Score_Distrib", nodraw
+ if _rc==0{
+ noi di in red "`filegraph'_Score_Distrib already exists (use option replace for replacing it)"
+ error 100
+ }
+ capture graph use "`filegraph'_Contrib", nodraw
+ if _rc==0{
+ noi di in red "`filegraph'_Contrib already exists (use option replace for replacing it)"
+ error 100
+ }
+ }
+ capture save "`filegraph'", replace
+ if _rc!=0{
+ noi di in red "Invalid path specification"
+ error 603
+ }
+ else{
+ erase "`filegraph'.dta"
+ }
+ }
+}
+
+ /***************************/
+ /* RĂ©cuperation de toutes */
+ /* les matrices estimées */
+/***************************/
+local itest=e(itest)
+if `itest'==0{
+ noi di in red "No tests of fit if the items difficulties are fixed (i.e. not estimated) "
+ error 100
+}
+local Elll=e(ll)
+local Ecn=e(cn)
+local EN=e(N)
+local ENit=e(Nit)
+local dataR1m=e(dataR1m)
+local mugauss=e(mugauss)
+local sdgauss=e(sdgauss)
+local ordre=e(order)
+local ENqual=e(Ncat)
+local ENquant=e(Ncont)
+local convergeance=e(converged)
+local Esigma=e(sigma)
+local EVarsigma=e(Varsigma)
+local ENumFit=e(NumFit)
+local Eitems=e(items)
+local IF=e(if)
+local IN=e(in)
+if "`IF'"!="" & "`IF'"!="."{
+ local if "`IF'"
+}
+if "`IN'"!="" & "`IN'"!="."{
+ local in "`IN'"
+}
+tempname EglobalFit EitemFit Etheta EVartheta Edelta EVardelta
+matrix `EglobalFit'=e(globalFit)
+matrix `EitemFit'=e(itemFit)
+matrix `Etheta'=e(theta)
+matrix `EVartheta'=e(Vartheta)
+matrix `Edelta'=e(delta)
+matrix `EVardelta'=e(Vardelta)
+local rsm=e(rsm)
+if "`rsm'"!="."{
+ local RSMtest2=1
+}
+else if "`RSMtest'"=="1"{
+ local RSMtest2=1
+}
+else{
+ local RSMtest2=0
+}
+
+/* irt pcm et irt rsm */
+
+if "`testIrtPcm'"=="1"{
+ local EN=e(N)
+ local mugauss=0
+ local if strpos(,s2)
+ local IFif=e(cmdline)
+ local PosIf=strpos("`IFif'"," if ")
+ local PosIn=strpos("`IFif'"," in ")
+ if strpos("`IFif'",",")==0{
+ local posComma="."
+ }
+ else{
+ local posComma=strpos("`IFif'",",")
+ }
+ if `PosIf'!=0 & `PosIn'!=0{
+ if `PosIf'<`PosIn'{
+ local if "`=substr("`IFif'",`=`PosIf'+4',`=`PosIn'-`PosIf'-4')'"
+ local in "`=substr("`IFif'",`=`PosIn'+4',`=`posComma'-`PosIn'-4')'"
+ }
+ else{
+ local in "`=substr("`IFif'",`=`PosIn'+4',`=`PosIf'-`PosIn'-4')'"
+ local if "`=substr("`IFif'",`=`PosIf'+4',`=`posComma'-`PosIf'-4')'"
+ }
+ }
+ else{
+ local if "`=substr("`IFif'",`=`PosIf'+4',`=`posComma'-`PosIf'-4')'"
+ local in "`=substr("`IFif'",`=`PosIn'+4',`=`posComma'-`PosIn'-4')'"
+ }
+ if `PosIf'==0{
+ local if=""
+ }
+ if `PosIn'==0{
+ local in=""
+ }
+ local itPcm=e(n_cuts1)
+ tempname Edelta DifComPcm tempmatdif EglobalFit EitemFit Etheta EVartheta EVardelta
+ matrix `DifComPcm'=e(b)
+ local nbcolMD=0
+ local plus=0
+ matrix `Edelta'=(.)
+ foreach i in `itPcm'{
+ local sum=0
+ forvalues it=2/`i'{
+ local tempmatdifnnn=`DifComPcm'[1,`=2*`it'+`plus'']-`DifComPcm'[1,`=2*`=`it'-1'+`plus'']
+ matrix `tempmatdif'=(`=-`tempmatdifnnn'')
+ matrix `Edelta'=`Edelta',`tempmatdif'
+ }
+ local plus=`plus'+2*`i'
+ }
+ matrix `Edelta'=`Edelta'[....,2...]
+ local sdgauss=`DifComPcm'[1,3]
+ local Eitems=e(items1)
+}
+qui capture matrix list r(globalFitTot)
+if _rc!=0{
+ local testafaire=1
+}
+else{
+ local testafaire=0
+}
+if "`new'"!=""{
+local testafaire=1
+}
+if "`nfit'"!=""{
+ local numFit=`nfit'
+}
+else{
+ local numFit=.
+}
+local varlist `Eitems'
+local nbit: word count `varlist'
+local nbitsuf=1
+if `nbit'<2{
+ noi di in red "No tests of fit if the number of items is less than 2"
+ error 100
+}
+if `nbit'==2{
+ noi di in gr "Only the R1m test is performed if the number of items is equal to 2"
+ local nbitsuf=0
+}
+tokenize `varlist'
+qui{
+ marksample touse,novarlist
+ keep if `touse'
+ local ordre=0
+ forvalues i=1/`nbit'{
+ tempname rep__`i'
+ tab ``i'', matrow(`rep__`i'')
+ local ordre=`ordre'+`=rowsof(`rep__`i'')'-1
+ forvalues j=1/`=rowsof(`rep__`i'')'{
+ replace ``i''=`j'-1 if ``i''==`rep__`i''[`j',1]
+ }
+ }
+ if `RSMtest2'==1{
+ local ordre=`=rowsof(`rep__1')'-2+`nbit'
+ }
+ q memory
+}
+tempfile bddini datatest bdd_b bdd_se bdd_seg bdd_P bdd_R1 bdd_G
+save `bdd_b', replace
+save `datatest', replace
+
+ /*************************************/
+ /* test R1m */
+/*************************************/
+
+noi di in gr "Performing R1m test"
+qui{
+ q memory
+ local matsizeini=r(matsize)
+ set matsize `matsizeini'
+ tempfile matU matU1 matU2
+ tempname dm cell row
+ egen `dm'=rowmiss(`varlist')
+ replace `dm'=`dm'>0
+ tab `dm',matcell(`cell') matrow(`row')
+ local nbmissing=`cell'[2,1]
+ local percentmissing=`cell'[2,1]/(`cell'[1,1]+`cell'[2,1])
+ if `nbmissing'==.{
+ local nbmissing=0
+ local percentmissing=0
+ }
+ keep if `dm'==0
+ local NbIdFit=_N
+ if `numFit'==.{
+ local propFit=1
+ local propFitPb=0
+ }
+ else if `numFit'>`NbIdFit'{
+ local propFit=1
+ local propFitPb=1
+ }
+ else{
+ local propFit=`numFit'/`NbIdFit'
+ local propFitPb=2
+ }
+ drop `dm'
+ keep `varlist'
+ forvalues i=1/`nbit'{
+ rename ``i'' pre_``i''
+ }
+ forvalues i=1/`nbit'{
+ gen it`i'=pre_``i''
+ drop pre_``i''
+ }
+ local nbscore=1
+ forvalues i=1/`nbit'{
+ qui tab it`i'
+ local nbmoda_`i'=r(r)
+ local nbscore=`nbscore'+`nbmoda_`i''-1
+ }
+ local score "it1"
+ forvalues i=2/`nbit'{
+ local score "`score'+it`i'"
+ }
+ gen score=`score'
+ save `bdd_se', replace
+ local N=_N
+/* autogroup */
+ if "`group'"==""{
+ su score, d
+ local list `=r(p25)'
+ if `=r(p25)'!=`=r(p50)'{
+ local list "`list' `=r(p50)'"
+ }
+ if `=r(p50)'!=`=r(p75)'{
+ local list "`list' `=r(p75)'"
+ }
+ if `=r(p75)'!=`=`nbscore'-1'{
+ local list "`list' `=`nbscore'-1'"
+ }
+ if wordcount("`list'")==1{
+ noi di in red "Problem with Autogroup option: creating groups from the score quartiles is not possible"
+ }
+ tab score, matcell(`freq') matrow(`val')
+ local nbgroup=wordcount("`list'")
+ }
+ else{
+ tab score, matcell(`freq') matrow(`val')
+ local list "`group'"
+ local nbgroup=wordcount("`list'")
+ if real(word("`list'",`nbgroup'))<`=`nbscore'-1'{
+ local list "`group' `=`nbscore'-1'"
+ local nbgroup=wordcount("`list'")
+ }
+ }
+ local nbmodagpe=0
+ forvalues i=1/`nbit'{
+ local nbmodagpe=`nbmodagpe'+`nbmoda_`i''
+ }
+ gen g=.
+ local liminf1=-1
+ forvalues i=1/`nbgroup'{
+ local limsup`i'=real("`=word("`list'",`i')'")
+ if `i'>1{
+ local liminf`i'=real("`=word("`list'",`=`i'-1')'")
+ }
+ replace g=`i' if score<=`limsup`i'' & score>`liminf`i''
+ }
+ forvalues i=1/`nbgroup'{
+ su score if g==`i'
+ local N`i'=r(N)
+ }
+ save `bdd_se', replace
+ save `bdd_seg', replace
+ use `bdd_se', replace
+ local count=0
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ if `j'==1{
+ local diffest`i'_`j'=0
+ }
+ else{
+ local count=`count'+1
+ local diffest`i'_`j'=round(`Edelta'[1,`count'],0.001)+`diffest`i'_`=`j'-1''
+ }
+ local num`i'_`j' "exp(`=`j'-1'*x-`diffest`i'_`j'')"
+ if `j'==1{
+ local denom`i' "1"
+ }
+ else{
+ local denom`i' "`denom`i''+`num`i'_`j''"
+ }
+ }
+ forvalues j=1/`nbmoda_`i''{
+ local PCM`i'_`j' "(`num`i'_`j'')/(`denom`i'')"
+ }
+ }
+ local nbcomb=1
+ forvalues i=1/`nbit'{
+ local nbcomb=`nbcomb'*`nbmoda_`i''
+ }
+ clear
+ set obs `=int(`nbcomb'+0.1)'
+ local facteur=1
+ gen score=0
+ local order "score"
+ forvalues i=1/`nbit'{
+ gen it`i'=floor(mod(_n/`facteur',`nbmoda_`i''))
+ local facteur=`facteur'*`nbmoda_`i''
+ replace score=score+it`i'
+ tab it`i', gen(i`i'c)
+ local order "`order' it`i'"
+ }
+ order `order', first
+ sort score
+ tab score, gen(score)
+ local nbscore=r(r)
+ gen P=1
+ local gdN=_N
+
+ /*************************************/
+/* */
+/* Calcul de la probabilité de */
+/* chaque patern de réponses */
+/* */
+/*************************************/
+
+ if "`approximation'"==""{
+ local percentcount=0
+ noi di ""
+ noi di in ye "`gdN'" in gr " response pattern probabilities to compute"
+ noi di in gr "Percentage of completion"
+ noi di in gr "----|---10%---|---20%---|---30%---|---40%---|---50%"
+ _dots 0, title(Loop computation of theorical probabilities of each response pattern) reps(100)
+ forvalues l=1/`gdN'{
+ local exp ""
+ forvalues i=1/`nbit'{
+ forvalues m=1/`nbmoda_`i''{
+ if i`i'c`m'[`l']==1{
+ if "`exp'"==""{
+ local exp "`PCM`i'_`m''"
+ }
+ else{
+ local exp "`exp'*`PCM`i'_`m''"
+ }
+ }
+ }
+ }
+ gausshermite `exp' , sigma(`sdgauss') mu(`mugauss') display
+ replace P=round(r(int),0.000001) if _n==`l'
+ local percentcountplus=floor(`l'*100/`gdN')
+ forvalues percen=`=`percentcount'+1'/`percentcountplus'{
+ nois _dots `percen' 0
+ }
+ local percentcount=`percentcountplus'
+ }
+ }
+ else{
+ noi di in gr "Response pattern probabilities computation"
+ replace P=0
+ sort score it*
+ save `bdd_P', replace
+ local NbCol=1
+ local compteur=1
+ forvalues i=1/`nbit'{
+ tempname Dit`i'
+ matrix `Dit`i''=`Edelta'[1,`compteur'..`=`compteur'+`nbmoda_`i''-2']
+ if colsof(`Dit`i'')>`NbCol'{
+ local NbCol=colsof(`Dit`i'')
+ }
+ local compteur=`compteur'+`nbmoda_`i''-1
+ }
+ clear
+ noi di in gr "----|---25%---|---50%---|---75%---|---100%
+ qui _dots 0, title(Title) reps(40)
+ set obs 1000000
+ gen id=_n
+ gen theta=`mugauss'+invnormal(uniform())*`sdgauss'
+ forvalues i=1/`nbit'{
+ gen denom`i'=1
+ gen num`i'_0=1
+ forvalues j=1/`=`nbmoda_`i''-1'{
+ gen num`i'_`j'=exp(ln(num`i'_`=`j'-1') + theta-`Dit`i''[1,`j'])
+ replace denom`i'=denom`i'+num`i'_`j'
+ }
+ forvalues j=0/`=`nbmoda_`i''-1'{
+ gen p`i'_`j'=num`i'_`j'/denom`i'
+ }
+ drop denom`i'
+ drop num`i'_*
+ forvalues j=1/`=`nbmoda_`i''-1'{
+ replace p`i'_`j'=p`i'_`j'+p`i'_`=`j'-1'
+ }
+ gen it`i'=0
+ gen random`i'=runiform()
+ forvalues j=1/`=`nbmoda_`i''-1'{
+ replace it`i'=`j' if random`i'>=p`i'_`=`j'-1' & random`i'`limsup`i'' | `j'<=`liminf`i''{
+ local nbscoreg`i'=`nbscoreg`i''-1
+ capture drop s`=`j'+1'g`i'
+ }
+ }
+ local order "`order' *g`i'"
+ use `matU1', replace
+ keep if score<=`limsup`i'' & score>`liminf`i''
+ gen g=`i'
+ forvalues a=1/`nbit'{
+ forvalues b=1/`nbmoda_`a''{
+ capture rename i`a'c`b' i`a'c`b'g`i'
+ }
+ }
+ forvalues a=1/`nbscore'{
+ capture rename score`a' s`a'g`i'
+ forvalues j=1/`=wordcount("`list'")'{
+ if `=`a'-1'>`limsup`i'' | `=`a'-1' <= `liminf`i''{
+ capture drop s`a'g`j'
+ }
+ }
+ }
+ tempfile bloc`i'
+ sort `sort'
+ save `b`i'_1', replace
+ }
+ local order ""
+ forvalues i=1/`=wordcount("`list'")'{
+ tempfile b`i'_2
+ local order "`order' *g`i'"
+ use `matU2', replace
+ keep if score<=`limsup`i'' & score>`liminf`i''
+ gen g=`i'
+ forvalues a=1/`nbit'{
+ forvalues b=1/`nbmoda_`a''{
+ capture rename i`a'c`b' i`a'c`b'g`i'b
+ }
+ }
+ forvalues a=1/`nbscore'{
+ capture rename score`a' s`a'g`i'b
+ forvalues j=1/`=wordcount("`list'")'{
+
+ if `=`a'-1'>`limsup`i'' | `=`a'-1' <= `liminf`i''{
+ capture drop s`a'g`j'
+ }
+ }
+ }
+ sort `sort'
+ save `b`i'_2', replace
+ describe
+ local mat_`i'=r(k)-3-`nbit'
+ }
+noi di "W matrix computation"
+/* Matrice W */
+ local nbscoreg0=0
+ forvalues g=1/`nbgroup'{
+ tempname W_`g'i W_`g'
+ tempfile b`g'_2b
+ qui q memory
+ if `mat_`g''>r(matsize) & `mat_`g''<=r(m_matsize){
+ set matsize `mat_`g''
+ }
+ if `mat_`g''>r(m_matsize){
+ noi di in red "Error, not enough memory to allocate to the W matrix computation"
+ }
+ matrix `W_`g''=J(`mat_`g'',`mat_`g'',.)
+ use `b`g'_2', replace
+ local count=1
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ rename i`i'c`j'g`g'b v`count'b
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename s`s'g`g'b v`count'b
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ local Ncol_`g'_=`count'-1
+ save `b`g'_2b', replace
+ use `b`g'_1', replace
+ local count=1
+ forvalues i=1/`nbit'{
+ forvalues j=1/`nbmoda_`i''{
+ rename i`i'c`j'g`g' v`count'
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename s`s'g`g' v`count'
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ local Ncol_`g'__=`count'-1
+ forvalues i=1/`=`count'-1'{
+ replace v`i'=P if round(v`i',0.000001)!=round(0,0.000001)
+ }
+ local countW_`g'=`count'-1
+ merge `sort' using `b`g'_2b'
+ drop _merge
+ forvalues i=1/`mat_`g''{
+ forvalues j=1/`mat_`g''{
+ gen prod=v`i'*v`j'b
+ qui su prod
+ matrix `W_`g''[`i',`j']=r(sum)
+ drop prod
+ }
+ }
+ capture matrix `W_`g'i'=invsym(`W_`g'')
+ if _rc!=0{
+ capture matrix `W_`g'i'=inv(`W_`g'')
+ }
+ if _rc!=0{
+ noi di in red "Error while computing the Wg matrix"
+ }
+ tempname A rank_
+ mata: `A'=J(1,1,.)
+ mata: `A'[1,1]=rank(st_matrix("`W_`g''"))
+ mata: st_matrix("`rank_'",`A')
+ local rank`g'=`rank_'[1,1]
+ }
+/* Matrice poid */
+ forvalues g=1/`nbgroup'{
+ tempfile bddSe`g' b`g'_2bi
+ use `bdd_seg', replace
+ keep if g==`g'
+ gen Pd=1
+ contract `sort', f(nb)
+ sort `sort'
+ save `bddSe`g'', replace
+ use `b`g'_2b', replace
+ sort `sort'
+ merge `sort' using `bddSe`g''
+ drop _merge
+ replace nb=0 if nb==.
+ gen nbth=P*`N'
+ gen Di=(nb-nbth)/sqrt(`N')
+ sort `sort'
+ save `b`g'_2bi', replace
+ if `countW_`g''>10{
+ set matsize `countW_`g''
+ }
+ else{
+ set matsize 10
+ }
+ tempname deviation_`g'
+ matrix `deviation_`g''=J(`countW_`g'',1,.)
+ use `b`g'_2bi', replace
+ gen Pobs=nb/`N'
+ gen Diff=Pobs-P
+ forvalues j=1/`countW_`g''{
+ replace v`j'b=v`j'b*Diff
+ su v`j'b
+ matrix `deviation_`g''[`j', 1]=r(sum)*sqrt(`N')
+ }
+ }
+ local sum=0
+ local ddl=0
+ local rank ""
+ qui q memory
+ if `matsizeini'>r(matsize) & 10000 > r(m_matsize){
+ set matsize `matsizeini'
+ }
+ else{
+ set matsize 10000
+ }
+ tempname graphContribPond
+ matrix `graphContribPond'=J(`nbgroup',2,.)
+ forvalues g=1/`nbgroup'{
+ tempname G_`g'
+ capture matrix `G_`g''=`deviation_`g'''*`W_`g'i'*`deviation_`g''
+ if _rc!=0{
+ noi di in red "Error, not enought memory to allocate to the W matrix computation
+ }
+ local sum=`sum'+`G_`g''[1,1]
+ local ddl=`ddl'+`rank`g''
+ local rank "`rank'`rank`g'' "
+ matrix `graphContribPond'[`g',1]=`g'
+ matrix `graphContribPond'[`g',2]=`G_`g''[1,1]
+ }
+ local ddl=`ddl'-`ordre'-1
+ set matsize `matsizeini'
+}
+local R1m_group "`list'"
+local R1m_Rank `rank'
+local R1M_ddl=`ddl'
+local R1M_stat=`sum'*`propFit'
+local R1M_p=`=1-chi2(`ddl', `R1M_stat')'
+
+/*************************************/
+/* tests Si */
+/*************************************/
+if `nbitsuf'==1 & "`sitest'"!=""{
+ qui{
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ }
+ tempname DGibase
+ matrix `DGibase'=J(6,`countbase',.)
+ use `bdd_seg', replace
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ tab it`ii', gen(i`ii'c)
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ matrix `DGibase'[2,`countbase']=`ii'
+ matrix `DGibase'[3,`countbase']=`j'
+ su i`ii'c`j'
+ matrix `DGibase'[4,`countbase']=r(sum)
+ }
+ drop i`ii'c*
+ }
+ tab score, gen(s)
+ forvalues s=1/`nbscore'{
+ capture su s`s'
+ if _rc!=0{
+ gen s`s'=0
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ matrix `DGibase'[2,`countbase']=`s'
+ su s`s'
+ matrix `DGibase'[4,`countbase']=r(sum)
+ }
+ use `matU2', replace
+ local countbase=0
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ local countbase=`countbase'+1
+ su P if i`ii'c`j'==1
+ matrix `DGibase'[5,`countbase']=r(sum)*`N'
+ matrix `DGibase'[6,`countbase']=(`DGibase'[4,`countbase']-`DGibase'[5,`countbase'])/sqrt(`N')
+ }
+ }
+ forvalues s=1/`nbscore'{
+ local countbase=`countbase'+1
+ su P if score`s'==1
+ matrix `DGibase'[5,`countbase']=r(sum)*`N'
+ matrix `DGibase'[6,`countbase']=(`DGibase'[4,`countbase']-`DGibase'[5,`countbase'])/sqrt(`N')
+ }
+ local colbase=`countbase'
+ }
+ forvalues i=1/`nbit'{
+ tempfile mU2_`i' mU_`i'
+ noi di in gr "Performing Si test for the `i'th item"
+ qui{
+ use `matU2', replace
+ gen g=.
+ local liminf1=-1
+ forvalues g=1/`nbgroup'{
+ replace g=`g' if score<=`limsup`g'' & score>`liminf`g''
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ gen testi`i'c`j'g`g'=0
+ replace testi`i'c`j'g`g'=i`i'c`j' if g==`g'
+ }
+ }
+ local count=1
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ rename i`ii'c`j' v`count'b
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename score`s' v`count'b
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ rename testi`i'c`j'g`g' v`count'b
+ local count=`count'+1
+ }
+ }
+ local nbarrive`i'=`count'-1
+ sort `sort'
+ save `mU2_`i'', replace
+ use `matU1', replace
+ gen g=.
+ local liminf1=-1
+ forvalues g=1/`nbgroup'{
+ replace g=`g' if score<=`limsup`g'' & score>`liminf`g''
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ gen testi`i'c`j'g`g'=0
+ replace testi`i'c`j'g`g'=i`i'c`j' if g==`g'
+ }
+ }
+ local count=1
+ forvalues ii=1/`nbit'{
+ forvalues j=1/`nbmoda_`ii''{
+ rename i`ii'c`j' v`count'
+ local count=`count'+1
+ }
+ }
+ forvalues s=1/`=`nbscore'+1'{
+ capture rename score`s' v`count'
+ if _rc ==0{
+ local count=`count'+1
+ }
+ }
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ rename testi`i'c`j'g`g' v`count'
+ local count=`count'+1
+ }
+ }
+ sort `sort'
+ merge `sort' using `mU2_`i''
+ drop _merge
+ if `nbarrive`i''>r(matsize) & `nbarrive`i''<=r(m_matsize){
+ set matsize `nbarrive`i''
+ }
+ if `nbarrive`i''>r(m_matsize){
+ noi di in red "Error, not enought memory to allocate to the W matrix computation"
+ }
+ tempname i`i'W
+ matrix `i`i'W'=J(`nbarrive`i'',`nbarrive`i'',0)
+ if `=`nbarrive`i''*`nbarrive`i'''>3000{
+ noi di in gr "----|---25%---|---50%---|---75%---|---100%
+ qui _dots 0, title(Loop computation of theorical probabilities of each response pattern) reps(40)
+ local percentcount=0
+ local countS=1
+ }
+ forvalues ii=1/`nbarrive`i''{
+ su v`ii'
+ if r(max)>=0.000001{
+ forvalues j=1/`nbarrive`i''{
+ gen prod=v`ii'*v`j'b
+ qui su prod
+ matrix `i`i'W'[`ii',`j']=r(sum)
+ drop prod
+ if `=`nbarrive`i''*`nbarrive`i'''>3000{
+ local percentcountplus=floor(`countS'*40/`=`nbarrive`i''*`nbarrive`i''')
+ forvalues percen=`=`percentcount'+1'/`percentcountplus'{
+ nois _dots `percen' 0
+ }
+ local percentcount=`percentcountplus'
+ local countS=`countS'+1
+ }
+ }
+ }
+ else{
+ if `=`nbarrive`i''*`nbarrive`i'''>3000{
+ local percentcountplus=floor((`countS'+`nbarrive`i''-1)*40/`=`nbarrive`i''*`nbarrive`i''')
+ forvalues percen=`=`percentcount'+1'/`percentcountplus'{
+ nois _dots `percen' 0
+ }
+ local percentcount=`percentcountplus'
+ local countS=`countS'+`nbarrive`i''
+ }
+ }
+ }
+ if `=`nbarrive`i''*`nbarrive`i'''>3000{
+ noi di ""
+ }
+ tempname i`i'Wi
+ capture matrix `i`i'Wi'=invsym(`i`i'W')
+ if _rc!=0{
+ capture matrix `i`i'Wi'=inv(`i`i'W')
+ }
+ if _rc!=0{
+ noi di in red "Error while computing the Wg matrix"
+ }
+ tempname A rank_
+ mata: `A'=J(1,1,.)
+ mata: `A'[1,1]=rank(st_matrix("`i`i'W'"))
+ mata: st_matrix("`rank_'",`A')
+ local i`i'rank=`rank_'[1,1]
+ tempname plus`i' DGi_`i' DGi`i'_a DGi`i'_b DGi_`i'_v2
+ matrix `plus`i''=J(6,`=`nbarrive`i''-`colbase'',.)
+ matrix `DGi_`i''=`DGibase',`plus`i''
+ matrix `DGi`i'_a'=J(1,`=colsof(`DGibase')',0)
+ matrix `DGi`i'_b'=J(1,`=`nbarrive`i''-`colbase'',.)
+ matrix `DGi_`i'_v2'=`DGi`i'_a',`DGi`i'_b'
+ save `mU_`i'', replace
+ local count=`colbase'
+ use `bdd_seg', replace
+ tab it`i', gen(i`i'c)
+ forvalues g=1/`nbgroup'{
+ forvalues j=1/`nbmoda_`i''{
+ local count=`count'+1
+ matrix `DGi_`i''[2,`count']=`i'
+ matrix `DGi_`i''[3,`count']=`j'
+ matrix `DGi_`i''[1,`count']=`g'
+ su i`i'c`j' if g==`g'
+ matrix `DGi_`i''[4,`count']=r(sum)
+ }
+ }
+ use `mU_`i'', replace
+ forvalues t=`=`colbase'+1'/`nbarrive`i''{
+ su P if v`t'b==1
+ matrix `DGi_`i''[5,`t']=r(sum)*`N'
+ matrix `DGi_`i''[6,`t']=(`DGi_`i''[4,`t']-`DGi_`i''[5,`t'])/sqrt(`N')
+ matrix `DGi_`i'_v2'[1,`t']=(`DGi_`i''[4,`t']-`DGi_`i''[5,`t'])/sqrt(`N')
+ }
+ set matsize `matsizeini'
+ tempname tDGi_`i' tDGi_`i'_v2 G G_v2
+ matrix `tDGi_`i''=`DGi_`i''[6,1..`=colsof(`DGi_`i'')']'
+ matrix `tDGi_`i'_v2'=`DGi_`i'_v2''
+ matrix `G'=`tDGi_`i'''*`i`i'Wi'*`tDGi_`i''
+ matrix `G_v2'=`tDGi_`i'_v2''*`i`i'Wi'*`tDGi_`i'_v2'
+ local sum=`G'[1,1]
+ local sum_v2=`G_v2'[1,1]
+ local rank "`i`i'rank'"
+ local ddl=(`nbgroup'-1)*(`nbmoda_`i''-1)
+ }
+ local S`i'_rank=`rank'
+ local S`i'_ddl=`ddl'
+ local S`i'_stat=`sum'*`propFit'
+ local S`i'_p=`=1-chi2(`S`i'_ddl', `S`i'_stat')'
+ }
+}
+
+/* Graphs : */
+
+if "`graphics'"!=""{
+ noi di ""
+ noi di ""
+ noi di in gr "Graphics:"
+ tempfile graph
+ qui{
+ local debut=1
+ local fin=1
+ forvalues i=1/`nbit'{
+ local fin=`fin'+`nbmoda_`i''-2
+ tempname it`i'
+ matrix `it`i''=`Edelta'[1,`debut'..`fin']
+ local fin=`fin'+1
+ local debut=`debut'+`nbmoda_`i''-1
+ }
+ clear
+ use `bdd_se', replace
+ local scmin=1
+ local scmax=-1
+ forvalues i=1/`nbit'{
+ local scmax=`scmax'+`nbmoda_`i''-1
+ }
+ gen select=score<=`scmin'
+ su score if select==1
+ local scorereel_scmin=r(mean)
+ replace select=score>=`scmax'
+ su score if select==1
+ local scorereel_scmax=r(mean)
+ replace score=`scmin' if score<`scmin'
+ replace score=`scmax' if score>`scmax'
+ tab score, matcell(matname)
+ local tottab=r(N)
+ clear
+ set obs 2000
+ gen theta=_n/100-10
+ gen scoreth=0
+ forvalues i=1/`nbit'{
+ tempname D`i'
+ matrix `D`i''=J(1,`nbmoda_`i'',0)
+ gen eV`i'_0=1
+ gen SeV`i'=1
+ forvalues j=1/`=`nbmoda_`i''-1'{
+ matrix `D`i''[1,`=`j'+1']=`it`i''[1,`j']+`D`i''[1,`j']
+ gen eV`i'_`j'=exp(`j'*theta-`D`i''[1,`=`j'+1'])
+ replace SeV`i'=SeV`i'+eV`i'_`j'
+ }
+ gen p`i'_0=eV`i'_0/SeV`i'
+ forvalues j=1/`=`nbmoda_`i''-1'{
+ gen p`i'_`j'=eV`i'_`j'/SeV`i'
+ replace scoreth=scoreth+(eV`i'_`j'/SeV`i')*`j'
+ }
+ }
+ drop e* S* p*
+ su scoreth
+ local scmin=ceil(r(min))
+ local scmax=floor(r(max))
+ gen sc=abs(scoreth-`scorereel_scmin')
+ sort sc
+ local valini_`scmin'=theta[1]
+ drop sc
+ gen sc=abs(scoreth-`scorereel_scmax')
+ sort sc
+ local valini_`scmax'=theta[1]
+ drop sc
+ tempname scoretheta
+ matrix `scoretheta'=J(2,`scmax',.)
+ forvalues i=`=`scmin'+1'/`=`scmax'-1'{
+ matrix `scoretheta'[1,`i']=`i'
+ gen sc=abs(scoreth-`i')
+ sort sc
+ local valini_`i'=theta[1]
+ drop sc
+ }
+ matrix `scoretheta'[1,1]=`scorereel_scmin'
+ matrix `scoretheta'[1,`scmax']=`scorereel_scmax'
+ forvalues i=1/`scmax'{
+ matrix `scoretheta'[2,`i']=`valini_`i''
+ }
+ tempfile graphscthscobstheta
+ save `graphscthscobstheta', replace
+ clear
+ use `bdd_se', replace
+ gen select=score<=`scmin'
+ su score if select==1
+ local scorereel_scmin=r(mean)
+ replace select=score>=`scmax'
+ su score if select==1
+ local scorereel_scmax=r(mean)
+ replace score=`scmin' if score<`scmin'
+ replace score=`scmax' if score>`scmax'
+ drop g
+ forvalues i=1/`nbit'{
+ gen rep`i' = it`i'
+ drop it`i'
+ }
+ contract rep1-rep`nbit' score, f(wt2)
+ gen id=_n
+ reshape long rep, i(id) j(it)
+ drop if rep==.
+ gen obs=_n
+ forvalues i=1/`nbit'{
+ expand `nbmoda_`i'' if it==`i'
+ }
+ by obs, sort: gen `x'=_n-1
+ gen choix=rep==`x'
+ rename it item
+ tab item, gen(it)
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`nbmoda_`i''-1'{
+ gen d_i`i'_m`g'=(-1)*it`i'*(`x'>=`g')
+ }
+ }
+ gen difficulties=0
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`nbmoda_`i''-1'{
+ replace difficulties=difficulties+`it`i''[1,`g']*d_i`i'_m`g'
+ }
+ }
+ tab score, gen(score__) matrow(nom)
+ local nbmodscore=r(r)
+ forvalues k=1/`nbmodscore'{
+ replace score__`k'=`x' if score__`k'==1
+ local ident=nom[`k',1]
+ if `k'==1{
+ local ident1=`ident'
+ }
+ rename score__`k' score_`ident'
+ }
+ eq slope: `x'
+ noi di in gr "Performing graphics"
+ use `graphscthscobstheta', replace
+ gen sc=abs(scoreth-`scorereel_scmin')
+ sort sc
+ local limginf=theta[1]-1.5
+ drop sc
+ gen sc=abs(scoreth-`scorereel_scmax')
+ sort sc
+ local limgsup=theta[1]+1.5
+ drop sc
+ drop if theta<`limginf' | theta>`limgsup'
+ capture graph drop Obs_vs_Exp_LT
+ capture graph drop MAP
+ capture graph drop Score_Distrib
+ capture graph drop Contrib
+ twoway (line scoreth theta, sort) , ytitle(Score) xtitle(Latent trait) title("Expected scores depending on individual latent traits", size(medium)) scheme(s2mono) graphregion(fcolor(white) ifcolor(white)) name("LT_Sc", replace)
+ tempfile gEO
+ graph save `gEO', replace
+ if "`filegraph'"!=""{
+ graph save "`filegraph'_LT_Sc", replace
+ }
+ clear
+ set obs `=int(`=rowsof(matname)+colsof(`Edelta')'+0.1)'
+ gen theta=.
+ gen diff=0
+ gen freq=.
+ forvalues i=1/`=rowsof(matname)'{
+ replace theta=`scoretheta'[2,`i'] if _n==`i'
+ replace freq=matname[`i',1]/`tottab' if _n==`i'
+ }
+ su freq
+ local tadatzouinzou=-r(max)/8
+ forvalues i=1/`=colsof(`Edelta')'{
+ replace theta=`Edelta'[1,`i'] if _n==`i'+`=rowsof(matname)'
+ replace freq=`tadatzouinzou' if _n==`i'+`=rowsof(matname)'
+ replace diff=1 if _n==`i'+`=rowsof(matname)'
+ }
+ sort diff theta
+ bysort diff: replace freq=freq-(`tadatzouinzou'/5) if theta1
+ gen d2=.
+ replace d2=(d1-d1[_n-1])/(theta-theta[_n-1]) if _n>1
+ replace d2=-d2
+ su freq
+ local freqmin=r(min)
+ local freqmax=r(max)
+ su d2
+ local d2max=r(max)
+ local d2min=`d2max'*`freqmax'/`freqmin'
+ label variable freq "Freq. (%)"
+ label variable d2 "Information"
+ sort theta
+ twoway (spike freq theta if diff==0, lwidth(thick) horizontal xscale(alt axis(1)) ) (scatter theta freq if diff==1,mcolor(black) msymbol(plus)) (line theta d2, xaxis(2) xscale(alt axis(2))) , yscale(noline) ylabel(#5, angle(horizontal)) xscale(range(`freqmin' `freqmax') axis(1)) xscale(reverse range(`d2min' `d2max') axis(2)) yscale(range(`mininf' `maxinf')) xline(0) xlabel(0 (0.05) `freqmax') title(, size(medium)) legend(order(1 "Persons" 2 "Thresholds location" 3 "Information curve") cols(1) size(small)) scheme(s2mono) graphregion(fcolor(white) ifcolor(white)) ytitle(Latent trait) title(MAP) name("MAP", replace)
+ tempfile gMAP
+ graph save `gMAP', replace
+ if "`filegraph'"!=""{
+ graph save "`filegraph'_MAP", replace
+ }
+ clear
+ use "`dataR1m'"
+ keep score P
+ collapse (sum) P, by(score)
+ sort score
+ save `bdd_G', replace
+ clear
+ use "`datatest'"
+ keep `varlist'
+ tempname dm SumScore
+ egen `dm'=rowmiss(`varlist')
+ replace `dm'=`dm'>0
+ keep if `dm'==0
+ tempname SumScore
+ egen `SumScore'=rowtotal(`varlist')
+ gen Pobs=1
+ rename `SumScore' score
+ keep Pobs score
+ local tot=_N
+ collapse (sum) Pobs, by(score)
+ replace Pobs=Pobs/`tot'
+ sort score
+ merge 1:1 score using `bdd_G'
+ gen g=.
+ drop _merge
+ sort g
+ save `bdd_G', replace
+ clear
+ svmat `graphContribPond'
+ rename `graphContribPond'1 g
+ rename `graphContribPond'2 Contrib
+ sort g
+ merge g using `bdd_G'
+ su Contrib
+ replace Contrib=Contrib/r(sum)
+ capture label drop g
+ local liminf1=-1
+ forvalues i=1/`nbgroup'{
+ local limsup`i'=real("`=word("`list'",`i')'")
+ if `i'>1{
+ local liminf`i'=real("`=word("`list'",`=`i'-1')'")
+ }
+ replace g=`i' if score<=`limsup`i'' & score>`liminf`i''
+ if `i'==1{
+ label define g `i' "[0;`limsup`i'']"
+ }
+ else if `i' == `nbgroup'{
+ label define g `i' "]`liminf`i'';`=`nbscore'-1']", a
+ }
+ else{
+ label define g `i' "]`liminf`i'';`limsup`i'']", a
+ }
+ }
+ label values g g
+ gen nb=P*`EN'
+ su score [iweight=nb]
+ local MoyThScore=r(mean)
+ local SdThScore=r(sd)
+ gen nbObs=Pobs*`EN'
+ su score [iweight=nbObs]
+ local MoyObsScore=r(mean)
+ local SdObdcore=r(sd)
+ drop _merge
+ tempfile BDD
+ sort score
+ save `BDD', replace
+ clear
+ set obs `=(`=r(max)'+2)*100'
+ gen score=(_n/100)-1
+ gen p=normalden(score,`MoyThScore',`SdThScore')
+ gen pobs=normalden(score,`MoyObsScore',`SdObdcore')
+ sort score
+ merge score using `BDD'
+ gen score1=score if Pobs!=.
+ gen scorep=score1-0.15
+ gen scorep2=score1+0.15
+ twoway (bar Pobs scorep, horizontal barwidth(0.3)) (bar P scorep2, horizontal barwidth(0.3)) (line score p, lpattern(solid)lcolor(black)) (line score pobs, lpattern(vshortdash) lcolor(gs12)), yscale(reverse) scheme(s2mono) xtitle(%) xscale(range(0 0.01)) xlabel(#5) legend(order(1 "% observed" 3 "" 2 "% expected" 4 "") cols(2) size(small)) title("Observed and expected" "scores distribution", size(medium)) graphregion(fcolor(white)) name("Score_Distrib", replace)
+ tempfile gTS
+ graph save `gTS', replace
+ if "`filegraph'"!=""{
+ graph save "`filegraph'_totscore", replace
+ }
+ graph hbar (sum) Pobs P Contrib, over(g) yvaroptions(relabel(1 "% observed" 2 "% expected" 3 "% R1m contribution") label(labcolor(none) labsize(zero))) title("Groups contribution to" "the R1m statistic", size(medium)) legend(cols(1) size(small)) ytitle("%") scheme(s2mono) graphregion(fcolor(white)) bar(3, fcolor(black)) bar(1, fcolor(gs8)) bar(2, fcolor(gs13)) name("Contrib", replace)
+ tempfile gSG
+ graph save `gSG', replace
+ if "`filegraph'"!=""{
+ graph save "`filegraph'_scoregp", replace
+ }
+ }
+}
+tempname globalFit itemFit
+matrix `globalFit'=(`R1M_stat',`R1M_ddl',`R1M_p')
+if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix itemFit=J(`nbit',3,.)
+ forvalues i=1/`nbit'{
+ matrix itemFit[`i',1]=`S`i'_stat'
+ matrix itemFit[`i',2]=`S`i'_ddl'
+ matrix itemFit[`i',3]=`S`i'_p'
+ }
+}
+if "`alpha'"==""{
+ local alpha=0.05
+}
+tempname g it r Power bB cC Discriminant
+matrix `g'=`globalFit'
+if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix `it'=itemFit
+}
+if "`nfit'"==""{
+ local `r'=1
+}
+else{
+ local `r'=`NbIdFit'/`nfit'
+}
+local `g'_t=`g'[1,1]*``r''
+if `g'[1,2]<=200{
+ local `Power'_t_R1m= 1-nchi2(`g'[1,2],``g'_t',invchi2tail(`g'[1,2],`alpha'))
+}
+else{
+ local `Power'_t_R1m=1-(normal((invchi2tail(`g'[1,2],`alpha')-(`g'[1,2]+``g'_t'))/sqrt(2*(`g'[1,2]+2*``g'_t'))))
+}
+if `nbitsuf'==1 & "`sitest'"!=""{
+ forvalues i=1/`nbit'{
+ local `it'_`i'_t=`it'[`i',1]*``r''
+ if `it'[`i',2]>200 | ``it'_`i'_t'>1000{
+ local `Power'_t_S`i'=1-(normal((invchi2tail(`it'[`i',2],`alpha')-(`it'[`i',2]+``it'_`i'_t'))/sqrt(2*(`it'[`i',2]+2*``it'_`i'_t'))))
+ }
+ else{
+ local `Power'_t_S`i'= 1-nchi2(`it'[`i',2],``it'_`i'_t',invchi2tail(`it'[`i',2],`alpha'))
+ }
+ }
+}
+if "`nfit'"!=""{
+ local `r'_2=``r''*`nfit'/`NbIdFit'
+ local `g'_newN=`g'[1,1]*``r'_2'
+ if `g'[1,2]<=200{
+ local `Power'_newN_R1m= 1-nchi2(`g'[1,2],``g'_newN',invchi2tail(`g'[1,2],`alpha'))
+ }
+ else{
+ local `Power'_newN_R1m=1-(normal((invchi2tail(`g'[1,2],`alpha')-(`g'[1,2]+``g'_newN'))/sqrt(2*(`g'[1,2]+2*``g'_newN'))))
+ }
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ forvalues i=1/`nbit'{
+ local `it'_`i'_newN=`it'[`i',1]*``r'_2'
+ if `it'[`i',2]>200 | ``it'_`i'_newN'>1000{
+ local `Power'_newN_S`i'=1-(normal((invchi2tail(`it'[`i',2],`alpha')-(`it'[`i',2]+``it'_`i'_newN'))/sqrt(2*(`it'[`i',2]+2*``it'_`i'_newN'))))
+ }
+ else{
+ local `Power'_newN_S`i'= 1-nchi2(`it'[`i',2],``it'_`i'_newN',invchi2tail(`it'[`i',2],`alpha'))
+ }
+ }
+ }
+}
+if "`power'"!=""{
+ if `g'[1,2]<=200{
+ local `g'_newP=npnchi2(`=`g'[1,2]',`=invchi2tail(`=`g'[1,2]',`alpha')',`=1-`power'')
+ }
+ else{
+ local `bB'=2*`=`g'[1,2]'-2*`=invchi2tail(`=`g'[1,2]',`alpha')'-4*(invnormal(`=1-0.8'))^2
+ local `cC'=(`=invchi2tail(`=`g'[1,2]',`alpha')')^2-2*`=`g'[1,2]'*`=invchi2tail(`=`g'[1,2]',`alpha')'+(`=`g'[1,2]')^2-2*`=`g'[1,2]'*(invnormal(`=1-0.8'))^2
+ local `Discriminant'=(``bB'')^2-4*``cC''
+ local `g'_newP=(sqrt(``Discriminant'')-``bB'')/2
+ }
+ local `r'_3=``g'_newP'/``g'_t'
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ forvalues i=1/`nbit'{
+ local `it'_`i'_newP=``it'_`i'_t'*``r'_3'
+ if `it'[`i',2]>200 | ``it'_`i'_newP'>1000{
+ local `Power'_newP_S`i'=1-(normal((invchi2tail(`it'[`i',2],`alpha')-(`it'[`i',2]+``it'_`i'_newP'))/sqrt(2*(`it'[`i',2]+2*``it'_`i'_newP'))))
+ }
+ else{
+ local `Power'_newP_S`i'= 1-nchi2(`it'[`i',2],``it'_`i'_newP',invchi2tail(`it'[`i',2],`alpha'))
+ }
+ }
+ }
+}
+}
+
+ /*************************************/
+ /* print */
+/*************************************/
+
+di ""
+di ""
+di in gr "Global tests of the fit : test R1m"
+di in gr " groups : " in ye "`R1m_group'"
+di in gr " Number of individuals with missing data : " in ye "`nbmissing' " in gr "(" in ye "`=round(`=`percentmissing'*100',0.01)'%" in gr ")"
+di ""
+if "`nfit'"!="" & "`power'"!=""{
+ di in gr "{hline 90}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `nfit' _col(76) in gr "N = " in ye %6.0f `=ceil(`NbIdFit'*``r'_3')'
+ di _col(16) in gr "df" _col(26) in gr "R1m" _col(32) in gr "p-val" _col(39) in gr "Power" _col(49) in gr "R1m" _col(55) in gr "p-val" _col(62) in gr "Power" _col(72) in gr "R1m" _col(78) in gr "p-val" _col(85) in gr "Power"
+ di in gr "{hline 90}"
+ di _col(3) in gr "R1m" _col(14) in ye %4.0f `R1M_ddl' _col(23) in ye %6.1f ``g'_t' _col(32) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_t')' _col(39) in ye %5.4f ``Power'_t_R1m' _col(46) in ye %6.1f ``g'_newN' _col(55) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_newN')' _col(62) in ye %5.4f ``Power'_newN_R1m' _col(69) in ye %6.1f ``g'_newP' _col(78) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_newP')' _col(85) in ye %5.4f `power'
+ di in gr "{hline 90}"
+ di in gr ""
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ di in gr "Items specific tests of the fit : tests Si"
+ di in gr ""
+ di in gr "{hline 90}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `nfit' _col(76) in gr "N = " in ye %6.0f `=ceil(`NbIdFit'*``r'_3')'
+ di _col(1) in gr "Item" _col(16) in gr "df" _col(27) in gr "Si" _col(32) in gr "p-val" _col(39) in gr "Power" _col(50) in gr "Si" _col(55) in gr "p-val" _col(62) in gr "Power" _col(73) in gr "Si" _col(78) in gr "p-val" _col(85) in gr "Power"
+ di in gr "{hline 90}"
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'' :" _col(14) in ye %4.0f `S`i'_ddl' _col(23) in ye %6.1f ``it'_`i'_t' _col(32) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_t')' _col(39) in ye %5.4f ``Power'_t_S`i'' _col(46) in ye %6.1f ``it'_`i'_newN' _col(55) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_newN')' _col(62) in ye %5.4f ``Power'_newN_S`i'' _col(69) in ye %6.1f ``it'_`i'_newP' _col(78) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_newP')' _col(85) in ye %5.4f ``Power'_newP_S`i''
+ di in gr "{hline 90}"
+ }
+ }
+}
+else if "`nfit'"!=""{
+ di in gr "{hline 67}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `nfit'
+ di _col(16) in gr "df" _col(26) in gr "R1m" _col(32) in gr "p-val" _col(39) in gr "Power" _col(49) in gr "R1m" _col(55) in gr "p-val" _col(62) in gr "Power"
+ di in gr "{hline 67}"
+ di _col(3) in gr "R1m" _col(14) in ye %4.0f `R1M_ddl' _col(23) in ye %6.1f ``g'_t' _col(32) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_t')' _col(39) in ye %5.4f ``Power'_t_R1m' _col(46) in ye %6.1f ``g'_newN' _col(55) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_newN')' _col(62) in ye %5.4f ``Power'_newN_R1m'
+ di in gr "{hline 67}"
+ di in gr ""
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ di in gr "Items specific tests of the fit : tests Si"
+ di in gr ""
+ di in gr "{hline 67}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `nfit'
+ di _col(1) in gr "Item" _col(17) in gr "df" _col(26) in gr "Si" _col(32) in gr "p-val" _col(39) in gr "Power" _col(50) in gr "Si" _col(55) in gr "p-val" _col(62) in gr "Power"
+ di in gr "{hline 67}"
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'' :" _col(14) in ye %4.0f `S`i'_ddl' _col(23) in ye %6.1f ``it'_`i'_t' _col(32) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_t')' _col(39) in ye %5.4f ``Power'_t_S`i'' _col(46) in ye %6.1f ``it'_`i'_newN' _col(55) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_newN')' _col(62) in ye %5.4f ``Power'_newN_S`i''
+ di in gr "{hline 90}"
+ }
+ }
+}
+else if "`power'"!=""{
+ di in gr "{hline 67}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `=ceil(`NbIdFit'*``r'_3')'
+ di _col(16) in gr "df" _col(26) in gr "R1m" _col(32) in gr "p-val" _col(39) in gr "Power" _col(49) in gr "R1m" _col(55) in gr "p-val" _col(62) in gr "Power"
+ di in gr "{hline 67}"
+ di _col(3) in gr "R1m" _col(14) in ye %4.0f `R1M_ddl' _col(23) in ye %6.1f ``g'_t' _col(32) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_t')' _col(39) in ye %5.4f ``Power'_t_R1m' _col(46) in ye %6.1f ``g'_newP' _col(55) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_newP')' _col(62) in ye %5.4f `power'
+ di in gr "{hline 67}"
+ di in gr ""
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ di in gr "Items specific tests of the fit : tests Si"
+ di in gr ""
+ di in gr "{hline 67}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit' _col(53) in gr "N = " in ye %6.0f `=ceil(`NbIdFit'*``r'_3')'
+ di _col(1) in gr "Item" _col(16) in gr "df" _col(27) in gr "Si" _col(32) in gr "p-val" _col(39) in gr "Power" _col(50) in gr "Si" _col(55) in gr "p-val" _col(62) in gr "Power"
+ di in gr "{hline 67}"
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'' :" _col(14) in ye %4.0f `S`i'_ddl' _col(23) in ye %6.1f ``it'_`i'_t' _col(32) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_t')' _col(39) in ye %5.4f ``Power'_t_S`i'' _col(46) in ye %6.1f ``it'_`i'_newP' _col(55) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_newP')' _col(62) in ye %5.4f ``Power'_newP_S`i''
+ di in gr "{hline 67}"
+ }
+ }
+}
+else{
+ di in gr "{hline 44}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit'
+ di _col(16) in gr "df" _col(26) in gr "R1m" _col(32) in gr "p-val" _col(39) in gr "Power"
+ di in gr "{hline 44}"
+ di _col(3) in gr "R1m" _col(14) in ye %4.0f `R1M_ddl' _col(23) in ye %6.1f ``g'_t' _col(32) in ye %5.4f `=1-chi2(`=`g'[1,2]', ``g'_t')' _col(39) in ye %5.4f ``Power'_t_R1m'
+ di in gr "{hline 44}"
+ di in gr ""
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ di in gr "Items specific tests of the fit : tests Si"
+ di in gr ""
+ di in gr "{hline 44}"
+ di _col(30) in gr "N = " in ye %6.0f `NbIdFit'
+ di _col(1) in gr "Item" _col(16) in gr "df" _col(27) in gr "Si" _col(32) in gr "p-val" _col(39) in gr "Power"
+ di in gr "{hline 44}"
+ forvalues i=1/`nbit'{
+ di _col(1) in gr "``i'' :" _col(14) in ye %4.0f `S`i'_ddl' _col(23) in ye %6.1f ``it'_`i'_t' _col(32) in ye %5.4f `=1-chi2(`=`it'[`i',2]', ``it'_`i'_t')' _col(39) in ye %5.4f ``Power'_t_S`i''
+ di in gr "{hline 44}"
+ }
+ }
+}
+
+ /*************************************/
+ /* ereturn */
+/*************************************/
+
+
+return clear
+if "`nfit'"!=""{
+ return scalar NumFit=`nfit'
+ tempname globalFitNu itemFitNu
+ matrix `globalFitNu'=(``g'_newN',`R1M_ddl',`=1-chi2(`=`g'[1,2]', ``g'_newN')',``Power'_newN_R1m',`nfit')
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix `itemFitNu'=J(`nbit',5,.)
+ forvalues i=1/`nbit'{
+ matrix `itemFitNu'[`i',1]=``it'_`i'_newN'
+ matrix `itemFitNu'[`i',2]=`S`i'_ddl'
+ matrix `itemFitNu'[`i',3]=`=1-chi2(`=`it'[`i',2]', ``it'_`i'_newN')'
+ matrix `itemFitNu'[`i',4]=``Power'_newN_S`i''
+ matrix `itemFitNu'[`i',5]=`nfit'
+ }
+ }
+ matrix coln `globalFitNu'=R1m df alpha power N
+ matrix rown `globalFitNu'=Global
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix coln `itemFitNu'=Si df alpha power N
+ return matrix itemFitNu=`itemFitNu'
+ }
+ return matrix globalFitNu=`globalFitNu'
+}
+if "`power'"!=""{
+ return scalar PowFit=`power'
+ tempname globalFitPo itemFitPo
+ matrix `globalFitPo'=(``g'_newP',`R1M_ddl',`=1-chi2(`=`g'[1,2]', ``g'_newP')',`power',`=ceil(`NbIdFit'*``r'_3')')
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix `itemFitPo'=J(`nbit',5,.)
+ forvalues i=1/`nbit'{
+ matrix `itemFitPo'[`i',1]=``it'_`i'_newP'
+ matrix `itemFitPo'[`i',2]=`S`i'_ddl'
+ matrix `itemFitPo'[`i',3]=`=1-chi2(`=`it'[`i',2]', ``it'_`i'_newP')'
+ matrix `itemFitPo'[`i',4]=``Power'_newP_S`i''
+ matrix `itemFitPo'[`i',5]=`=ceil(`NbIdFit'*``r'_3')'
+ }
+ }
+ matrix coln `globalFitPo'=R1m df alpha power N
+ matrix rown `globalFitPo'=Global
+ if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix coln `itemFitPo'=Si df alpha power N
+ return matrix itemFitPo=`itemFitPo'
+ }
+ return matrix globalFitPo=`globalFitPo'
+}
+tempname globalFitTot itemFitTot
+matrix `globalFitTot'=(``g'_t',`R1M_ddl',`=1-chi2(`=`g'[1,2]', ``g'_t')',``Power'_t_R1m',`NbIdFit')
+if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix `itemFitTot'=J(`nbit',5,.)
+ forvalues i=1/`nbit'{
+ matrix `itemFitTot'[`i',1]=``it'_`i'_t'
+ matrix `itemFitTot'[`i',2]=`S`i'_ddl'
+ matrix `itemFitTot'[`i',3]=`=1-chi2(`=`it'[`i',2]', ``it'_`i'_t')'
+ matrix `itemFitTot'[`i',4]=``Power'_t_S`i''
+ matrix `itemFitTot'[`i',5]=`NbIdFit'
+ }
+}
+matrix coln `globalFitTot'=R1m df alpha power N
+matrix rown `globalFitTot'=Global
+if `nbitsuf'==1 & "`sitest'"!=""{
+ matrix coln `itemFitTot'=Si df alpha power N
+ return matrix itemFitTot=`itemFitTot'
+}
+return matrix globalFitTot=`globalFitTot'
+use `bddtravail', replace
+restore
+end
diff --git a/Modules/ado/personal/p/pcmtest.hlp b/Modules/ado/personal/p/pcmtest.hlp
new file mode 100644
index 0000000..e6d8ca1
--- /dev/null
+++ b/Modules/ado/personal/p/pcmtest.hlp
@@ -0,0 +1,65 @@
+{smcl}
+{* Mars 2012}{...}
+{hline}
+help for {hi:pcmtest}{right:JFH}
+{hline}
+
+{title:Global and item specific tests of the fit for Partial Cradit Model}
+
+{p 8 14 2}{cmd:pcmtest}, [{cmdab:g:roup}({it:numlist})
+{cmdab:n:fit}(#)
+{cmdab:p:ower}(#)
+{cmdab:graph:ics}(#)
+{cmdab:a:lpha}(#)
+{cmdab:ap:proximation}
+{cmdab:n:ew}]
+
+{title:Description}
+
+{p 8 14 2}{cmd:pcmtest} allows to test the fit between an observed data and the
+ partial credit model.{p_end}
+{p 14 14 2}The global test of the fit (test R1m) can only be computed if the data
+ contains at least two items. Item specific test of the fit (Si tests) can only be
+ computed if the data contains at least three items. {p_end}
+{p 14 14 2}{cmd:pcmtest} is only performed if item difficulties have been
+ estimated using {cmd:pcmodel}. {cmd:pcmtest} can be performed either if covariates
+ have been included in {cmd:pcmodel} or not.
+
+{title:Options}
+
+{p 4 8 2}{cmd:group} specifies groups of scores, by defining the superior limits of
+ each group
+
+{p 4 8 2}{cmd:nfit} specifies the size of a virtual sample with items response
+ distribution strictly identical to that observed ({cmd:nfit} can deal with
+ over-power problems when tests of the fit are performed on large samples).
+
+{p 4 8 2}{cmd:power} specifies the desired power for a test R1m, and estimates the
+ corresponding size of a virtual sample with items response distribution strictly
+ identical to that observed.
+
+{p 4 8 2}{cmd:alpha} specifies the type I error used to performe the tests of the fit
+ (default: 0.05).
+
+{p 4 8 2}{cmd:graphics} displays several graphs (Graphical fit between the observed and
+ expected latent traits according to the individual scores, graphic of MAP, graphic of
+ groups contribution to the R1m statistic, and graphice of the observed and expected
+ score distribution)
+
+{p 4 8 2}{cmd:approximation} Computation of the pattern response probabilities using
+simulation instead of Gauss Hermitte quadratures. Computation should be quicker for
+high number of items or responses modalities.
+
+{p 4 8 2}{cmd:new} Do not use pattern response probabilities computed during a previous
+test of the fit, compute it an other time! (allows changing the computation methodology)
+
+{title:Author}
+
+{p 4 8 2}Jean-François HAMEL{p_end}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help pcmodel}, {help gllamm}, {help simirt}
+, {help raschtest}.{p_end}
+
+
diff --git a/Modules/ado/personal/p/pcmtest.sthlp b/Modules/ado/personal/p/pcmtest.sthlp
new file mode 100644
index 0000000..87328a1
--- /dev/null
+++ b/Modules/ado/personal/p/pcmtest.sthlp
@@ -0,0 +1,98 @@
+{smcl}
+{* Mars 2012}{...}
+{hline}
+help for {hi:pcmtest}
+{hline}
+
+
+{title:Global and item specific tests of fit for a Partial Credit Model or a Rating Scale Model}
+
+{p 8 14 2}{cmd:pcmtest}, [{cmdab:g:roup}({it:numlist})
+{cmdab:ne:w}
+{cmdab:nf:it}(#)
+{cmdab:p:ower}(#)
+{cmdab:a:lpha}(#)
+{cmdab:ap:proximation}
+{cmdab:s:itest}
+{cmdab:graph:ics}
+{cmdab:file:graph}({it:filegraph[, replace])]
+
+
+{title:Description}
+
+{p 8 14 2}{cmd:pcmtest} allows testing the fit between observed data and a
+ partial credit model or a rating scale model.{p_end}
+{p 14 14 2}The global test of fit (test R1m) can only be computed if the data
+ contains at least two items. Item specific test of fit (Si tests) can only be
+ computed if the data contains at least three items. {p_end}
+{p 14 14 2}{cmd:pcmtest} is only performed if item difficulties have been
+ estimated using {cmd:pcmodel}. {cmd:pcmtest} can be performed whether covariates
+ have been included in {cmd:pcmodel} or not.
+
+
+{title:Options}
+
+{p 4 8 2}{cmd:group} specifies groups of scores, by defining the upper limit of
+ each group
+
+{p 4 8 2}{cmd:new} allows changing the computation methodology of the pattern
+response probabilities between several tests of fit, rather than using the pattern
+response probabilities stored in Stata memory.
+
+{p 4 8 2}{cmd:nfit} specifies the size of a virtual sample with items response
+ distribution strictly identical to that observed ({cmd:nfit} can deal with
+ over-power problems when fit tests are performed on large samples).
+
+{p 4 8 2}{cmd:power} specifies the desired power for a R1m test, and estimates the
+ corresponding size of a virtual sample with items response distribution strictly
+ identical to that observed.
+
+{p 4 8 2}{cmd:alpha} specifies the type I error used to perform the test of fit
+ (default: 0.05).
+
+{p 4 8 2}{cmd:approximation} Computation of the pattern response probabilities using
+simulation instead of Gauss Hermitte quadratures. Computation should be quicker for
+high number of items or responses categories.
+
+{p 4 8 2}{cmd:sitest} performs item specific test of fit (Si tests).
+
+{p 4 8 2}{cmd:graphics} displays several graphs (Distribution of the latent trait
+depending on the individual scores, graphic of MAP, graphic of
+ the groups contributions to the R1m statistic, and graphic of the observed and expected
+ score distribution).
+
+{p 4 8 2}{cmd:filegraph} indicates the filename and path for saving the graphs
+(four graphs are store: {it:filegraph}_LT_Sc, {it:filegraph}_MAP, {it:filegraph}_Contrib
+and {it:filegraph}_Score_Distrib.)
+
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:e(globalFitTot)}: Results of the R1m test performed on the observed sample.
+
+{p 4 8 2}{cmd:e(itemFitTot)}: Results of the Si tests performed on the observed sample.
+
+{p 4 8 2}{cmd:e(globalFitPo)}: Results of the R1m test corresponding
+to the indicated power.
+
+{p 4 8 2}{cmd:e(itemFitPo)}: Results of the Si tests corresponding
+to the indicated power.
+
+{p 4 8 2}{cmd:e(globalFitTot)}: Results of the R1m test corresponding
+to the indicated sample size.
+
+{p 4 8 2}{cmd:e(itemFitTot)}: Results of the Si tests corresponding
+to the indicated sample size.
+
+
+{title:Author}
+
+{p 4 8 2}Jean-François Hamel{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jeanfrancois.hamel@chu-angers.fr":jeanfrancois.hamel@chu-angers.fr}{p_end}
+
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help pcmodel}, {help gllamm}, {help simirt}
+, {help raschtest}.{p_end}
diff --git a/Modules/ado/personal/p/predraschwlm.ado b/Modules/ado/personal/p/predraschwlm.ado
new file mode 100644
index 0000000..3abc1db
--- /dev/null
+++ b/Modules/ado/personal/p/predraschwlm.ado
@@ -0,0 +1,66 @@
+program define predraschwlm,rclass
+syntax varlist , genlt(string) id(string)
+
+tempfile filesave
+qui save `filesave',replace
+tempname diff theta
+matrix `diff'=r(beta)
+matrix `theta'=r(theta)
+
+
+qui count
+local N=r(N)
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+
+tempname item offset id
+qui gen `id'=_n
+
+forvalues i=0/`nbitems' {
+ local thetascore`i'=`theta'[1,`=`i'+1']
+}
+
+tempname nbmiss
+qui egen `nbmiss'=rowmiss(`varlist')
+tempfile s
+qui save `s',replace
+forvalues i=1/`N' {
+ use `s',clear
+ if `nbmiss'[`i']!=0 {
+ local w`i'=0
+ local l`i'=1
+ forvalues j=1/`nbitems' {
+ local item`j'=``j''[`N']
+ local diff`j'=`diff'[1,`j']
+ local rep`i'_`j'=``j''[`i']
+ if `rep`i'_`j''!=. {
+ local w`i' `w`i''+exp(x-`diff`j'')/(1+exp(x-`diff`j''))^2
+ local l`i' `l`i''*exp(`rep`i'_`j''*(x-`diff`j''))/(1+exp(x-`diff`j''))
+ }
+ }
+ local w`i' sqrt(`w`i'')
+ *di "`i'"
+ clear
+ qui set obs 20001
+ qui gen u=_n
+ qui gen x=(u-10001)/1000
+ qui gen f=`w`i''*`l`i''
+ qui gsort -f
+ local tl`i'=x[1]
+ }
+}
+qui use `filesave',clear
+qui capture drop `genlt'
+qui gen `genlt'=.
+tempname scores
+qui genscore `varlist',score(`scores')
+forvalues i=0/`nbitems' {
+ qui replace `genlt'=`thetascore`i'' if `scores'==`i'
+}
+forvalues i=1/`N' {
+ if `genlt'[`i']==. {
+ qui replace `genlt'=`tl`i'' in `i' if `genlt'==.
+ }
+}
+end
diff --git a/Modules/ado/personal/qualmosta/Grille QUALMOSTA.docx b/Modules/ado/personal/qualmosta/Grille QUALMOSTA.docx
new file mode 100644
index 0000000..3901977
Binary files /dev/null and b/Modules/ado/personal/qualmosta/Grille QUALMOSTA.docx differ
diff --git a/Modules/ado/personal/qualmosta/~$ille QUALMOSTA.docx b/Modules/ado/personal/qualmosta/~$ille QUALMOSTA.docx
new file mode 100644
index 0000000..072c8e7
Binary files /dev/null and b/Modules/ado/personal/qualmosta/~$ille QUALMOSTA.docx differ
diff --git a/Modules/ado/personal/r/old/raschfit2.ado b/Modules/ado/personal/r/old/raschfit2.ado
new file mode 100644
index 0000000..350af8a
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschfit2.ado
@@ -0,0 +1,315 @@
+************************************************************************************************************
+* Stata program : Raschfit
+* The Raschfit and the Raschfit-fast procedures to construct sub-scales of items
+* Release 2 : June 8, 2004
+*
+* Historic
+* Version 1 (2004-05-06) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* Use the Stata programs mmsrm, raschtest and gammasym who can be download on http://anaqol.free.fr
+* News about this program :http://anaqol.free.fr
+*
+* 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 raschfit,rclass
+version 7.0
+syntax varlist(min=2 numeric) [,KERnel(integer 0) NBSCales(integer 1) ITEMSorder(string) nofast]
+if "`itemsorder'"=="" {
+ local itemsorder mspinv
+}
+local nbitemstot : word count `varlist'
+tokenize `varlist'
+
+tempfile raschfitfile
+qui save `raschfitfile',replace
+preserve
+
+tempname affect
+matrix define `affect'=J(1,`nbitemstot',0)
+matrix colnames `affect'=`varlist'
+
+tempname rep item matbetadim1 matbetadim2
+if `kernel'!=0 {
+ local listkernel
+ forvalues i=1/`kernel' {
+ local listkernel `listkernel' `rep'`i'
+ matrix `affect'[1,`i']=1
+ }
+}
+
+local dim=0
+local nbitemsnosel=`nbitemstot'
+local nbitemstotdim1=`nbitemstot'
+local nbitemsnoselukernel=`nbitemstot'-`kernel'
+
+
+tempvar id betadim1 betadim2
+forvalues i=1/`nbitemstot' {
+ qui drop if ``i''==.
+ rename ``i'' `rep'`i'
+}
+qui gen `id'=_n
+tempfile filescale
+qui save `filescale',replace
+
+
+while `nbitemsnosel'>2&`dim'<`nbscales' {
+ use `filescale',replace
+ local iteration=0
+ local dim=`dim'+1
+ if `dim'>1 {
+ local kernel=0
+ local listkernel
+ }
+
+ di in green "SCALE: " in yellow `dim'
+ di in green "{hline 9}"
+ di
+ tempname result`dim'
+ local listitemsnosel
+ local varlist`dim'
+ tokenize `varlist'
+ forvalues i=1/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ local varlist`dim' `varlist`dim'' ``i''
+ local listitemsnosel `listitemsnosel' `rep'`i'
+ }
+ }
+ local nbitemsnosel:word count `listitemsnosel'
+ if `dim'>1 {
+ local nbitemstotdim`dim':word count `listitemsnosel'
+ }
+
+ if `kernel'>=2 {
+ local fixed=`kernel'
+ }
+ else {
+ local fixed=2
+ }
+ matrix define `result`dim''=J(`=`nbitemstotdim`dim''-`fixed'',`=`nbitemstotdim`dim''+7',0)
+
+ tempname order`dim' affect`dim'
+ matrix `order`dim''=J(1,`nbitemstotdim`dim'',0)
+ matrix `affect`dim''=J(1,`nbitemstotdim`dim'',0)
+
+ if "`itemsorder'"=="msp"|"`itemsorder'"=="mspinv" {
+ di in green _col(0) "The program is ordering the items"
+ qui msp `listkernel' `listitemsnosel',c(-99) notest kernel(`kernel')
+ local scale1 "`r(scale1)'"
+ local scalenum1 "`r(scalenum1)'"
+ tokenize `scalenum1'
+ local listitemsselnum
+ forvalues j=`=`nbitemstotdim`dim''+1-`fixed''/`nbitemstotdim`dim'' {
+ matrix `order`dim''[1,``j'']=1
+ local k:word `j' of `scalenum1'
+ matrix `affect`dim''[1,`k']=1
+ local listitemsselnum `listitemsselnum' `k'
+ }
+ forvalues j=1/`nbitemsnosel' {
+ matrix `order`dim''[1,`j']=`=`nbitemsnosel'+1-`j''
+ }
+ tokenize `scale1'
+ local listitemssel ``=`nbitemstotdim`dim''-1'' ``nbitemstotdim`dim'''
+
+ local listitemsnosel
+ local listitemsnoselnum
+
+ if "`itemsorder'"=="mspinv" {
+ forvalues j=1/`=`nbitemstotdim`dim''-`fixed'' {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ else if "`itemsorder'"=="msp"{
+ forvalues j=`=`nbitemstotdim`dim''-`fixed''(-1)1 {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ }
+ else if "`itemsorder'"=="order" {
+ tokenize `listkernel' `varlist`dim''
+ local listitemssel
+ local listitemsselnum
+ local listitemsnosel
+ local listitemsnoselnum
+ forvalues j=1/`fixed'{
+ local listitemssel `listitemssel' `rep'`j'
+ local listitemsselnum `listitemsselnum' `j'
+ matrix `affect`dim''[1,`j']=1
+ }
+ forvalues j=`=`fixed'+1'/`nbitemstotdim`dim'' {
+ local listitemsnosel `listitemsnosel' `rep'`j'
+ local listitemsnoselnum `listitemsnoselnum' `j'
+ }
+ }
+
+ if `dim'>1 {
+ tokenize `varlist`dim''
+ }
+ else {
+ tokenize `varlist'
+ }
+
+ local nbitemsnosel:word count `listitemsnosel'
+ local list
+ *tokenize `varlist'
+ forvalues i=1/`=`nbitemsnosel'+`fixed'' {
+ local tmp:word `i' of "`listitemsnosel' `listitemssel'"
+ local list `list' ``i''
+ }
+
+ matrix colnames `result`dim''=`list' iteration nbitems ll1 AIC1 ll2 AIC2 choose
+
+ di _col(0) in green "The kernel of the scale is " in yellow _continue
+ forvalues i=1/`fixed' {
+ local inum:word `i' of `listitemsselnum'
+ di in yellow "``inum'' " _continue
+ }
+ di
+ tokenize `listitemsnosel'
+ forvalues i=1/`=`nbitemsnosel-2'' {
+ local iteration=`iteration'+1
+ di
+ di in green _col(10) "iteration:" in yellow" `iteration'"
+ di in green _col(10) "{hline 13}"
+ di
+ qui use `filescale' , clear
+ local i2:word `i' of `listitemsnosel'
+ local i2num:word `i' of `listitemsnoselnum'
+ qui keep `id' `listitemssel' `i2'
+ tempname score1 score2
+ qui gen `score2'=0
+ tokenize `listitemssel'
+ local nbitemssel: word count `listitemssel'
+ forvalues j=1/`i' {
+ local j2num:word `j' of `listitemsnoselnum'
+ if `affect`dim''[1,`j2num']==1 {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ }
+ forvalues j=1/`nbitemssel' {
+ local j2:word `j' of `listitemssel'
+ local j2num:word `j' of `listitemsselnum'
+ qui replace `score2'=`score2'+`j2'
+ }
+ tokenize `listitemsnosel'
+ qui gen `score1'=`score2'+`i2'
+ forvalues j=`=`nbitemsnosel'+1'/`=`nbitemsnosel'+`nbitemssel'' {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+1']=`iteration'
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+2']=`nbitemssel'
+ matrix `result`dim''[`iteration',`i']=2
+
+ if "`fast'"=="" {
+ qui count if `score1'!=`=`nbitemssel'+1'&`score1'!=0&`score2'!=`nbitemssel'
+ local N=r(N)
+ di in green _col(10)"The program is estimating the parameters of the models (N=" in yellow "`N'" in green ")"
+ qui raschtest `listitemssel' `i2' if `score1'!=3&`score1'!=0&`score2'!=2, mml notest
+
+ matrix `matbetadim1'=e(beta),0
+ qui raschtest `listitemssel' if `score1'!=3&`score1'!=0&`score2'!=2, mml notest
+ matrix `matbetadim2'=e(beta),0
+ qui reshape long `rep' , i(`id') j(`item')
+ qui gen `betadim1'=0
+ qui gen `betadim2'=0
+
+ forvalues j=1/`nbitemssel' {
+ local j2num:word `j' of `listitemsselnum'
+ qui replace `betadim1'=-`matbetadim1'[1,`j'] if `item'==`j2num'
+ qui replace `betadim2'=-`matbetadim2'[1,`j'] if `item'==`j2num'
+ }
+ qui replace `betadim1'= -`matbetadim1'[1,`=`nbitemssel'+1'] if `item'==`i2num'
+ qui count if `rep'==1&`item'==`i2num'&`score1'!=`=`nbitemssel'+1'&`score1'!=0&`score2'!=`nbitemssel'
+ local nb1=r(N)
+ qui count if `item'==`i2num'&`score1'!=`=`nbitemssel'+1'&`score1'!=0&`score2'!=`nbitemssel'
+ local nb2=r(N)
+
+ qui replace `betadim2'= log(`nb1'/(`nb2'-`nb1')) if `item'==`i2num'
+ qui xi:logit `rep' i.`score1' if `score1'!=`=`nbitemssel'+1'&`score1'!=0&`score2'!=`nbitemssel', nocons offset(`betadim1') iter(100)
+ local N1=e(N)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-e(ll)+2*(`nbitemssel'+1)-1)
+
+ tempvar newscore2
+ qui gen `newscore2'=`score2'
+ qui replace `newscore2'=99 if `item'==`i2num'
+ qui xi:logit `rep' i.`newscore2' if `score1'!=`=`nbitemssel'+1'&`score1'!=0&`score2'!=`nbitemssel', offset(`betadim2') iter(100)
+ local N2=e(N)
+ local ll=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-e(ll)+2*(`nbitemssel'+1)-2)
+ }
+ else {
+ qui count
+ local N=r(N)
+ di in green _col(10)"The program is estimating the parameters of the models (N=" in yellow "`N'" in green ")"
+ qui raschtest `listitemssel' `i2' , mml notest
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-e(ll)+`nbitemssel'+2)
+
+ local nb1:word count `listitemssel'
+ qui mmsrm `listitemssel' `i2' , part(`nb1' 1)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-e(ll)+`nbitemssel'+4)
+ }
+ di in green _col(10)"Unidimensional model: " _col(32) "ll: " in yellow _col(37) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+3'] _col(52) in green "AIC: " in yellow _col(57) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']
+ di in green _col(10)"Bidimensional model: " _col(32) "ll: " in yellow _col(37) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+5'] _col(52) in green "AIC: " in yellow _col(57) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']
+ tokenize `listkernel' `varlist`dim''
+ if `result`dim''[`iteration',`=`nbitemstot'+4']<=`result`dim''[`iteration',`=`nbitemstot'+6'] {
+ matrix `result`dim''[`iteration',`i']=1
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=1
+ local nbitemssel=`nbitemssel'+1
+ local nbitemsnosel=`nbitemsnosel'-1
+ local listitemssel `listitemssel' `rep'`i2num'
+ local listitemsselnum `listitemsselnum' `i2num'
+ matrix `affect`dim''[1,`i2num']=1
+ di _col(10) in green "The item " in yellow "``i2num''" in green " is selected in the scale " in yellow `dim'
+ }
+ else {
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=2
+ di _col(10) in green "The item "in yellow "``i2num''" in green " is not selected in the scale " in yellow `dim'
+
+ }
+ }
+ return matrix result`dim' `result`dim''
+ local j=`kernel'+1
+ forvalues i=`=`kernel'+1'/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ if `affect`dim''[1,`j']==1 {
+ matrix `affect'[1,`i']=`dim'
+ }
+ local j=`j'+1
+ }
+ }
+}
+use `raschfitfile',clear
+
+return matrix affect `affect'
+
+end
diff --git a/Modules/ado/personal/r/old/raschfit31.ado b/Modules/ado/personal/r/old/raschfit31.ado
new file mode 100644
index 0000000..673d554
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschfit31.ado
@@ -0,0 +1,336 @@
+*! Raschfit version 3.1 (29 January 2006)
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : Raschfit
+* The Raschfit and the Raschfit-fast procedures to construct sub-scales of items
+* Release 3.1 : January 29, 2006 /*MEAN option in raschtestv7, correction of a bug when there is several scales*/
+*
+* Historic
+* Version 1 (2004-05-06) [Jean-Benoit Hardouin]
+* Version 2 (2004-06-08) [Jean-Benoit Hardouin]
+* Version 3 (2005-12-28) [Jean-Benoit Hardouin]
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* Use the Stata programs mmsrm, raschtest and gammasym who can be download on http://anaqol.free.fr
+* News about this program :http://anaqol.free.fr
+*
+* FreeIRT Project website : http://freeirt.free.fr
+*
+* Copyright 2004-2006 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 raschfit,rclass
+version 7
+syntax varlist(min=2 numeric) [,KERnel(integer 0) NBSCales(integer 1) ITEMSorder(string) nofast ]
+if "`itemsorder'"=="" {
+ local itemsorder mspinv
+}
+local nbitemstot : word count `varlist'
+tokenize `varlist'
+
+tempfile raschfitfile
+qui save `raschfitfile',replace
+preserve
+
+tempname affect
+matrix define `affect'=J(1,`nbitemstot',0)
+matrix colnames `affect'=`varlist'
+
+tempname rep item matbetadim1 matbetadim2
+if `kernel'!=0 {
+ local listkernel
+ forvalues i=1/`kernel' {
+ local listkernel `listkernel' `rep'`i'
+ matrix `affect'[1,`i']=1
+ }
+}
+
+local dim=0
+local nbitemsnosel=`nbitemstot'
+local nbitemstotdim1=`nbitemstot'
+local nbitemsnoselukernel=`nbitemstot'-`kernel'
+
+
+tempvar id betadim1 betadim2
+forvalues i=1/`nbitemstot' {
+ qui drop if ``i''==.
+ rename ``i'' `rep'`i'
+}
+qui gen `id'=_n
+tempfile filescale
+qui save `filescale',replace
+
+di in green "{hline 55}"
+qui count
+local N=r(N)
+if "`fast'"!="" {
+ di in green "Method: " in ye "Raschfit"
+}
+else {
+ di in green "Method: " in ye "Raschfit-Fast"
+}
+di in green "Number of individuals: " in ye `N' in green " (with none missing values)"
+di in green "Number of items: " in ye `nbitemstot'
+di in green "{hline 55}"
+di
+di in green "{hline 100}"
+if "`fast'"!="" {
+ di in green "Model 1: " in ye "Rasch model"
+ di in green "Model 2: " in ye "MMSRM"
+}
+else {
+ di in green "Model 1: " in ye "Rasch model"
+ di in green "Model 2: " in ye "Adapted Rasch model (the response of the new item is not influenced by the latent trait)"
+}
+di in green "Order of the items:" _c
+if "`itemsorder'"=="order" {
+ di in ye " order of {it:varlist}"
+}
+else if "`itemsorder'"=="msp" {
+ di in ye " Obtained with MSP (from the first selected item to the last one)"
+}
+else if "`itemsorder'"=="mspinv" {
+ di in ye " Obtained with MSP (from the last selected item to the first one)"
+}
+if `kernel'!=0 {
+ di in green "Kernel of the first scale: " _c
+ forvalues i=1/`kernel' {
+ di in ye " ``i''" _c
+ }
+ di
+}
+di in green "{hline 100}"
+di
+
+while `nbitemsnosel'>2&`dim'<`nbscales' {
+ use `filescale',replace
+ local iteration=0
+ local dim=`dim'+1
+ if `dim'>1 {
+ local kernel=0
+ local listkernel
+ }
+
+ di in green "SCALE: " in yellow `dim'
+ di in green "{hline 9}"
+ di
+ tempname result`dim'
+ local listitemsnosel
+ local varlist`dim'
+ tokenize `varlist'
+ forvalues i=1/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ local varlist`dim' `varlist`dim'' ``i''
+ local listitemsnosel `listitemsnosel' `rep'`i'
+ }
+ }
+ local nbitemsnosel:word count `listitemsnosel'
+ if `dim'>1 {
+ local nbitemstotdim`dim':word count `listitemsnosel'
+ }
+
+ if `kernel'>=2 {
+ local fixed=`kernel'
+ }
+ else {
+ local fixed=2
+ }
+ matrix define `result`dim''=J(`=`nbitemstotdim`dim''-`fixed'',`=`nbitemstotdim`dim''+7',0)
+
+ tempname order`dim' affect`dim'
+ matrix `order`dim''=J(1,`nbitemstotdim`dim'',0)
+ matrix `affect`dim''=J(1,`nbitemstotdim`dim'',0)
+
+ if "`itemsorder'"=="msp"|"`itemsorder'"=="mspinv" {
+ di in green _col(0) "The program is ordering the items"
+ di
+ qui msp `listkernel' `listitemsnosel',c(-99) notest kernel(`kernel')
+ local scale1 "`r(scale1)'"
+ local scalenum1 "`r(scalenum1)'"
+ tokenize `scalenum1'
+ local listitemsselnum
+ forvalues j=`=`nbitemstotdim`dim''+1-`fixed''/`nbitemstotdim`dim'' {
+ matrix `order`dim''[1,`j']=1
+ local k:word `j' of `scalenum1'
+ matrix `affect`dim''[1,`k']=1
+ local listitemsselnum `listitemsselnum' `k'
+ }
+ forvalues j=1/`nbitemsnosel' {
+ matrix `order`dim''[1,`j']=`=`nbitemsnosel'+1-`j''
+ }
+ tokenize `scale1'
+ local listitemssel ``=`nbitemstotdim`dim''-1'' ``nbitemstotdim`dim'''
+
+ local listitemsnosel
+ local listitemsnoselnum
+
+ if "`itemsorder'"=="mspinv" {
+ forvalues j=1/`=`nbitemstotdim`dim''-`fixed'' {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ else if "`itemsorder'"=="msp"{
+ forvalues j=`=`nbitemstotdim`dim''-`fixed''(-1)1 {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ }
+ else if "`itemsorder'"=="order" {
+ tokenize `listkernel' `varlist`dim''
+ local listitemssel
+ local listitemsselnum
+ local listitemsnosel
+ local listitemsnoselnum
+ forvalues j=1/`fixed'{
+ local listitemssel `listitemssel' `rep'`j'
+ local listitemsselnum `listitemsselnum' `j'
+ matrix `affect`dim''[1,`j']=1
+ }
+ forvalues j=`=`fixed'+1'/`nbitemstotdim`dim'' {
+ local listitemsnosel `listitemsnosel' `rep'`j'
+ local listitemsnoselnum `listitemsnoselnum' `j'
+ }
+ }
+
+ if `dim'>1 {
+ tokenize `varlist`dim''
+ }
+ else {
+ tokenize `varlist'
+ }
+
+ local nbitemsnosel:word count `listitemsnosel'
+ local list
+ tokenize `varlist`dim''
+ forvalues i=1/`=`nbitemsnosel'+`fixed'' {
+ local tmp:word `i' of `listitemsnoselnum' `listitemsselnum'
+ local list `list' ``tmp''
+ }
+ matrix colnames `result`dim''=`list' Iteration Nbitems ll1 AIC1 ll2 AIC2 Selected
+
+ di _col(0) in green "The kernel of the scale is " in yellow _continue
+ forvalues i=1/`fixed' {
+ local inum:word `i' of `listitemsselnum'
+ di in yellow "``inum'' " _continue
+ }
+ di
+ di
+ tokenize `listitemsnosel'
+ di in green "{hline 90}"
+ di in green _col(36) "Log-Likelihood" _col(58) "Akaike Criterion (AIC)"
+ di in green _col(4) "Iteration" _col(20) "New Item" _col(34) "Model 1" _col(47) "Model 2" _col(60) "Model 1" _col(73) "Model 2" _col(81) "Selected"
+ di in green "{hline 90}"
+ forvalues i=1/`=`nbitemsnosel-2'' {
+ local iteration=`iteration'+1
+ qui use `filescale' , clear
+ local i2:word `i' of `listitemsnosel'
+ local i2num:word `i' of `listitemsnoselnum'
+ qui keep `id' `listitemssel' `i2'
+ tempname score1 score2
+ qui gen `score2'=0
+ tokenize `listitemssel'
+ local nbitemssel: word count `listitemssel'
+ forvalues j=1/`i' {
+ local j2num:word `j' of `listitemsnoselnum'
+ if `affect`dim''[1,`j2num']==1 {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ }
+ forvalues j=1/`nbitemssel' {
+ local j2:word `j' of `listitemssel'
+ local j2num:word `j' of `listitemsselnum'
+ qui replace `score2'=`score2'+`j2'
+ }
+ tokenize `listitemsnosel'
+ qui gen `score1'=`score2'+`i2'
+ forvalues j=`=`nbitemsnosel'+1'/`=`nbitemsnosel'+`nbitemssel'' {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+1']=`iteration'
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+2']=`nbitemssel'
+ matrix `result`dim''[`iteration',`i']=2
+
+ if "`fast'"=="" {
+ qui count
+ local N=r(N)
+* di "qui raschtestv7 `listitemssel' `i2' , mean method(cml) test(none)"
+ qui raschtestv7 `listitemssel' `i2' , mean method(cml) test(none)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=r(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-r(ll)+(2*`nbitemssel'+3))
+
+ local nb1:word count `listitemssel'
+ qui raschtestv7 `listitemssel',trace test(none) mean
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=r(ll)
+ qui logit `i2'
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=`result`dim''[`iteration',`=`nbitemstotdim`dim''+5']+e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-`result`dim''[`iteration',`=`nbitemstotdim`dim''+5']+(2*`nbitemssel'+3))
+ }
+ else {
+ qui count
+ local N=r(N)
+ qui raschtestv7 `listitemssel' `i2' , method(mml) test(none)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=r(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-r(ll)+`nbitemssel'+2)
+
+ local nb1:word count `listitemssel'
+ qui mmsrm `listitemssel' `i2' , part(`nb1' 1) iterate(20)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-e(ll)+`nbitemssel'+4)
+ }
+ tokenize `listkernel' `varlist`dim''
+ di in ye _col(4) %9.0f `iteration' _col(14) %14s abbrev("``i2num''",14) _col(29) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+3'] _col(42) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+5'] _col(55) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+4'] _col(68) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+6'] _c
+ if `result`dim''[`iteration',`=`nbitemstot'+4']<=`result`dim''[`iteration',`=`nbitemstot'+6'] {
+ matrix `result`dim''[`iteration',`i']=1
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=1
+ local nbitemssel=`nbitemssel'+1
+ local nbitemsnosel=`nbitemsnosel'-1
+* local listitemssel `listitemssel' `rep'`i2num'
+ local listitemssel `listitemssel' `i2'
+ local listitemsselnum `listitemsselnum' `i2num'
+ matrix `affect`dim''[1,`i2num']=1
+ di in ye _col(88) "X"
+ }
+ else {
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=2
+ di
+ }
+ }
+ di in green "{hline 90}"
+ return matrix result`dim' `result`dim''
+ local j=`kernel'+1
+ forvalues i=`=`kernel'+1'/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ if `affect`dim''[1,`j']==1 {
+ matrix `affect'[1,`i']=`dim'
+ }
+ local j=`j'+1
+ }
+ }
+}
+use `raschfitfile',clear
+
+return matrix affect `affect'
+
+end
diff --git a/Modules/ado/personal/r/old/raschpower - Copie version SIM.ado b/Modules/ado/personal/r/old/raschpower - Copie version SIM.ado
new file mode 100644
index 0000000..674f1a1
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschpower - Copie version SIM.ado
@@ -0,0 +1,217 @@
+*! version 1.2 November 1st, 2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : November 1st, 2010 (Jean-Benoit Hardouin)
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) gamma(real .5) d(string) var(real 1) nodes(int 12)]
+version 11
+
+
+if "`d'"=="" {
+ tempname d
+ matrix `d'=[-1\-.5\0\.5\1]
+}
+
+
+/*tempname abs weight
+ghquadm `nodes' `abs' `weight'
+matrix `abs'=`abs''
+matrix `weight'=`weight''
+
+matrix `abs'=`abs'*sqrt(`var')
+*matrix list `abs'
+matrix `abs'=[5.50090170446774,4.27182584793228,3.22370982877010,2.25946445100080,1.34037519715162,0.444403001944139,-5.50090170446774,-4.27182584793228,-3.22370982877010,-2.25946445100080,-1.34037519715162,-0.444403001944139]
+matrix `abs'=`abs''*sqrt(`var')
+matrix `weight'=[0.000000375975985,0.000121250244966,0.005523056331147,0.072984713184739,0.368391758069477,0.806292983509187,0.000000375975985,0.000121250244966,0.005523056331147,0.072984713184739,0.368391758069477,0.806292983509187]
+matrix `weight'=`weight''
+*matrix list `abs'
+*/
+local nbitems=rowsof(`d')
+
+di in gr "Number of individuals in the first group: " in ye `n0'
+di in gr "Number of individuals in the second group: " in ye `n1'
+di in green "Group effect: " in ye `gamma'
+di in gr "Variance of the latent trait: " in ye `var'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: " _c
+tempname dd
+matrix `dd'=`d''
+matrix list `dd',noblank nohalf nonames noheader
+
+matrix `dd'=`d'/sqrt(`var')
+local gamma=`gamma'/sqrt(`var')
+
+
+clear
+local temp=2^(`nbitems')
+qui range x 0 `=`temp'-1' `temp'
+qui g t=x
+loc i=1
+qui count if t>0
+loc z=r(N)
+qui while `z'>0 {
+ qui g item`i'=mod(t,2^`i')==2^`=`i'-1'
+ qui replace t=t-item`i'*2^`=`i'-1'
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'+1
+}
+drop t
+qui expand 2
+qui gen group=0 in 1/`temp'
+qui replace group=1 in `=`temp'+1'/`=2*`temp''
+qui gen mean=-`n1'*`gamma'/(`n0'+`n1') if group==0
+qui replace mean=`n0'*`gamma'/(`n0'+`n1') if group==1
+qui gen proba=1
+forvalues i=1/`nbitems' {
+ qui gen eps`i'=exp(mean-`d'[`i',1])
+ qui replace proba=proba*eps`i'^item`i'/(1+eps`i')
+}
+
+*list item* proba
+
+qui gen eff=.
+forvalues i=0/1 {
+ qui replace eff=proba*`n`i'' if group==`i'
+}
+
+/*
+forvalues i=1/`nbitems' {
+ qui gen f`i'=eps`i'^item`i'/(1+eps`i')
+ qui gen fp`i'=(item`i'*eps`i'^item`i'+(item`i'-1)*eps`i'^(item`i'+1))/(1+eps`i')^2
+ qui gen fpp`i'=((item`i'^2*eps`i'^item`i'+(item`i'^2-1)*eps`i'^(item`i'+1))*(1+eps`i')^2-2*eps`i'*(1+eps`i')*(item`i'*eps`i'^item`i'+(item`i'-1)*eps`i'^(item`i'+1)))/(1+eps`i')^4
+}
+*/
+qui replace eff=proba
+keep item* eff group proba
+
+local p1=1/`n1'
+local p0=1/`n0'
+qui gen eff2=.
+qui replace eff2=floor(eff/`p1') if group==1
+qui replace eff2=floor(eff/`p0') if group==0
+
+
+qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+qui su eff2 if group==1
+local aff1=r(sum)
+qui su eff2 if group==0
+local aff0=r(sum)
+
+*di "Nombre de patients affectes : `aff1' dans groupe 1 (sur `n1') et `aff0' dans le groupe 0 (sur `n0')"
+
+local unaff1=`n1'-`aff1'
+local unaff0=`n0'-`aff0'
+*di "Nombre de patients non affectes : `unaff1' dans groupe 1 (sur `n1') et `unaff0' dans le groupe 0 (sur `n0')"
+
+
+di "avant sort"
+list item* group proba eff2
+
+
+qui gsort + group - eff
+list item* group proba eff2
+qui replace eff2=eff2+1 in 1/`unaff0'
+di "apres sort"
+qui gsort - group - eff
+qui replace eff2=eff2+1 in 1/`unaff1'
+list item* group proba eff2
+su proba
+return list
+
+*list eff eff2 group proba
+
+qui drop if eff2==0
+
+qui expand eff2
+qui gen i=_n
+
+tempname diff
+matrix `diff'=`dd''
+
+/***************************A REVOIR
+forvalues i=1/`nbitems' {
+ qui su item`i'
+ local var=r(Var)
+ if `var'==0 {
+ qui drop item`i'
+ }
+}
+****************************FIN A REVOIR*/
+
+*irtpoly item*, fixedvar(1) rasch fixed(`diff') covariablemean(group) sasout
+
+qui drop proba eff eff2
+qui reshape long item, i(i)
+qui rename item rep
+qui rename _j item
+
+qui gen offset=0
+forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+}
+constraint 1 _cons=0
+qui gen groupc=group-.5
+qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local gammaest=`b'[1,1]*sqrt(`var')
+local se=`V'[1,1]^.5*sqrt(`var')
+di
+di
+di in gr "{hline 76}"
+di _col(50) "Estimation with the "
+di _col(40) "Cramer-Rao bound" _col(60) "classical formula"
+di in gr "{hline 76}"
+di in green "Estimated value of the group effect" _col(49) in ye %7.2f `gammaest'
+di in green "Standard Error of this estimation" _col(49) in ye %7.2f `se'
+di in green "Variance of this estimation" _col(46) in ye %10.4f `=`se'^2'
+local power=1-normal(1.96-`gamma'*sqrt(`var')/`se')
+local clpower=normal(sqrt(`n1'*`gamma'^2/(`n1'/`n0'+1))-1.96)
+di in green "Estimated value of the power" _col(50) in ye %6.4f `power' _col(71) in ye %6.4f `clpower'
+local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*`gamma'^2)*(1.96-invnorm(1-`power'))^2
+di in green "Number of patients for a power of" %6.2f `=`power'*100' "%" _col(49) in ye `n0' "/" `n1' _col(62) in ye %7.2f `clnsn' "/" %7.2f `clnsn'
+di in green "Ratio of the number of patients" in ye %6.2f _col(55)`=(`n0'+`n1')/(2*`clnsn')'
+di in gr "{hline 76}"
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`power'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`=`n0'/`clnsn''
+
+
+
+
+end
diff --git a/Modules/ado/personal/r/old/raschpower1.5.ado b/Modules/ado/personal/r/old/raschpower1.5.ado
new file mode 100644
index 0000000..e5b59f7
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschpower1.5.ado
@@ -0,0 +1,220 @@
+*! version 1.5 : July 11th, 2011
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2011 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) gamma(real .5) d(string) var(real 1) fast nodata gammafix EXPectedpower(real -1)]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+if "`d'"=="" {
+ tempname d
+ matrix `d'=[-1\-.5\0\.5\1]
+}
+
+local nbitems=rowsof(`d')
+
+di in gr "Number of individuals in the first group: " in ye `n0'
+di in gr "Number of individuals in the second group: " in ye `n1'
+di in green "Group effect: " in ye `gamma'
+di in gr "Variance of the latent trait: " in ye `var'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: " _c
+tempname dd
+matrix `dd'=`d''
+matrix list `dd',noblank nohalf nonames noheader
+
+matrix `dd'=`d'/*sqrt(`var')*/
+local gamma=`gamma'/*sqrt(`var')*/
+
+if "`data'"=="" {
+ clear
+ local temp=2^(`nbitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=1
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui g item`i'=mod(t,2^`i')==2^`=`i'-1'
+ qui replace t=t-item`i'*2^`=`i'-1'
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'+1
+ }
+ drop t
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ qui gen mean=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean=`n0'*`gamma'/(`n0'+`n1') if group==1
+
+ if "`fast'"=="" {
+ qui gen proba=.
+ forvalues i=1/`=2*`temp'' {
+ local int=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff=`d'[`j',1]
+ local int "`int'*exp(`rep'*(x-`diff'))/(1+exp(x-`diff'))"
+ }
+ qui su mean in `i'
+ local mean=r(mean)
+ qui gausshermite `int',mu(`mean') sigma(`=sqrt(`var')') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ else {
+ qui gen proba=1
+ forvalues i=1/`nbitems' {
+ qui gen eps`i'=exp(mean-`d'[`i',1])
+ qui replace proba=proba*eps`i'^item`i'/(1+eps`i')
+ }
+ }
+ qui gen eff=.
+ forvalues i=0/1 {
+ qui replace eff=proba*`n`i'' if group==`i'
+ }
+ qui replace eff=proba
+ keep item* eff group proba
+
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui gen eff2=.
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ gen efftmp=eff2
+
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ *qui drop if eff2==0
+ gsort group item*
+ gen res=proba*50
+*list item* group efftmp eff2 proba
+
+ qui expand eff2
+ qui drop proba eff eff2
+}
+qui gen i=_n
+
+*su
+qui alpha item*
+local alpha=r(alpha)
+
+tempname diff
+matrix `diff'=`dd''
+
+qui reshape long item, i(i)
+qui rename item rep
+qui rename _j item
+
+qui gen offset=0
+forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+}
+qui gen groupc=group-.5
+matrix est=(`gamma',`=sqrt(`var')')
+
+
+
+if "`gammafix'"=="" {
+ constraint 1 _cons=`=ln(`var')'
+ qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+}
+else {
+ qui gllamm rep groupc, nocons i(i) offset(offset) iterate(0) fam(bin) link(logit) from(est) copy
+}
+
+
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local gammaest=`b'[1,1]/*sqrt(`var')*/
+local se=`V'[1,1]^.5/*sqrt(`var')*/
+di
+di
+di in gr "{hline 91}"
+di _col(60) "Estimation with the "
+di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+di in gr "{hline 91}"
+if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+}
+di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+local power=1-normal(1.96-`gamma'/*sqrt(`var')*//`se')+normal(-1.96-`gamma'*sqrt(`var')/`se')
+local poweruni=1-normal(1.96-`gamma'/*sqrt(`var')*//`se')
+local clpower=normal(sqrt(`n1'*`gamma'^2/(`n1'/`n0'+1))-1.96)
+/*si on ne néglige pas le deuxième terme, la bonne puissance est*/
+*di in green "Estimation of the power" _col(60) in ye %6.4f `power' _col(86) in ye %6.4f `clpower'
+di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+/*si on ne néglige pas le deucième terme, la bonne puissance est*/
+*local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96-invnorm(1-`power'))^2
+local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96-invnorm(1-`poweruni'))^2
+di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `clnsn'
+di in green "Ratio of the number of patients" in ye %6.2f _col(68)`=(`n0'+`n1')/(2*`clnsn')'
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower')
+ local expn=r(N_1)
+ local expn2=`expn'*`=(`n0'+`n1')/(2*`clnsn')'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `expn2' _col(77) in ye %7.2f `expn' "/" %7.2f `expn'
+}
+di in gr "{hline 91}"
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`=`n0'/`clnsn''
+return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/old/raschpower1.ado b/Modules/ado/personal/r/old/raschpower1.ado
new file mode 100644
index 0000000..2e2f2fe
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschpower1.ado
@@ -0,0 +1,193 @@
+*! version 1 january 25th, 2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010 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 raschpower1,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) gamma(real .5) d(string) var(real 1) nodes(int 12)]
+
+
+
+if "`d'"=="" {
+ tempname d
+ matrix `d'=[-1\-.5\0\.5\1]
+}
+
+/*tempname abs weight
+ghquadm `nodes' `abs' `weight'
+matrix `abs'=`abs''
+matrix `weight'=`weight''
+
+matrix `abs'=`abs'*sqrt(`var')
+*matrix list `abs'
+matrix `abs'=[5.50090170446774,4.27182584793228,3.22370982877010,2.25946445100080,1.34037519715162,0.444403001944139,-5.50090170446774,-4.27182584793228,-3.22370982877010,-2.25946445100080,-1.34037519715162,-0.444403001944139]
+matrix `abs'=`abs''*sqrt(`var')
+matrix `weight'=[0.000000375975985,0.000121250244966,0.005523056331147,0.072984713184739,0.368391758069477,0.806292983509187,0.000000375975985,0.000121250244966,0.005523056331147,0.072984713184739,0.368391758069477,0.806292983509187]
+matrix `weight'=`weight''
+*matrix list `abs'
+*/
+local nbitems=rowsof(`d')
+
+di in gr "Number of individuals in the first group: " in ye `n0'
+di in gr "Number of individuals in the second group: " in ye `n1'
+di in green "Group effect: " in ye `gamma'
+di in gr "Variance of the latent trait: " in ye `var'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: " _c
+tempname dd
+matrix `dd'=`d''
+matrix list `dd',noblank nohalf nonames noheader
+
+
+
+clear
+local temp=2^(`nbitems')
+qui range x 0 `=`temp'-1' `temp'
+qui g t=x
+loc i=1
+qui count if t>0
+loc z=r(N)
+qui while `z'>0 {
+ qui g item`i'=mod(t,2^`i')==2^`=`i'-1'
+ qui replace t=t-item`i'*2^`=`i'-1'
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'+1
+}
+drop t
+qui expand 2
+qui gen group=0 in 1/`temp'
+qui replace group=1 in `=`temp'+1'/`=2*`temp''
+qui gen mean=(-1)^(1-group)*`gamma'*sqrt(`var')/2
+qui gen proba=1
+forvalues i=1/`nbitems' {
+ qui gen eps`i'=exp(mean-`d'[`i',1])
+ qui replace proba=proba*eps`i'^item`i'/(1+eps`i')
+}
+qui gen eff=.
+forvalues i=0/1 {
+ qui replace eff=proba*`n`i'' if group==`i'
+}
+forvalues i=1/`nbitems' {
+ qui gen f`i'=eps`i'^item`i'/(1+eps`i')
+ qui gen fp`i'=(item`i'*eps`i'^item`i'+(item`i'-1)*eps`i'^(item`i'+1))/(1+eps`i')^2
+ qui gen fpp`i'=((item`i'^2*eps`i'^item`i'+(item`i'^2-1)*eps`i'^(item`i'+1))*(1+eps`i')^2-2*eps`i'*(1+eps`i')*(item`i'*eps`i'^item`i'+(item`i'-1)*eps`i'^(item`i'+1)))/(1+eps`i')^4
+}
+qui replace eff=proba
+keep item* eff group proba
+
+local p1=1/`n1'
+local p0=1/`n0'
+qui gen eff2=.
+qui replace eff2=floor(eff/`p1') if group==1
+qui replace eff2=floor(eff/`p0') if group==0
+qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+qui su eff2 if group==1
+local aff1=r(sum)
+qui su eff2 if group==0
+local aff0=r(sum)
+
+*di "Nombre de patients affectes : `aff1' dans groupe 1 (sur `n1') et `aff0' dans le groupe 0 (sur `n0')"
+
+local unaff1=`n1'-`aff1'
+local unaff0=`n0'-`aff0'
+*di "Nombre de patients non affectes : `unaff1' dans groupe 1 (sur `n1') et `unaff0' dans le groupe 0 (sur `n0')"
+
+qui gsort + group - eff
+qui replace eff2=eff2+1 in 1/`unaff0'
+qui gsort - group - eff
+qui replace eff2=eff2+1 in 1/`unaff1'
+
+*list eff eff2 group proba
+
+qui drop if eff2==0
+
+qui expand eff2
+qui gen i=_n
+
+tempname diff
+matrix `diff'=`d''
+
+/***************************A REVOIR
+forvalues i=1/`nbitems' {
+ qui su item`i'
+ local var=r(Var)
+ if `var'==0 {
+ qui drop item`i'
+ }
+}
+****************************FIN A REVOIR*/
+
+*irtpoly item*, fixedvar(1) rasch fixed(`diff') covariablemean(group) sasout
+
+qui drop proba eff eff2
+qui reshape long item, i(i)
+qui rename item rep
+qui rename _j item
+
+qui gen offset=0
+forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+}
+constraint 1 _cons=0
+qui gen groupc=group-.5
+ xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local gammaest=`b'[1,1]
+local se=`V'[1,1]^.5
+di
+di
+di in gr "{hline 76}"
+di _col(50) "Estimation with the "
+di _col(40) "Cramer-Rao bound" _col(60) "classical formula"
+di in gr "{hline 76}"
+di in green "Estimated value of the group effect" _col(49) in ye %7.2f `gammaest'
+di in green "Standard Error of this estimation" _col(49) in ye %7.2f `se'
+di in green "Variance if this estimation" _col(46) in ye %10.4f `=`se'^2'
+local power=1-normal(1.96-`gamma'/`se')
+local clpower=normal(sqrt(`n0'*`gamma'^2/2)-1.96)
+di in green "Estimated value of the power" _col(50) in ye %6.4f `power' _col(71) in ye %6.4f `clpower'
+local clnsn=2/`gamma'^2*(1.96-invnorm(1-`power'))^2
+di in green "Number of patients for a power of" %6.2f `=`power'*100' "%" _col(49) in ye `n0' "/" `n1' _col(62) in ye %7.2f `clnsn' "/" %7.2f `clnsn'
+di in green "Ratio of the number of patients" in ye %6.2f _col(55)`=(`n0'+`n1')/(2*`clnsn')'
+di in gr "{hline 76}"
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`power'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`=`n0'/`clnsn''
+
+
+
+
+end
diff --git a/Modules/ado/personal/r/old/raschpowerpcm.ado b/Modules/ado/personal/r/old/raschpowerpcm.ado
new file mode 100644
index 0000000..7219cf2
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschpowerpcm.ado
@@ -0,0 +1,374 @@
+*! version 3.1 : October 25th, 2011
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2011 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 raschpowerpcm,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(real 1) Method(string) NBPatterns(int 2) nodata gammafix EXPectedpower(real -1)]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d
+if "`difficulties'"=="" {
+ *matrix `d'=[-1\-.5\0\.5\1]
+ matrix `d'=[-1.151, -0.987\-0.615, -0.325\-0.184, -0.043\0.246, 0.554\0.782, 1.724]
+ *matrix `d'=[ -1.527, -1.019\-1.100, -0.793\-0.796, -0.369\-0.540, 0.152\-0.306, -0.220\-0.077, 0.147\0.156, 0.431\0.412, 0.685\0.716, 1.332\1.043, 1.572]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`=`nbmodat'^`nbitems'*2' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if "`method'"=="" {
+ if `nbmodat'^`nbitems'*2<1000 {
+ local method GH
+ }
+ else if `nbmodat'^`nbitems'<10000 {
+ local method MEAN+GH
+ }
+ else if `nbmodat'^`nbitems'<1000000 {
+ local method MEAN
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+
+
+di in gr "Method: " in ye "`method'"
+di in gr "Number of individuals in the first group: " in ye `n0'
+di in gr "Number of individuals in the second group: " in ye `n1'
+di in green "Group effect: " in ye `gamma'
+di in gr "Variance of the latent trait: " in ye `var'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+di in gr "Number of studied response's patterns: " in ye `=`nbmodat'^`nbitems'*2'
+
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"&"`method'"!="POPULATION+MEAN" {
+ local temp=`nbmodat'^(`nbitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ else {
+ qui simirt, clear pcm(`difficulties') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui keep if keep==1
+ qui count
+ local tmp=r(N)
+ di "Number of kept patterns:`tmp'"
+ local method GH
+ }
+ qui gen mean=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean=`n0'*`gamma'/(`n0'+`n1') if group==1
+
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ local int=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`d'[`j',1]
+ local sum "1+exp(x-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`j',`m']
+ local sum "`sum'+exp(`m'*x-`diff`m'')"
+ }
+ local int "(`int'*exp(`rep'*x-`diff`rep''))/(`sum')"
+ }
+ qui su mean in `i'
+ local mean=r(mean)
+ qui gausshermite `int',mu(`mean') sigma(`=sqrt(`var')') display
+ qui replace proba=r(int) in `i'
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues i=1/`nbitems' {
+ local diff0=0
+ local diff1=`d'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ local int=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`d'[`j',1]
+ local sum "1+exp(x-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`j',`m']
+ local sum "`sum'+exp(`m'*x-`diff`m'')"
+ }
+ local int "(`int'*exp(`rep'*x-`diff`rep''))/(`sum')"
+ }
+ qui su mean in `i'
+ local mean=r(mean)
+ qui gausshermite `int',mu(`mean') sigma(`=sqrt(`var')') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ qui gen eff=.
+ forvalues i=0/1 {
+ qui replace eff=proba*`n`i'' if group==`i'
+ }
+ qui replace eff=proba
+ qui keep item* eff group proba
+
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui gen eff2=.
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+qui gen groupc=group-.5
+if `nbmodat'==1 {
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ }
+ matrix est=(`gamma',`=sqrt(`var')')
+
+ if "`gammafix'"=="" {
+ constraint 1 _cons=`=ln(`var')'
+ qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ }
+ else {
+ qui gllamm rep groupc, nocons i(i) offset(offset) iterate(0) fam(bin) link(logit) from(est) copy
+ }
+ tempname b V
+}
+else {
+ matrix `db'=`db''
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var')
+}
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local gammaest=`b'[1,1]
+local se=`V'[1,1]^.5
+
+
+di
+di
+di in gr "{hline 91}"
+di _col(60) "Estimation with the "
+di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+di in gr "{hline 91}"
+if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+}
+di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+local poweruni=1-normal(1.96-`gamma'/`se')
+local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+}
+di in gr "{hline 91}"
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/old/raschpowers.hlp b/Modules/ado/personal/r/old/raschpowers.hlp
new file mode 100644
index 0000000..eb18771
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschpowers.hlp
@@ -0,0 +1,51 @@
+{smcl}
+{* 7july2011}{...}
+{hline}
+help for {hi:raschpower}{right:Jean-Benoit Hardouin, Myriam Blanchin}
+{hline}
+
+{title:Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals}
+
+{p 8 14 2}{cmd:raschpower} [{cmd:,} {cmdab:n0}({it:#}) {cmdab:n1}({it:#})
+{cmdab:gamma}({it:#}) {cmdab:var}({it:#}) {cmdab:d}({it:vector})]
+
+
+{title:Description}
+
+{p 4 8 2}{cmd:raschpower} allows estimating the power of the Wald test comparing the means of two groups of patients in the context of the Rasch model. The estimation is based on the estimation of the variance of the difference of the means based on the Cramer-Rao bound.
+
+{title:Options}
+
+{p 4 8 2}{cmd:n0} and {cmd:n1} indicates the numbers of individuals in the two groups (100 by default).
+
+{p 4 8 2}{cmd:gamma} indicates the group effect (difference between the two means) [0.5 by default].
+
+{p 4 8 2}{cmd:var} indicates the value of the variance of the latent trait [1 by default].
+
+{p 4 8 2}{cmd:d} is a vector containing the difficulties of the items [one row per item, one column - (-1,-0.5,0,0.5,1)' by default].
+
+{title:Example}
+
+ {p 4 8 2}{cmd:. raschpower}
+
+ {p 4 8 2}{cmd:. raschpower, n0(200) n1(200) gamma(0.4) var(1.3)}
+
+ {p 4 8 2}{cmd:. matrix diff=(-1.47\-0.97\-.23\-0.12\0.02\0.1)}{p_end}
+ {p 4 8 2}{cmd:. raschpower, n0(127) n1(134) gamma(0.23) d(diff) var(2.58)}{p_end}
+
+{title:References}
+
+ {p 4 8 2}Hardouin J.B., Amri S., Feddag M., Sébille V. (2011) Towards Power And Sample Size Calculations For The Comparison Of Two Groups Of Patients With Item Response Theory Models. Accept to appear in Statistics in Medicine.
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
diff --git a/Modules/ado/personal/r/old/raschtest2.ado b/Modules/ado/personal/r/old/raschtest2.ado
new file mode 100644
index 0000000..4a007a4
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtest2.ado
@@ -0,0 +1,200 @@
+*! version 8 25june2009
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+*
+* Needed modules :
+* raschtestv7jf version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest2,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) ]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+
+raschtestv7jf `varlist' `if' `in' , id(`id') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/old/raschtest82.ado b/Modules/ado/personal/r/old/raschtest82.ado
new file mode 100644
index 0000000..b443c36
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtest82.ado
@@ -0,0 +1,200 @@
+*! version 8 25june2009
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+*
+* Needed modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) ]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+
+raschtestv7 `varlist' `if' `in' , id(`id') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/old/raschtest83.ado b/Modules/ado/personal/r/old/raschtest83.ado
new file mode 100644
index 0000000..be65556
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtest83.ado
@@ -0,0 +1,204 @@
+*! version 8.3 15june2010
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+* Version 8.3 (2009-06-20) : Jean-Benoit Hardouin /*GENRES option*/
+*
+* Needed modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) GENRes(string)]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genres'"!="" {
+ local gensresv8 "genres(`genres')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+
+raschtestv7 `varlist' `if' `in' , id(`id') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genresv8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/old/raschtestv7732.ado b/Modules/ado/personal/r/old/raschtestv7732.ado
new file mode 100644
index 0000000..eb90c63
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv7732.ado
@@ -0,0 +1,1743 @@
+*! version 7.3.2 5october2005
+************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 7.3 of Raschtest (http://freeirt.free.fr) for Stata7
+*
+* Version 7.3.2 (Stata 7.0) : July 2, 2005 /*correction for the *genlt* option with *method(cml)**/
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+*
+* Needed modules :
+* gammasym version 2.1 (http://freeirt.free.fr)
+* gausshermite version 1 (http://freeirt.free.fr)
+* geekel2d version 4.2 (http://freeirt.free.fr)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.10 (ssc describe gllamm)
+* gllapred version 2.3.2 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003-2005 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) time TRace Details Explain ]
+
+
+/***********************************************************************************************************
+EXPLAIN OPTION
+***********************************************************************************************************/
+
+if "`explain'"!="" {
+
+ di in green "{hline}"
+ di in green "{title:ESTIMATION METHODS} (define by the {cmd:method} option)"
+ di in green "{hline}"
+ di
+ di in green "{p 0 0 0}{hi:CML : Conditional Maximum Likelihood} ({cmd:method(cml)}) {p_end}"
+ di in green "{p 4 4 2}The latent trait is considered as a set of fixed parameters, and the difficulty parameters are estimated conditionnally to them{p_end}"
+ di in green "{p 4 4 2}The identifiability constraint consit to fix the difficulty parameter of the last item to 0{p_end}"
+ di in green "{p 0 0 0}{hi:MML : Marginal Maximum Likelihood} ({cmd:method(mml)}){p_end}"
+ di in green "{p 4 4 2}The latent trait is considered as a random variable, and the difficulty parameters are estimated marginally to it{p_end}"
+ di in green "{p 4 4 2}The identifiability constraint consit to fix the mean fo the latent trait to 0{p_end}"
+ di in green "{p 0 0 0}{hi:GEE : Generalized Estimating Equation} ({cmd:method(gee)}){p_end}"
+ di in green "{p 4 4 2}Same assumption than for the MML technic.{p_end}"
+ di
+ di in green "{hline}"
+ di in green "{title:NOTATIONS} "
+ di in green "{hline}"
+ di
+ di in green "{p 0 0 0}{hi :J} is the number of items.{p_end}"
+ di in green "{p 0 0 0}{hi :N} is the number of individuals.{p_end}"
+ di in green "{p 0 0 0}{hi :N_c} is the number of individuals with a score different of 0 and of J.{p_end}"
+ di in green "{p 0 0 0}{hi :G} is the number of number of groups of scores.{p_end}"
+ di
+ di in green "{hline}"
+ di in green "{title:TESTS} "
+ di in green "{hline}"
+ di
+ di in green "{p 0 0 0}{hi: General test}{p_end}"
+ di in green "{p 4 4 2}The {hi: Andersen test} consit to test if the difficulty parameters of the items are the same values in estimating them in each subgroups of individuals defined by the values of the score (who can be grouped by the {cmd:group} or {cmd:autogroup} options). This test is only available with CML technic.{p_end}"
+ di
+ di in green "{p 0 0 0}{hi: Tests of the first order}{p_end} (defined by the {cmd:test} option)"
+ di in green "{p 4 4 2}The {hi: Wright Panchapakesan test}, the {hi:Q1 test}, the {hi:R1c test} and the {hi:R1m test} consist to test the adequation between the observed and the theorical number of positive responses to each item in each group of scores (defined by the {cmd:group} or {cmd:autogroup} options). The differences between the tests are explained by the method to estimate the theorical number of positive response in each group of scores, and by the definition of the covariance matrix between these theorical numbers. {p_end}"
+ di in green "{p 4 4 2}{hi: The Wright Panchapakesan test} ({cmd:test(WP)}) consist to estimate the number of positive responses to each item in function of the estimations of the difficulty parameters and of the individual values of the latent trait. The covariance matrix between these estimations is a diagonal matrix. {p_end}"
+ di in green "{p 4 4 2}{hi:The Van den Wollenberg Q1 test} ({cmd:test(Q)}) consist to estimate the number of positive responses to each item only in function of the estimations of the difficulty parameters. The covariance matrix between these estimations is a diagonal matrix.{p_end}"
+ di in green "{p 4 4 2}{hi:The R1c test} ({cmd:test(R)}) consist to estimate the number of positive responses to each item only in function of the estimations of the difficulty parameters. The covariance matrix between these estimations is no more a diagonal matrix. This test is available only with a CML technic of estimation of the parameters.{p_end}"
+ di in green "{p 4 4 2}{hi:The R1m test} ({cmd:test(R)}) is the same test than the R1c test, except that the individuals with a nul score or a perfect score are considered. This test is available with the MML or the GEE technic of estimation of the parameters.{p_end}"
+ di
+ di in green "{p 0 0 0}{hi:Others Tests and indexes}{p_end}"
+ di in green "{p 4 4 2}{hi:The split test} (obtained by the {cmd:splittest} option) consists to estimate the parameters of the items conditionnaly to the response to one of them. We can test the global difference between the two estimated vectors of parameters with the Andersen LR Z test. This test allows detecting dependent items.{p_end}"
+ di in green "{p 4 4 2}{hi:The U test} allows detecting items with low or high discriminating powers. The U statistics follow a standardized gaussian distribution, and a significant positive value signifies that the slope of the item is too low (compared to the others items) and a significant negative value signifies that the slope of the item is too high (compared to the others). {p_end}"
+ di in green "{p 4 4 2}{hi:The OUTFIT and INFIT} (graphs obtained by the {cmd:fitgraph} option) indexes allows detecting items with a baf fit. The values of these two indexes must be in the interval [.6;1.4].{p_end}"
+
+ di
+
+ exit
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+tokenize `varlist'
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ confirm new variable `genfit' `genlt' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui gen `autoscore'=0
+ forvalues i=1/`nbitems' {
+ qui replace `autoscore'=`autoscore'+``i''
+ }
+ tempname matscore tmp
+ *qui tab `autoscore', matcell(`tmp')
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in red "You cannot compare two populations with the CML estimation method"
+ di in red "Use another method of estimation."
+ error 198
+ exit
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the details, icc, fitgraph or splittest if you use test(none)."
+ di in green "These options are ignored."
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The MEANDIFF option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The SPLITTESTS option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+tempvar id
+gen `id'=_n
+
+qui keep if `touse'==1
+
+qui keep `varlist' `comp' `id'
+
+tempname rep item
+tempvar score realscore
+gen `score'=0
+
+
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+ qui drop if `rep'`i'==.|`rep'`i'>1
+ qui replace `score'=`score'+`rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep' , i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ qui xtlogit `rep' `rep'1-`rep'`nbitems', i(`id') nocons
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+1']=exp(`est'[1,`=`nbitems'+1']/2)
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1', group(`id')
+}
+
+if "`method'"!="gee" {
+ matrix `coef'=e(b)
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ matrix `var'=e(V)
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])*`sig'/2
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+ /************************************
+ A VIRER DEBUT
+ ****************************************/
+ /*
+ tempfile jbh
+ save `jbh',replace
+ set trace on
+ rename `rep' rep
+ forvalues i=1/`nbitems' {
+ rename `rep'`i' rep`i'
+ }
+ rename `id' id
+ matrix est=`est'
+ keep rep* id
+ save c:\ado\jbh.dta,replace
+ set trace off
+ use `jbh',replace
+ */
+ /************************************
+ A VIRER FIN
+ ****************************************/
+
+
+ capture gllamm `rep' `rep'1-`rep'`nbitems', i(`id') nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 10001
+ qui gen theta=(_n-5001)/1000
+ qui gen A=1
+ *set trace on
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=V[1]
+ }
+ use `verytmp',replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=sqrt(`sdtheta'[`=`s'+1',`= `s'+1'])
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ forvalues i=0/`nbitems' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Pi Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else if "`test'"=="R"&`nbrealscore`s''!=0{
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if "`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob2'*(1-`prob2'))
+ qui gen `z2'=(`rep'-`prob2')^2
+ qui gen `y2'=`z2'/`v2'
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Score `g' : The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save `Q2file',replace
+ qui use `saveraschtest',replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use `Q2file',replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save `Zfile', replace
+ qui use `saveraschtest',replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE)
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use `Zfile',replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=34
+}
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `nbind' in green " (" in yellow `missing' in green " individuals removed for missing values)"
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty"
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in green "`fixed`i''" in yellow _col(3) %12s abbrev("``i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfit`i'' _col(65) %6.3f `infit`i'' `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfit`i''
+ matrix `itemfit'[`i',5]=`infit`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(7) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(7) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+if "`method'"!="cml" {
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig'
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+/*Tabular of the estimated values of the latent trait*/
+
+ di
+ di
+ noi di in green _col(33) "Ability"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(69) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=54
+ }
+ else {
+ local line=42
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ if `effscore`g''!=0 {
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(60) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ else {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(55) %4.0f `nbrealscore`s''
+ }
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc`i',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc`i' `saving' , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save `saveinfo',replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information `saving' , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use `saveinfo',replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+
+ tempname outfit meanz2 meanv2 infit
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui su `outfit'
+ local maxo=r(max)
+ qui su `infit'
+ local maxi=r(max)
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfit' `id'), name(outfit,replace) yline(.6 1.4) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(0(.2)2 2(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infit' `id'), name(infit,replace) yline(.6 1.4) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(0(.2)2 2(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit `savingo' , `replace'
+ graph save infit `savingi' , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfit' `id', `savingo' twoway sy(.) c(.) yline(.6 1.4) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(0(.2)2 2(.5)`maxo')
+ pause
+ graph `infit' `id', `savingi' twoway sy(.) c(.) yline(.6 1.4) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(0(.2)2 2(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitj infitj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitj'=.
+ qui gen `infitj'=.
+ local mino=.6
+ local maxo=1.4
+ local mini=.6
+ local maxi=1.4
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitj'=`outfit`j'' in `j'
+ qui replace `infitj'=`infit`j'' in `j'
+ local mino=min(`mino',`outfit`j'')
+ local mini=min(`mini',`infit`j'')
+ local maxo=max(`maxo',`outfit`j'')
+ local maxi=max(`maxi',`infit`j'')
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitj' `betap',name(outfit,replace) mlabel(`name')), yline(.6 1.4) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.2)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitj' `betap',name(infit,replace) mlabel(`name')), yline(.6 1.4) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.2)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit `savingo' , `replace'
+ graph save infit `savingi' , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitj' `betap', `savingo' twoway c(.) yline(.6 1.4) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.2)`maxo') sy([`name'])
+ pause
+ graph `infitj' `betap', `savingi' twoway c(.) yline(.6 1.4) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.2)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ *set trace on
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use `saveraschtest',replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml)
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml)
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml)
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split `saving' , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (scatter `tl2' `latent2',mlabel(`labtl2')) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph `saving' , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''!=0 {
+ local colnametheta `colnametheta' score_`i'
+ }
+ }
+}
+else {
+ forvalues i=0/`nbgroups' {
+ if `effscore`i''!=0 {
+ local colnametheta `colnametheta' score_`i'
+ }
+ }
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+*set trace off
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use `saveraschtest'
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i''
+ }
+ qui gen `genlt2'=.
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' if `score'==`i'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score'
+ }
+ if "`genlt'"!="" {
+ qui gen `genlt'=`genlt2'
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0
+ qui gen `infit'=0
+ tempname infit1 infit2
+ qui gen `infit1'=0
+ qui gen `infit2'=0
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j''))
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j''))
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j''))
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems'
+ }
+ qui replace `infit'=`infit1'/`infit2'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+end
diff --git a/Modules/ado/personal/r/old/raschtestv7761.ado b/Modules/ado/personal/r/old/raschtestv7761.ado
new file mode 100644
index 0000000..df9201a
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv7761.ado
@@ -0,0 +1,1809 @@
+*! version 7.6.1 26june2008
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 7.6 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+*
+* Needed modules :
+* gammasym version 2.1 (http://freeirt.free.fr)
+* gausshermite version 1 (http://freeirt.free.fr)
+* geekel2d version 4.2 (http://freeirt.free.fr)
+* genscore version 1.4 (http://freeirt.free.fr)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.11 (ssc describe gllamm)
+* gllapred version 2.3.2 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003-2008 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold]
+
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ confirm new variable `genfit' `genlt' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+
+tempvar id
+gen `id'=_n
+
+
+qui keep `varlist' `comp' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+* di "LD : `ld'"
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+ *qui drop if `rep'`i'==.|`rep'`i'>1
+ *qui replace `score'=`score'+`rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep' , i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ qui xtlogit `rep' `rep'1-`rep'`nbitems', i(`id') nocons
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+1']=exp(`est'[1,`=`nbitems'+1']/2)
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1', group(`id')
+}
+
+if "`method'"!="gee" {
+ matrix `coef'=e(b)
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ matrix `var'=e(V)
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])*`sig'/2
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ capture gllamm `rep' `rep'1-`rep'`nbitems', i(`id') nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=V[1]
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=sqrt(`sdtheta'[`=`s'+1',`= `s'+1'])
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld'
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+if "`method'"!="cml" {
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig'
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+/*Tabular of the estimated values of the latent trait*/
+
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ *graph twoway (scatter `outfit' `id'), name(outfit,replace) yline(.6 1.4) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(0(.2)2 2(.5)`maxo') `draw'
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ *graph twoway (scatter `infit' `id'), name(infit,replace) yline(.6 1.4) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(0(.2)2 2(.5)`maxi') `draw'
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld'
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld'
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld'
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (scatter `tl2' `latent2',mlabel(`labtl2')) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE)
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ qui gen `genlt'=`genlt2' `if'
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+end
diff --git a/Modules/ado/personal/r/old/raschtestv7762.ado b/Modules/ado/personal/r/old/raschtestv7762.ado
new file mode 100644
index 0000000..7f5fc09
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv7762.ado
@@ -0,0 +1,1829 @@
+*! version 7.6.1 26june2008
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 7.6 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+*
+* Needed modules :
+* gammasym version 2.1 (http://freeirt.free.fr)
+* gausshermite version 1 (http://freeirt.free.fr)
+* geekel2d version 4.2 (http://freeirt.free.fr)
+* genscore version 1.4 (http://freeirt.free.fr)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.11 (ssc describe gllamm)
+* gllapred version 2.3.2 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003-2008 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200)]
+
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ confirm new variable `genfit' `genlt' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+
+tempvar id
+gen `id'=_n
+
+
+qui keep `varlist' `comp' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+* di "LD : `ld'"
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+ *qui drop if `rep'`i'==.|`rep'`i'>1
+ *qui replace `score'=`score'+`rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep' , i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ noi xtlogit `rep' `rep'1-`rep'`nbitems', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+1']=exp(`est'[1,`=`nbitems'+1']/2)
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1', group(`id')
+}
+
+if "`method'"!="gee" {
+ matrix `coef'=e(b)
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ matrix `var'=e(V)
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])*`sig'/2
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ capture gllamm `rep' `rep'1-`rep'`nbitems', i(`id') nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/`vartheta'
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld'
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+if "`method'"!="cml" {
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig'
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+/*Tabular of the estimated values of the latent trait*/
+
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+ if "`method'"=="mml"|"`method'"=="gee" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ *di in green "Personal Separation Index (PSI)" _col(50) in ye %5.3f `psi'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ }
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ *graph twoway (scatter `outfit' `id'), name(outfit,replace) yline(.6 1.4) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(0(.2)2 2(.5)`maxo') `draw'
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ *graph twoway (scatter `infit' `id'), name(infit,replace) yline(.6 1.4) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(0(.2)2 2(.5)`maxi') `draw'
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld'
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld'
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld'
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE)
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ qui gen `genlt'=`genlt2' `if'
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+end
diff --git a/Modules/ado/personal/r/old/raschtestv78 avant COVARIABLES.ado b/Modules/ado/personal/r/old/raschtestv78 avant COVARIABLES.ado
new file mode 100644
index 0000000..2a7b5b1
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv78 avant COVARIABLES.ado
@@ -0,0 +1,1890 @@
+*! version 7.6.1 26june2008
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 7.6 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8 (2009-03-01) : Jean-Benoit Hardouin /*DIFFICULTIES option*/
+*
+* Needed modules :
+* gammasym version 2.1 (http://freeirt.free.fr)
+* gausshermite version 1 (http://freeirt.free.fr)
+* geekel2d version 4.2 (http://freeirt.free.fr)
+* genscore version 1.4 (http://freeirt.free.fr)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.11 (ssc describe gllamm)
+* gllapred version 2.3.2 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariables(varlist)]
+
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ confirm new variable `genfit' `genlt' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+
+tempvar id
+gen `id'=_n
+
+
+qui keep `varlist' `comp' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+* di "LD : `ld'"
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+ *qui drop if `rep'`i'==.|`rep'`i'>1
+ *qui replace `score'=`score'+`rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep' , i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+1']=exp(`est'[1,`=`nbitems'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ *xtlogit `rep' , offset(`offset') i(`id') nocons iterate(`iterate')
+ qui gllamm `rep' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+* noi ereturn list
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',0
+ matrix `est'[1,`=`nbitems'+1']=exp(`b'[1,1]/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1', group(`id')
+}
+
+*set trace on
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ *set trace on
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])*`sig'/2
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ local sig=`tmp'[1,1]
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[1,1])
+ matrix `beta'=`difficulties'
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ capture gllamm `rep' `rep'1-`rep'`nbitems', i(`id') nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/`vartheta'
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld'
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+if "`method'"!="cml" {
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig'
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+/*Tabular of the estimated values of the latent trait*/
+
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+ if "`method'"=="mml"|"`method'"=="gee" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ *di in green "Personal Separation Index (PSI)" _col(50) in ye %5.3f `psi'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ }
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ *graph twoway (scatter `outfit' `id'), name(outfit,replace) yline(.6 1.4) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(0(.2)2 2(.5)`maxo') `draw'
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ *graph twoway (scatter `infit' `id'), name(infit,replace) yline(.6 1.4) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(0(.2)2 2(.5)`maxi') `draw'
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld'
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld'
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld'
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE)
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ qui gen `genlt'=`genlt2' `if'
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+end
diff --git a/Modules/ado/personal/r/old/raschtestv782.ado b/Modules/ado/personal/r/old/raschtestv782.ado
new file mode 100644
index 0000000..e6baeb9
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv782.ado
@@ -0,0 +1,2157 @@
+*! version 8 24june2009
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) DIF2(string)]
+
+local covariables `covariates'
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee"&"`method'"!="pce" {
+ di in red "Uncorrect {hi:method} option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ capture confirm new variable `genfit' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`method'"=="pce" {
+*set trace on
+*set tracedepth 1
+ raschpce `varlist'
+ exit
+}
+
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+local nbinteractions=0
+if "`dif2'"!="" {
+ local interactions
+ local listinteractions
+ forvalues i=1/`nbcovariables' {
+ forvalues j=1/`nbitems' {
+ if `dif2'[`i',`j']==1 {
+ gen int`nbinteractions'=-`rep'`j'*`covariable`i''
+ qui su int`nbinteractions'
+ *replace int`nbinteractions'=int`nbinteractions'-`r(mean)'
+ local interactions `interactions' int`nbinteractions'
+ local listinteractions `listinteractions' ``j''*`covariable`i''
+ local ++nbinteractions
+ }
+ }
+ }
+}
+
+* set trace on
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ *di "xtlogit `rep' `rep'1-`rep'`nbitems' `covariables' `interactions', i(`id') nocons iterate(`iterate')"
+ *list in 1/10
+ *dshqkjf
+ xtlogit `rep' `rep'1-`rep'`nbitems' `covariables' `interactions', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+`nbinteractions'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+`nbinteractions'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' `interactions', offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+`nbinteractions'+1']=exp(`b'[1,`=`nbcovariables'+`nbinteractions'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+`nbinteractions'+1',`=`nbitems'+`nbcovariables'+`nbinteractions'+1',.)
+ matrix `var'[`=`nbitems'/*+`nbcovariables'+`nbinteractions'*/+1',`=`nbitems'/*+`nbcovariables'+`nbinteractions'*/+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+`nbinteractions'+1',`=`nbitems'+`nbinteractions'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'+`nbinteractions'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'+`nbinteractions'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'+`nbinteractions'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+`nbinteractions'+1',`=`nbitems'+`nbcovariables'+`nbinteractions'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`=`nbcovariables'+`nbinteractions'']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+`nbinteractions'+1',`=`nbcovariables'+`nbinteractions'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`=`nbcovariables'+`nbinteractions'',1..`=`nbcovariables'+`nbinteractions'']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ forvalues i=1/`nbinteractions'{
+ local tmp:word `i' of `interactionss'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables' `interactions', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', id(`id') test(NONE) `ld'
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+
+
+di
+if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+}
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local ss10=`var0'*`=`N'-1'
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 56}"
+ di in green _col(27) "Variance of the" _col(48) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(30) "latent trait" _col(49) "Variance"
+ di "{hline 56}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(34) %8.3f `var0'
+ di in green "{dup 56:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local ss1`i'=`var`i''*`=`N'-1'
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss1`=`i'-1''-`ss1`i''' _col(34) %8.3f `var`i'' _col(52) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 56}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local ss30=`var0'*`=`N'-1'
+ }
+ else {
+ local ss30=`ss10'
+ }
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 56}"
+ di in green _col(27) "Variance of the" _col(48) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(30) "latent trait" _col(49) "Variance"
+ di "{hline 56}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(34) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `sig'^2*(`N'-1) _col(34) %8.3f `sig'^2
+ di in green "{dup 56:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local ss3s`i'=`vars`i''*`=`N'-1'
+ local vara`i'=`sig'^2
+ local ss3a`i'=`vara`i''*`=`N'-1'
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(34) %8.3f `vars`i'' _col(52) %5.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 56}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+}
+if "`method'"=="mml"|"`method'"=="gee" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,id(`id') test(NONE) meth(cml) `ld'
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,id(`id') test(NONE) meth(cml) `ld'
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',id(`id') test(NONE) meth(cml) `ld'
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', id(`id') test(NONE)
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/old/raschtestv785.ado b/Modules/ado/personal/r/old/raschtestv785.ado
new file mode 100644
index 0000000..4025d5d
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv785.ado
@@ -0,0 +1,2146 @@
+*! version 8.5 20december2009
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string)]
+
+local covariables `covariates'
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+
+
+di
+if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+}
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local df0=`N'*`nbitems'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 75}"
+ di in green _col(34) "Degrees" _col(46) "Variance of the" _col(67) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(34) "freedom"_col(49) "latent trait" _col(68) "Variance"
+ di "{hline 75}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(37) %4.0f `df0' _col(53) %8.3f `var0'
+ di in green "{dup 75:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count of `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`N'*`nbitems'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`N'*`nbitems'-(`nbitems'+1+`nbcovtmp')-1
+ local ss1`i'=`var`i''* `df`i''
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss1`=`i'-1''-`ss1`i''' _col(40) %4.0f "1" _col(53) %8.3f `var`i'' _col(71) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 75}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local df0=`N'*`nbitems'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 75}"
+ di in green _col(34) "Degrees" _col(46) "Variance of the" _col(67) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(34) "freedom"_col(49) "latent trait" _col(68) "Variance"
+ di "{hline 75}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(37) %4.0f `df0' _col(53) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `=`sig'^2*(`df0'+`nbcovariables')' _col(37) %4.0f `=`df0'+`nbcovariables'' _col(53) %8.3f `sig'^2 _col(71) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 75:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local ss3s`i'=`vars`i''*`=`N'-1'
+ local vara`i'=`sig'^2
+ local ss3a`i'=`vara`i''*`=`N'-1'
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(40) %4.0f "1" _col(53) %8.3f `vars`i'' _col(71) %5.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 75}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+}
+if "`method'"=="mml"|"`method'"=="gee" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/old/raschtestv7jf.ado b/Modules/ado/personal/r/old/raschtestv7jf.ado
new file mode 100644
index 0000000..35b27f3
--- /dev/null
+++ b/Modules/ado/personal/r/old/raschtestv7jf.ado
@@ -0,0 +1,2239 @@
+*! version 8.2 15july2009
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2009 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7jf,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [ MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) ]
+
+local covariables `covariates'
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ capture confirm new variable `genfit' `genscore'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+
+
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp verytmp2
+ qui save `verytmp',replace
+ clear
+ qui use `saveraschtest'
+
+ tempvar itembis score2 a aa b c z
+ forvalues i=1/`nbitems'{
+ gen `itembis'`i'=``i''
+ replace `itembis'`i'=0 if ``i''==.
+ }
+ genscore `itembis'*, score(`score2')
+ drop `itembis'*
+
+ local exp "string(`1'!=.)"
+ noi di
+ local exp2 "`1'==. "
+ forvalues i=2/`nbitems'{
+ local exp "`exp'+string(``i''!=.)"
+ local exp2 "`exp2' & ``i''==."
+ }
+ gen `z'=0
+ replace `z'=1 if `exp2'
+* save "~/Bureau/baseRasch.dta", replace
+set trace on
+set tracedepth 1
+ su
+ gen `aa'=`exp' if `z'==0
+
+ encode `aa',gen(`b')
+ bysort `b': gen `c'=_n if `z'==0
+ su `b'
+ local nbpos=r(max)
+
+forvalues i=1/`nbpos'{
+ su `score2' if `b'==`i'
+ local scorem`i'=r(max)
+ local expp`i' ""
+ local expi`i' ""
+ local expj`i' ""
+ forvalues j=1/`nbitems'{
+ su ``j'' if `b'==`i'
+ if r(N)!=0{
+ local expp`i' "`expp`i'' p`j'"
+ local expi`i' "`expi`i'' i`j'"
+ local expj`i' "`expj`i'' j`j'"
+ }
+ }
+}
+drop `aa' `c'
+qui save `verytmp2',replace
+
+
+
+
+
+
+
+
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+
+
+
+forvalues i=1/`nbpos'{
+ egen P`i'=rsum(`expp`i'')
+ egen I`i'=rsum(`expi`i'')
+ egen J`i'=rsum(`expj`i'')
+ tempname theta sdtheta
+ matrix `theta'`i'=J(1,`=`scorem`i''+1',0)
+ matrix `sdtheta'`i'=J(`=`scorem`i''+1',`=`scorem`i''+1',0)
+ forvalues s=0/`scorem`i'' {
+ capture drop f`s'
+ gen f`s'=abs(`s'-P`i'+.5*J`i'/I`i'^2)
+ sort f`s'
+ matrix `theta'`i'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'`i'[`=`s'+1',`=`s'+1']=sqrt(1/I`i'[1])
+ }
+ drop P`i' I`i' J`i'
+}
+matrix `theta'=`theta'`nbpos'
+matrix `sdtheta'=`sdtheta'`nbpos'
+
+use "`verytmp2'",replace
+
+tempvar gentl3 sdgentl3
+gen `gentl3'=.
+gen `sdgentl3'=.
+forvalues i=1/`nbpos'{
+ forvalues j=0/`scorem`i''{
+ replace `gentl3'=`theta'`i'[1,`=`j'+1'] if `score2'==`j'& `b'==`i'
+ replace `sdgentl3'=`sdtheta'`i'[1,`=`j'+1'] if `score2'==`j'& `b'==`i'
+ }
+}
+
+keep `id' `gentl3' `sdgentl3'
+qui save `verytmp2',replace
+
+
+
+
+
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempname Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7jf `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+di in green "Number of items: " in yellow `nbitems'
+
+di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+di in green "Number of individuals: " in yellow `N'
+di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+if "`ld'"=="" {
+ di in green " (removed)"
+}
+else {
+ di
+}
+di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+if "`method'"=="cml" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+else {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+}
+di
+noi di in green _col(16) "Difficulty" `conttest'
+if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+}
+noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+}
+di in green "{hline `line'}"
+forvalues i=1/`nbitems' {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ if "`test'"!="NONE" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ di in ye _col(72) %6.3f `U`i''
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ }
+}
+di in green "{hline `line'}"
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+}
+
+if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+}
+if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+}
+if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+}
+if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+}
+
+
+
+di
+if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+}
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7jf `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local ss10=`var0'*`=`N'-1'
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 56}"
+ di in green _col(27) "Variance of the" _col(48) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(30) "latent trait" _col(49) "Variance"
+ di "{hline 56}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(34) %8.3f `var0'
+ di in green "{dup 56:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7jf `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local ss1`i'=`var`i''*`=`N'-1'
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss1`=`i'-1''-`ss1`i''' _col(34) %8.3f `var`i'' _col(52) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 56}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7jf `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local ss30=`var0'*`=`N'-1'
+ }
+ else {
+ local ss30=`ss10'
+ }
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 56}"
+ di in green _col(27) "Variance of the" _col(48) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(30) "latent trait" _col(49) "Variance"
+ di "{hline 56}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(34) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `sig'^2*(`N'-1) _col(34) %8.3f `sig'^2
+ di in green "{dup 56:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7jf `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local ss3s`i'=`vars`i''*`=`N'-1'
+ local vara`i'=`sig'^2
+ local ss3a`i'=`vara`i''*`=`N'-1'
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(34) %8.3f `vars`i'' _col(52) %5.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 56}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ di in green _col(17) "{dup `line':-}"
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ local nonul=`nonul'+1
+ }
+ }
+ di in green _col(17) "{hline `line'}"
+}
+if "`method'"=="mml"|"`method'"=="gee" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`v8'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`v8'"!="" {
+ graph twoway (line `info' `latent') , name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ pause
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstd' `id'), name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfit "`savingo'" , `replace'
+ graph save infit "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ pause
+ graph twoway (scatter `infitstdj' `betap',name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save outfititem "`savingo'" , `replace'
+ graph save infititem "`savingi'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7jf `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7jf `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7jf `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ pause
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7jf `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+
+
+
+
+
+
+
+
+
+ else if "`method'"=="cml" {
+
+ qui sort `id'
+ qui merge `id' using `verytmp2'
+ qui rename `gentl3' `genlt'
+ qui rename `sdgentl3' se`genlt'
+ qui drop _merge
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/old/rsoort.do b/Modules/ado/personal/r/old/rsoort.do
new file mode 100644
index 0000000..76f1389
--- /dev/null
+++ b/Modules/ado/personal/r/old/rsoort.do
@@ -0,0 +1,584 @@
+*! version 1 25februar2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=1 numeric) [if] [in] [,METHod(string) UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPriorisation(varlist) noSearch]
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+di _col(20) "{hline 30}"
+di _col(20) in gr "Time 1" _col(40) "Time 2"
+di _col(20) "{hline 30}"
+forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+}
+di _col(20) "{hline 30}"
+
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+qui sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method')
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+
+di "{hline 105}"
+di in gr _col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"
+di in gr "Models" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+di in gr "Model 1" _col(20) %8.2f in ye `chi21'
+di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' _col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'
+di "{hline 105}"
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+
+forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `repriorisation'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `repriorisation'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+}
+matrix list `RS'
+
+if "`search'"=="" {
+
+di
+di "{hline 105}"
+di in green _col(50) "Model 3"
+di "{hline 105}"
+di
+di in white _col(10) "Non uniform Recalibration"
+
+local continue=1
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+}
+local prec_chi2=`chi22'
+local testNU_varchi2=0
+local testNU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+
+while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+/**************************************************************************************************************
+Model 3 / Uniform recalibration
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Uniform Recalibration"
+
+local continue=1
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+
+/**************************************************************************************************************
+Model 3 / Repriorisation
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Repriorisation"
+
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) "Anavailable"
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+di
+di "{hline 74}"
+di in gr _col(22) "Non uniform" _col(46) "Uniform"
+di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(60) "Repriorisation"
+di "{hline 74}"
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+}
+di "{hline 74}"
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100)
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+
+di
+di "{hline 95}"
+di in gr "Models" _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+di "{hline 95}"
+di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `dfc2' _col(30) %6.4f `p2' _col(40) %6.4f `rmsea2' _col(50) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+*di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `dfc4' _col(30) %6.4f `p4' _col(40) %6.4f `rmsea4' _col(50) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+di "{hline 95}"
+
+
+
+di
+di "{hline 77}"
+di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+di "{hline 77}"
+di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+di "{hline 77}"
+
+di
+
+
+
+
+end
diff --git a/Modules/ado/personal/r/old/rsoort1 (2).ado b/Modules/ado/personal/r/old/rsoort1 (2).ado
new file mode 100644
index 0000000..76f1389
--- /dev/null
+++ b/Modules/ado/personal/r/old/rsoort1 (2).ado
@@ -0,0 +1,584 @@
+*! version 1 25februar2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=1 numeric) [if] [in] [,METHod(string) UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPriorisation(varlist) noSearch]
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+di _col(20) "{hline 30}"
+di _col(20) in gr "Time 1" _col(40) "Time 2"
+di _col(20) "{hline 30}"
+forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+}
+di _col(20) "{hline 30}"
+
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+qui sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method')
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+
+di "{hline 105}"
+di in gr _col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"
+di in gr "Models" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+di in gr "Model 1" _col(20) %8.2f in ye `chi21'
+di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' _col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'
+di "{hline 105}"
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+
+forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `repriorisation'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `repriorisation'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+}
+matrix list `RS'
+
+if "`search'"=="" {
+
+di
+di "{hline 105}"
+di in green _col(50) "Model 3"
+di "{hline 105}"
+di
+di in white _col(10) "Non uniform Recalibration"
+
+local continue=1
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+}
+local prec_chi2=`chi22'
+local testNU_varchi2=0
+local testNU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+
+while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+/**************************************************************************************************************
+Model 3 / Uniform recalibration
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Uniform Recalibration"
+
+local continue=1
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+
+/**************************************************************************************************************
+Model 3 / Repriorisation
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Repriorisation"
+
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) "Anavailable"
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+di
+di "{hline 74}"
+di in gr _col(22) "Non uniform" _col(46) "Uniform"
+di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(60) "Repriorisation"
+di "{hline 74}"
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+}
+di "{hline 74}"
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100)
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+
+di
+di "{hline 95}"
+di in gr "Models" _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+di "{hline 95}"
+di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `dfc2' _col(30) %6.4f `p2' _col(40) %6.4f `rmsea2' _col(50) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+*di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `dfc4' _col(30) %6.4f `p4' _col(40) %6.4f `rmsea4' _col(50) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+di "{hline 95}"
+
+
+
+di
+di "{hline 77}"
+di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+di "{hline 77}"
+di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+di "{hline 77}"
+
+di
+
+
+
+
+end
diff --git a/Modules/ado/personal/r/old/rsoort1.ado b/Modules/ado/personal/r/old/rsoort1.ado
new file mode 100644
index 0000000..76f1389
--- /dev/null
+++ b/Modules/ado/personal/r/old/rsoort1.ado
@@ -0,0 +1,584 @@
+*! version 1 25februar2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=1 numeric) [if] [in] [,METHod(string) UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPriorisation(varlist) noSearch]
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+di _col(20) "{hline 30}"
+di _col(20) in gr "Time 1" _col(40) "Time 2"
+di _col(20) "{hline 30}"
+forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+}
+di _col(20) "{hline 30}"
+
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+qui sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method')
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+
+di "{hline 105}"
+di in gr _col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"
+di in gr "Models" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+di in gr "Model 1" _col(20) %8.2f in ye `chi21'
+di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' _col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'
+di "{hline 105}"
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+
+forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `repriorisation'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `repriorisation'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+}
+matrix list `RS'
+
+if "`search'"=="" {
+
+di
+di "{hline 105}"
+di in green _col(50) "Model 3"
+di "{hline 105}"
+di
+di in white _col(10) "Non uniform Recalibration"
+
+local continue=1
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+}
+local prec_chi2=`chi22'
+local testNU_varchi2=0
+local testNU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+
+while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+/**************************************************************************************************************
+Model 3 / Uniform recalibration
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Uniform Recalibration"
+
+local continue=1
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+
+
+
+
+/**************************************************************************************************************
+Model 3 / Repriorisation
+***************************************************************************************************************/
+
+di
+di in white _col(10) "Repriorisation"
+
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+}
+local testU_varchi2=0
+local testU_p=1
+di "{hline 105}"
+di in gr _col(39) "Comparison with previous model" _col(79) "Comparison with model 1"
+di in gr "Items" _col(18) "Chi-square" _col(39) "Chi-square" _col(54) "df" _col(59) "p-value" _col(79) "Chi-square" _col(94) "df" _col(99) "p-value"
+di "{hline 105}"
+
+while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(55) "1" %6.4f _col(60) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' _col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) "Anavailable"
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ di "{hline 105}"
+ }
+}
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+di
+di "{hline 74}"
+di in gr _col(22) "Non uniform" _col(46) "Uniform"
+di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(60) "Repriorisation"
+di "{hline 74}"
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+}
+di "{hline 74}"
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100)
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+
+di
+di "{hline 95}"
+di in gr "Models" _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+di "{hline 95}"
+di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `dfc2' _col(30) %6.4f `p2' _col(40) %6.4f `rmsea2' _col(50) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+*di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `dfc4' _col(30) %6.4f `p4' _col(40) %6.4f `rmsea4' _col(50) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+di "{hline 95}"
+
+
+
+di
+di "{hline 77}"
+di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+di "{hline 77}"
+di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+di "{hline 77}"
+
+di
+
+
+
+
+end
diff --git a/Modules/ado/personal/r/raschfit.ado b/Modules/ado/personal/r/raschfit.ado
new file mode 100644
index 0000000..d363b89
--- /dev/null
+++ b/Modules/ado/personal/r/raschfit.ado
@@ -0,0 +1,340 @@
+*! Raschfit version 4 (19 December 2012)
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : Raschfit
+* The Raschfit and the Raschfit-fast procedures to construct sub-scales of items
+*
+* Historic
+* Version 1 (2004-05-06) [Jean-Benoit Hardouin]
+* Version 2 (2004-06-08) [Jean-Benoit Hardouin]
+* Version 3 (2005-12-28) [Jean-Benoit Hardouin]
+* Release 3.1 (January 29, 2006) [Jean-Benoit Hardouin] /*MEAN option in raschtestv7, correction of a bug when there is several scales*/
+* Release 4 (December 19, 2019) [Jean-Benoit Hardouin] /*identifiant variable for raschtest and mmsrm*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2004-2006, 2012 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 raschfit,rclass
+version 7
+syntax varlist(min=2 numeric) [,KERnel(integer 0) NBSCales(integer 1) ITEMSorder(string) nofast ]
+if "`itemsorder'"=="" {
+ local itemsorder mspinv
+}
+local nbitemstot : word count `varlist'
+tokenize `varlist'
+
+tempfile raschfitfile
+qui save `raschfitfile',replace
+preserve
+
+tempname affect
+matrix define `affect'=J(1,`nbitemstot',0)
+matrix colnames `affect'=`varlist'
+
+tempvar id
+gen `id'=_n
+
+tempname rep item matbetadim1 matbetadim2
+if `kernel'!=0 {
+ local listkernel
+ forvalues i=1/`kernel' {
+ local listkernel `listkernel' `rep'`i'
+ matrix `affect'[1,`i']=1
+ }
+}
+
+local dim=0
+local nbitemsnosel=`nbitemstot'
+local nbitemstotdim1=`nbitemstot'
+local nbitemsnoselukernel=`nbitemstot'-`kernel'
+
+
+tempvar id betadim1 betadim2
+forvalues i=1/`nbitemstot' {
+ qui drop if ``i''==.
+ rename ``i'' `rep'`i'
+}
+qui gen `id'=_n
+tempfile filescale
+qui save `filescale',replace
+
+di in green "{hline 55}"
+qui count
+local N=r(N)
+if "`fast'"!="" {
+ di in green "Method: " in ye "Raschfit"
+}
+else {
+ di in green "Method: " in ye "Raschfit-Fast"
+}
+di in green "Number of individuals: " in ye `N' in green " (with none missing values)"
+di in green "Number of items: " in ye `nbitemstot'
+di in green "{hline 55}"
+di
+di in green "{hline 100}"
+if "`fast'"!="" {
+ di in green "Model 1: " in ye "Rasch model"
+ di in green "Model 2: " in ye "MMSRM"
+}
+else {
+ di in green "Model 1: " in ye "Rasch model"
+ di in green "Model 2: " in ye "Adapted Rasch model (the response of the new item is not influenced by the latent trait)"
+}
+di in green "Order of the items:" _c
+if "`itemsorder'"=="order" {
+ di in ye " order of {it:varlist}"
+}
+else if "`itemsorder'"=="msp" {
+ di in ye " Obtained with MSP (from the first selected item to the last one)"
+}
+else if "`itemsorder'"=="mspinv" {
+ di in ye " Obtained with MSP (from the last selected item to the first one)"
+}
+if `kernel'!=0 {
+ di in green "Kernel of the first scale: " _c
+ forvalues i=1/`kernel' {
+ di in ye " ``i''" _c
+ }
+ di
+}
+di in green "{hline 100}"
+di
+
+while `nbitemsnosel'>2&`dim'<`nbscales' {
+ use `filescale',replace
+ local iteration=0
+ local dim=`dim'+1
+ if `dim'>1 {
+ local kernel=0
+ local listkernel
+ }
+
+ di in green "SCALE: " in yellow `dim'
+ di in green "{hline 9}"
+ di
+ tempname result`dim'
+ local listitemsnosel
+ local varlist`dim'
+ tokenize `varlist'
+ forvalues i=1/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ local varlist`dim' `varlist`dim'' ``i''
+ local listitemsnosel `listitemsnosel' `rep'`i'
+ }
+ }
+ local nbitemsnosel:word count `listitemsnosel'
+ if `dim'>1 {
+ local nbitemstotdim`dim':word count `listitemsnosel'
+ }
+
+ if `kernel'>=2 {
+ local fixed=`kernel'
+ }
+ else {
+ local fixed=2
+ }
+ matrix define `result`dim''=J(`=`nbitemstotdim`dim''-`fixed'',`=`nbitemstotdim`dim''+7',0)
+
+ tempname order`dim' affect`dim'
+ matrix `order`dim''=J(1,`nbitemstotdim`dim'',0)
+ matrix `affect`dim''=J(1,`nbitemstotdim`dim'',0)
+
+ if "`itemsorder'"=="msp"|"`itemsorder'"=="mspinv" {
+ di in green _col(0) "The program is ordering the items"
+ di
+ qui msp `listkernel' `listitemsnosel',c(-99) notest kernel(`kernel')
+ local scale1 "`r(scale1)'"
+ local scalenum1 "`r(scalenum1)'"
+ tokenize `scalenum1'
+ local listitemsselnum
+ forvalues j=`=`nbitemstotdim`dim''+1-`fixed''/`nbitemstotdim`dim'' {
+ matrix `order`dim''[1,`j']=1
+ local k:word `j' of `scalenum1'
+ matrix `affect`dim''[1,`k']=1
+ local listitemsselnum `listitemsselnum' `k'
+ }
+ forvalues j=1/`nbitemsnosel' {
+ matrix `order`dim''[1,`j']=`=`nbitemsnosel'+1-`j''
+ }
+ tokenize `scale1'
+ local listitemssel ``=`nbitemstotdim`dim''-1'' ``nbitemstotdim`dim'''
+
+ local listitemsnosel
+ local listitemsnoselnum
+
+ if "`itemsorder'"=="mspinv" {
+ forvalues j=1/`=`nbitemstotdim`dim''-`fixed'' {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ else if "`itemsorder'"=="msp"{
+ forvalues j=`=`nbitemstotdim`dim''-`fixed''(-1)1 {
+ local listitemsnosel `listitemsnosel' ``j''
+ local k:word `j' of `scalenum1'
+ local listitemsnoselnum `listitemsnoselnum' `k'
+ }
+ }
+ }
+ else if "`itemsorder'"=="order" {
+ tokenize `listkernel' `varlist`dim''
+ local listitemssel
+ local listitemsselnum
+ local listitemsnosel
+ local listitemsnoselnum
+ forvalues j=1/`fixed'{
+ local listitemssel `listitemssel' `rep'`j'
+ local listitemsselnum `listitemsselnum' `j'
+ matrix `affect`dim''[1,`j']=1
+ }
+ forvalues j=`=`fixed'+1'/`nbitemstotdim`dim'' {
+ local listitemsnosel `listitemsnosel' `rep'`j'
+ local listitemsnoselnum `listitemsnoselnum' `j'
+ }
+ }
+
+ if `dim'>1 {
+ tokenize `varlist`dim''
+ }
+ else {
+ tokenize `varlist'
+ }
+
+ local nbitemsnosel:word count `listitemsnosel'
+ local list
+ tokenize `varlist`dim''
+ forvalues i=1/`=`nbitemsnosel'+`fixed'' {
+ local tmp:word `i' of `listitemsnoselnum' `listitemsselnum'
+ local list `list' ``tmp''
+ }
+ matrix colnames `result`dim''=`list' Iteration Nbitems ll1 AIC1 ll2 AIC2 Selected
+
+ di _col(0) in green "The kernel of the scale is " in yellow _continue
+ forvalues i=1/`fixed' {
+ local inum:word `i' of `listitemsselnum'
+ di in yellow "``inum'' " _continue
+ }
+ di
+ di
+ tokenize `listitemsnosel'
+ di in green "{hline 90}"
+ di in green _col(36) "Log-Likelihood" _col(58) "Akaike Criterion (AIC)"
+ di in green _col(4) "Iteration" _col(20) "New Item" _col(34) "Model 1" _col(47) "Model 2" _col(60) "Model 1" _col(73) "Model 2" _col(81) "Selected"
+ di in green "{hline 90}"
+ forvalues i=1/`=`nbitemsnosel-2'' {
+ local iteration=`iteration'+1
+ qui use `filescale' , clear
+ local i2:word `i' of `listitemsnosel'
+ local i2num:word `i' of `listitemsnoselnum'
+ qui keep `id' `listitemssel' `i2'
+ tempname score1 score2
+ qui gen `score2'=0
+ tokenize `listitemssel'
+ local nbitemssel: word count `listitemssel'
+ forvalues j=1/`i' {
+ local j2num:word `j' of `listitemsnoselnum'
+ if `affect`dim''[1,`j2num']==1 {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ }
+ forvalues j=1/`nbitemssel' {
+ local j2:word `j' of `listitemssel'
+ local j2num:word `j' of `listitemsselnum'
+ qui replace `score2'=`score2'+`j2'
+ }
+ tokenize `listitemsnosel'
+ qui gen `score1'=`score2'+`i2'
+ forvalues j=`=`nbitemsnosel'+1'/`=`nbitemsnosel'+`nbitemssel'' {
+ matrix `result`dim''[`iteration',`j']=1
+ }
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+1']=`iteration'
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+2']=`nbitemssel'
+ matrix `result`dim''[`iteration',`i']=2
+
+ if "`fast'"=="" {
+ qui count
+ local N=r(N)
+* di "qui raschtestv7 `listitemssel' `i2' , mean method(cml) test(none)"
+ qui raschtestv7 `listitemssel' `i2' , mean method(cml) test(none) id(`id')
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=r(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-r(ll)+(2*`nbitemssel'+3))
+
+ local nb1:word count `listitemssel'
+ qui raschtestv7 `listitemssel',trace test(none) mean id(`id')
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=r(ll)
+ qui logit `i2'
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=`result`dim''[`iteration',`=`nbitemstotdim`dim''+5']+e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-`result`dim''[`iteration',`=`nbitemstotdim`dim''+5']+(2*`nbitemssel'+3))
+ }
+ else {
+ qui count
+ local N=r(N)
+ qui raschtestv7 `listitemssel' `i2' , method(mml) test(none) id(`id')
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+3']=r(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+4']=2*(-r(ll)+`nbitemssel'+2)
+
+ local nb1:word count `listitemssel'
+ qui mmsrm `listitemssel' `i2' , part(`nb1' 1) iterate(20) id(`id')
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+5']=e(ll)
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+6']=2*(-e(ll)+`nbitemssel'+4)
+ }
+ tokenize `listkernel' `varlist`dim''
+ di in ye _col(4) %9.0f `iteration' _col(14) %14s abbrev("``i2num''",14) _col(29) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+3'] _col(42) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+5'] _col(55) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+4'] _col(68) %12.4f `result`dim''[`iteration',`=`nbitemstotdim`dim''+6'] _c
+ if `result`dim''[`iteration',`=`nbitemstot'+4']<=`result`dim''[`iteration',`=`nbitemstot'+6'] {
+ matrix `result`dim''[`iteration',`i']=1
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=1
+ local nbitemssel=`nbitemssel'+1
+ local nbitemsnosel=`nbitemsnosel'-1
+* local listitemssel `listitemssel' `rep'`i2num'
+ local listitemssel `listitemssel' `i2'
+ local listitemsselnum `listitemsselnum' `i2num'
+ matrix `affect`dim''[1,`i2num']=1
+ di in ye _col(88) "X"
+ }
+ else {
+ matrix `result`dim''[`iteration',`=`nbitemstotdim`dim''+7']=2
+ di
+ }
+ }
+ di in green "{hline 90}"
+ return matrix result`dim' `result`dim''
+ local j=`kernel'+1
+ forvalues i=`=`kernel'+1'/`nbitemstot' {
+ if `affect'[1,`i']==0 {
+ if `affect`dim''[1,`j']==1 {
+ matrix `affect'[1,`i']=`dim'
+ }
+ local j=`j'+1
+ }
+ }
+}
+use `raschfitfile',clear
+
+return matrix affect `affect'
+
+end
diff --git a/Modules/ado/personal/r/raschfit.hlp b/Modules/ado/personal/r/raschfit.hlp
new file mode 100644
index 0000000..3585db6
--- /dev/null
+++ b/Modules/ado/personal/r/raschfit.hlp
@@ -0,0 +1,70 @@
+{smcl}
+{* 208December2005}{...}
+{hline}
+help for {hi:raschfit}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:The Raschfit procedure}
+
+{p 8 14 2}{cmd:raschfit} {it:varlist} {cmd:,} [{cmdab:ker:nel}({it:#}) {cmdab:nbsc:ales}({it:#}) {cmdab:items:order}({it:keyword}) {cmdab:nofast}]
+
+{title:Description}
+
+{p 4 8 2}{cmd:raschfit} realizes the Raschfit algorithm defined by Hardouin and
+Mesbah (2004). This method selects sub-scales of items which fit a
+Rasch model. The method begin with a kernel of items (two or more items)
+defined by the user. At each step, the method uses a new item and verifies if this
+new item is explained by the same latent trait than the already selected items.
+If not, the items is not selected. The former version of the Raschfit algorithm
+is based on the comparison of two model: A Rasch model and a Multidimensional
+Marginally Sufficient Rasch Model (MMSRM). These two models are compared by the
+Akaike Information Criterion (AIC). A faster version of the algorithm (Raschfit-Fast)
+compares the Rasch model and an adapted version of this model where the response
+to the "new" item is not explained by the latent trait. Raschfit-Fast is executed
+by default.
+
+{title:Options}
+
+{p 4 8 2}{cmd:kernel}({it:#}) defines the # first items of {it:varlist} as the kernel
+of the first sub-scale (by default with {cmd:itemsorder}({it:order}), this number is
+fixed to 2).
+
+{p 4 8 2}{cmd:nbscales}({it:#}) defines the maximal number of sub-scales (by default,
+only one sub-scale is selected).
+
+{p 4 8 2}{cmd:itemsorder}({it:keyword}) defines the order of the items. If you type
+{it:order}, the kernel is composed of the first items defined in {it:varlist},
+and the items are tested in the same order than in {it:varlist}.
+If you type {it:msp} or {it:mspinv}, a Mokken Scale Procedure is run under
+the items (the {it:msp} and {it:loevH} Stata programs are necessary) and the
+items are selected from the first order selected by this procedure to the last
+one (with {it:msp}), or in the inverse order (with {it:mspinv}). The method {it:msp}
+is generaly more robust, but is longer to run. By default, the program uses {it:msp}.
+
+{p 4 8 2}{cmd:nofast} allows to execute the former version of the algorithm.
+
+{title:Example}
+
+{p 4 8 2}{cmd:. raschfit itemA* , itemsorder(order)}
+
+{p 4 8 2}{cmd:. raschfit itemA1-itemA7 , itemsorder(msp) kernel(4) nofast}
+
+{p 4 8 2}{cmd:. raschfit item* }
+
+{title:References}
+
+{p 4 8 2} Hardouin J.-B. and Mesbah M. {it:Clustering binary variables in subscales using an extended Rasch model and Akaike Information Criterion}, Communication in Statistics Theory and methods}, {cmd:33}(6), pp. 1277-1294, 2004
+
+{p 4 8 2} Hardouin J.-B. {it:Construction d'échelles d'items unidimensionnelles en qualité de vie (Item selection in unidimensional scale applied to the Quality of Life)}, PhD thesis of the University René Descartes - Paris 5,
+France, 201 pp, 2005
+
+{p 4 8 2} Hardouin J.-B. and Mesbah M. {it:Fast Clustering of Binary Variables in Subscales}, Unpublished document, 2005.
+
+{title:Author}
+
+{p 4 8 2} Jean-Benoit Hardouin, Regional Health Observatory (ORS) - 1, rue Porte
+Madeleine - BP 2439 - 45032 Orleans Cedex 1 - France. You can contact the
+author at
+{browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+and visit the websites {browse "http://anaqol.free.fr":AnaQol}
+and {browse "http://freeirt.free.fr":FreeIRT}
diff --git a/Modules/ado/personal/r/raschlong.ado b/Modules/ado/personal/r/raschlong.ado
new file mode 100644
index 0000000..168653e
--- /dev/null
+++ b/Modules/ado/personal/r/raschlong.ado
@@ -0,0 +1,229 @@
+*! version 1 : February 15th, 2012
+*! Myriam Blanchin
+************************************************************************************************************
+* raschlong: Estimation of the parameters of a model of the Rasch family in a longitudinal setting
+*
+* Version 1 : February 15th, 2012: pcm et rasch, contraintes sur la matrice de variance-covariance et difficultés d'items fixées
+*
+************************************************************************************************************/
+
+program define raschlong,eclass
+syntax varlist [, NBT(int 2) DIFFiculties(string) VAR(string) ]
+
+*the dataset should be in wide format
+*the matrix of difficulties should contain `nbit' rows and `nbmodpos' columns
+*the item parameters are assumed to be constant with time
+*same number of modalities for each item
+*varlist should contain for each timepoint the list of variables containing the answers to the items - example: T1item1 T1item2 T1item3 T2item1 T2item2 T2item3
+preserve
+
+tempname diff varcov item id temps one obs estbeta estvar
+/*di "item" "`item'"
+di "temps" "`temps'"
+di "obs" "`obs'"
+di "diff" "`diff'"
+di "varcov" "`varcov'"
+di "id" "`id'"
+di "one" "`one'"*/
+*verif varlist
+tokenize `varlist'
+local nbittot:word count `varlist'
+local nbit=`nbittot'/`nbt'
+if `=int(`nbit')'!=`nbit'{
+ di in red "The number of variables should be equal to (the number of items * the number of timepoints). Please correct it."
+ error 198
+ exit
+}
+
+
+/*verif nb diff items*/
+if "`difficulties'"!=""{
+ matrix `diff'=`difficulties'
+ if `nbit'!=`=rowsof(`diff')'{
+ di in red "The number of rows of the matrix of item parameters should be equal to the number of items. Please correct it."
+ error 198
+ exit
+ }
+ local nbmodat=colsof(`diff')+1
+}
+else{
+ local modcount=word("`varlist'",1)
+ qui tab `modcount'
+ local nbmodat=r(r)
+}
+
+*verif matcov
+if "`var'"!=""{
+ matrix `varcov'=`var'
+ if `=rowsof(`var')'!=`nbt'{
+ di in red "The covariance matrix is incorrectly specified. Please correct it."
+ error 198
+ exit
+ }
+}
+
+qui{
+ *reshape of the dataset
+ gen `one'=1
+ collapse(sum) wt2=`one', by (`varlist')
+ *list in 1/3
+ forvalues t=1/`nbt'{
+ forvalues i=1/`nbit'{
+ local vartemp=word("`varlist'",`=(`t'-1)*`nbit'+`i'')
+ gen tps`t'item`i'=`vartemp'
+ }
+ }
+
+ gen `id'=_n
+ local list=""
+ forvalues i=1/`nbit'{
+ local list="`list' tps@item`i'"
+ }
+ reshape long `list', i(`id') j(`temps')
+ *list in 1/20
+ reshape long tpsitem, i(`id' `temps') j(`item')
+ *list in 1/20
+ drop if tpsitem==.
+ gen `obs'=_n
+ expand `nbmodat'
+ sort `id' `temps' `item' `obs'
+ *list in 1/20
+ tab `temps', gen(t)
+ forvalues t=1/`nbt'{
+ by `obs', sort: gen x`t'=(_n-1)*t`t'
+ }
+ gen chosen=.
+ forvalues t=1/`nbt'{
+ replace chosen=tpsitem==x`t' if `temps'==`t'
+ }
+ tab `item', gen(it)
+
+ if "`difficulties'"==""{
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`nbmodat'-1'{
+ gen d`i'_`g'=.
+ }
+ }
+ forvalues t=1/`nbt'{
+ forvalues i=1/`nbit'{
+ forvalues g=1/`=`nbmodat'-1'{
+ replace d`i'_`g'=-1*it`i'*(x`t'>=`g') if `temps'==`t'
+ }
+ }
+ }
+ }
+ else{
+ gen offset=0
+ forvalues t=1/`nbt'{
+ forvalues i=1/`nbit'{
+ local sumdiff=0
+ forvalues g=1/`=`nbmodat'-1'{
+ local sumdiff=`sumdiff'-`diff'[`i',`g']
+ replace offset=`sumdiff' if it`i'==1 & x`t'==`g'
+ }
+ }
+ }
+ }
+ *list in 1/25
+ local listeq ""
+ forvalues t=1/`nbt'{
+ eq slope`t':x`t'
+ local listeq "`listeq' slope`t'"
+ }
+ if "`var'"!=""{
+ matrix C=cholesky(`varcov')
+ constraint define 1 [__01_1]x1=`=C[1,1]'
+ constraint define 2 [__01_2]x2=`=C[2,2]'
+ constraint define 3 [__01_2_1]_cons=`=C[2,1]'
+ }
+}
+tempname b V
+if "`difficulties'"==""{
+ if "`var'"==""{
+ gllamm x1-x`nbt' d1_1-d`nbit'_`=`nbmodat'-1',i(`id') eqs(`listeq') link(mlogit) expand(`obs' chosen o) weight(wt) nocons nrf(`nbt') adapt
+ }
+ else{
+ gllamm x1-x`nbt' d1_1-d`nbit'_`=`nbmodat'-1',i(`id') eqs(`listeq') link(mlogit) constraints(1 2 3) expand(`obs' chosen o) weight(wt) nocons nrf(`nbt') adapt
+ }
+ matrix `b'=e(b)
+ matrix EstDiff=J(`nbit',`=`nbmodat'-1',.)
+ forvalues j=1/`nbit'{
+ matrix EstDiff[`j',1]=`b'[1,`=`nbt'+(`j'-1)*(`nbmodat'-1)'..`=`nbt'-1+`j'*(`nbmodat'-1)']
+ }
+
+}
+else{
+ if "`var'"==""{
+ gllamm x1-x`nbt',i(`id') eqs(`listeq') link(mlogit) expand(`obs' chosen o) weight(wt) nocons nrf(`nbt') adapt offset(offset)
+ }
+ else{
+ gllamm x1-x`nbt',i(`id') eqs(`listeq') link(mlogit) constraints(1 2 3) expand(`obs' chosen o) weight(wt) nocons nrf(`nbt') adapt offset(offset)
+ }
+ matrix `b'=e(b)
+}
+matrix `V'=e(V)
+matrix EstMu=`b'[1,1..`=`nbt'-1']
+matrix Var=e(chol)*e(chol)'
+matrix se2=vecdiag(`V'[1..`=`nbt'-1',1..`=`nbt'-1'])
+
+/*if test
+test x2=x3=0
+ r(chi2)
+ r(df)
+ r(p)
+*/
+di
+di
+di in gr "{hline 91}"
+di in gr _col(39) "RASCH FAMILY MODEL"
+di in gr "{hline 91}"
+di in gr "Number of timepoints: " in ye `nbt'
+di in gr "Number of items: " in ye `nbit'
+di in gr "Number of modalities per item: " in ye `nbmodat'
+di in gr "{hline 91}"
+
+local collist ""
+forvalues i=1/`=`nbmodat'-1'{
+ local collist "`collist' dj_`i'"
+}
+local rowlist ""
+forvalues i=1/`nbit'{
+ local rowlist "`rowlist' item`i'"
+}
+
+if "`difficulties'"==""{
+ di in gr "Item parameters estimations:"
+ matrix colnames EstDiff = `collist'
+ matrix rownames EstDiff = `rowlist'
+ matrix list EstDiff,noheader format(%7.3f)
+ ereturn matrix Diff=EstDiff
+}
+else{
+ di in gr "Item parameters fixed to:"
+ matrix colnames `diff' = `collist'
+ matrix rownames `diff' = `rowlist'
+ matrix list `diff',noheader format(%7.3f)
+ ereturn matrix Diff=`diff'
+}
+di
+di
+if "`var'"==""{
+ di in gr "Covariance matrix estimations:"
+}
+else{
+ di in gr "Covariance matrix fixed to:"
+}
+matrix list Var,noheader nonames format(%7.3f)
+di
+di
+di in gr "Time effect estimations:"
+di in gr _col(19) "Coef" _col(29) "S.E."
+forvalues t=1/`=`nbt'-1'{
+ di in gr "Time" `=`t'+1' in ye _col(16) %7.2f EstMu[1,`t'] _col(26) %7.2f `=sqrt(se2[1,`t'])'
+}
+
+ereturn matrix Var=Var
+
+
+
+end
diff --git a/Modules/ado/personal/r/raschlongitudinal2.ado b/Modules/ado/personal/r/raschlongitudinal2.ado
new file mode 100644
index 0000000..24aa04f
--- /dev/null
+++ b/Modules/ado/personal/r/raschlongitudinal2.ado
@@ -0,0 +1,210 @@
+* 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 raschlongitudinal2,rclass
+syntax [varlist] [, n(int 100) diff(string) Mu(string) Sigma(string) Nodes(int 12) fast]
+version 11
+tempfile raschlongitudinalfile
+capture qui save "`raschlongitudinalfile'",replace
+
+if "`diff'"=="" {
+ tempname diff
+ *matrix `diff'=[-1\0\1]
+ matrix `diff'=[-1\-.5\0\.5\1]
+}
+
+if "`mu'"=="" {
+ tempname mu
+ matrix `mu'=[0,0]
+}
+if "`sigma'"=="" {
+ tempname sigma
+ matrix `sigma'=[1,0\0,1]
+}
+
+local nbitems=rowsof(`diff')
+*local J=rowsof(`diff')+1
+*local Nbit=rowsof(`diff')*2
+di in gr "Number of individuals in the study: " in ye `n'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: " _c
+tempname dt
+matrix `dt'=`diff' ' ''
+matrix list `dt',noblank nohalf nonames noheader
+di in green "mean of the latent traits: " _c
+matrix list `mu',noblank nohalf nonames noheader
+di in green "variance matrix of the latent traits: " _c
+di
+matrix list `sigma',noblank nohalf nonames noheader
+
+
+if "`data'"=="" {
+ clear
+ local temp=2^(`nbitems'*2)
+ qui range x1 0 `=`temp'-1' `temp'
+ qui g t=x1
+ qui g x2=x1
+ qui g x=x2
+ loc i=1
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui g item`i'=mod(t,2^`i')==2^`=`i'-1'
+ qui replace t=t-item`i'*2^`=`i'-1'
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'+1
+ }
+}
+drop t
+*edit
+
+if "`fast'"=="" {
+ qui gen proba=.
+ *qui gen proba2=.
+ forvalues i=1/`temp' {
+ local int1=1
+ local int2=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diffic=`diff'[`j',1]
+ local int1 "`int1'*exp(`rep'*(x1-`diffic'))/(1+exp(x1-`diffic'))"
+ *di `j'
+ *di `int1'
+ }
+ *qui gausshermite `int1', mu(1) sigma(2) display
+ * di r(int)
+ *qui replace proba=r(int) in `i'
+
+ forvalues k=`=`nbitems'+1' /`=2*`nbitems'' {
+ qui su item`k' in `i'
+ local rep=r(mean)
+ local diffic=`diff'[`=`k'-`nbitems'',1]
+ local int2 "`int2'*exp(`rep'*(x2-`diffic'))/(1+exp(x2-`diffic'))"
+ }
+ *di `i'
+ *di "`int1'"
+ *di "`int2'"
+ local int "`int1'*`int2'"
+ qui gausshermite2 `int', mu(`mu') sigma(`sigma') display
+ qui replace proba=r(int) in `i'
+ *di proba[`i']
+ }
+ }
+
+ gen eff=proba
+ keep item* proba eff
+ *gen eff2=`n'*proba2
+ *keep item* proba proba2 eff1 eff2
+
+ edit
+ local p=1/`n'
+ qui gen eff2=floor(eff/`p')
+ *list eff2 eff
+ qui replace eff=eff-eff2*(`p')
+ qui su eff2
+ local aff=r(sum)
+
+ local unaff=`n'-`aff'
+ di `aff'
+ di `unaff'
+ gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff'
+
+ qui drop if eff2==0
+ gsort item*
+ *gen res=proba*50
+ * keep item* proba eff eff2 aff unaff
+
+ * Matrice complete qui ne tient pas compte des effectifs dans l'analyse
+
+ qui expand eff2
+ *qui drop proba eff eff2
+ *keep item* proba eff eff2
+ *}
+
+
+ forvalues j=1/`nbitems' {
+ rename item`j' T1reponse`j'
+ }
+
+ forvalues j=`=1+`nbitems''/`=2*`nbitems'' {
+ rename item`j' T2reponse`=`j'-`nbitems''
+ }
+rename eff2 Eff
+keep T1reponse* T2reponse* Eff
+
+gen id=_n
+forvalues i=1/`nbitems'{
+ local list="`list' T@reponse`i'"
+}
+reshape long `list', i(id) j(temps)
+reshape long Treponse, i(id temps) j(item)
+forvalues i=1/`nbitems'{
+ gen item`i'=0
+ replace item`i'=-1 if item==`i'
+}
+gen temps1=temps==1
+gen temps2=temps==2
+*gen W1=0
+*gen W2=0
+*replace W1=Eff if temps1==1
+*replace W2=Eff if temps2==1
+
+qui gen offset=0
+forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[`i',1] if item==`i'
+}
+
+matrix C=cholesky(`sigma')
+
+*constraint define 1 `sigma'[1,1]-C[1,1]^2=0
+*constraint define 2 `sigma'[2,2]-C[2,1]^2-C[2,2]^2=0
+*constraint define 3 `sigma'[2,1]-C[1,1]*C[2,1]=0
+
+*constraint define 1 id_1:temps1=`=sqrt(`sigma'[1,1])'
+*constraint define 2 id_2:temps2=`=sqrt(`sigma'[2,2]-`sigma'[2,1]^2/`sigma'[1,1])'
+*constraint define 3 id1_2_1:_cons=`=`sigma'[2,1]/sqrt(`sigma'[1,1])'
+
+*constraint define 1 var(1): =`=`sigma'[1,1]'
+*constraint define 2 cov(2,1): =`=`sigma'[1,2]'
+*constraint define 3 var(2): =`=`sigma'[2,2]'
+
+
+
+constraint define 1 id1_1:temps1=`=C[1,1]'
+constraint define 2 id1_2:temps2=`=C[2,2]'
+constraint define 3 id1_2_1:_cons=`=C[2,1]'
+
+/*CODE JBH*/
+gen Treponse1=Treponse if temps1
+replace Treponse1=0 if Treponse1==.
+gen Treponse2=Treponse if temps2
+replace Treponse2=0 if Treponse2==.
+
+constraint define 1 Treponse1=`=C[1,1]'
+constraint define 2 Treponse2=`=C[2,2]'
+constraint define 3 _cons=`=C[2,1]'
+
+eq b1:Treponse1
+eq b2:Treponse2
+/*FIN CODE JBH*/
+gllamm Treponse temps1 temps2, offset(offset) i(id) link(logit) nocons fam(bin) nrf(2) constraints(1 2 3) eqs(b1 b2) iterate(20) trace
+
+capture qui use `raschlongitudinalfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpce.ado b/Modules/ado/personal/r/raschpce.ado
new file mode 100644
index 0000000..aba801f
--- /dev/null
+++ b/Modules/ado/personal/r/raschpce.ado
@@ -0,0 +1,227 @@
+program define raschpce,rclass
+syntax varlist [if] [in] [, rsm]
+preserve
+if "`if'"!=""|"`in'"!="" {
+ di "if:`if' in: `in'"
+ keep `if' `in'
+}
+tokenize `varlist'
+
+local nbitems:word count `varlist'
+
+local lines=1
+local summ=0
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ local moda`i'=r(max)
+ local lines=`lines'*(`moda`i''+1)
+ local summ=`summ'+`moda`i''
+ if `modamax'<`moda`i'' {
+ local modamax `moda`i''
+ }
+}
+local col=1+`nbitems'
+*di "matrix table=J(`lines',`col',.)"
+
+
+*matrix table=J(`lines',`col',.)
+
+local line=1
+/*forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ forvalues mi=0/`moda`i'' {
+ forvalues mj=0/`moda`j'' {
+ matrix table[`line',`i']=`mi'
+ matrix table[`line',`j']=`mj'
+ qui count if ``i''==`mi'&``j''==`mj'
+ matrix table[`line',`=`nbitems'+1']=r(N)
+ local ++line
+ }
+ }
+ }
+}
+*/
+
+local line=1
+forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ forvalues mi=0/`moda`i'' {
+ forvalues mj=0/`moda`j'' {
+ qui count if ``i''==`mi'&``j''==`mj'
+ local table_`line'_`=`nbitems'+1'=r(N)
+ local ++line
+ }
+ }
+ }
+}
+qui drop _all
+set obs `=`line'-1'
+local line=1
+forvalues i=1/`nbitems' {
+ qui gen table`i'=.
+}
+qui gen table`=`nbitems'+1'=.
+*set trace on
+forvalues i=1/`nbitems' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ forvalues mi=0/`moda`i'' {
+ forvalues mj=0/`moda`j'' {
+ qui replace table`i'=`mi' in `line'
+ qui replace table`j'=`mj' in `line'
+ qui replace table`=`nbitems'+1'=`table_`line'_`=`nbitems'+1'' in `line'
+ local ++line
+ }
+ }
+ }
+}
+*qui svmat table
+local ti
+local vi
+forvalues i=1/`nbitems' {
+ rename table`i' ``i''
+}
+rename table`=`nbitems'+1' freq
+local s="0"
+local max=0
+forvalues i=1/`nbitems' {
+ local max=`max'+`moda`i''
+ local bi`i'm0=0
+ local s="`s'+vi`i'mi`moda`i''"
+ forvalues j=`=`i'+1'/`nbitems' {
+ qui gen ti`i'j`j'=``i''+``j''
+ qui replace ti`i'j`j'=0 if ti`i'j`j'==.
+ local ti "`ti' i.ti`i'j`j'"
+ }
+ forvalues mi=1/`moda`i'' {
+ qui gen vi`i'mi`mi'=``i''==`mi'
+ local vi "`vi' vi`i'mi`mi'"
+ }
+}
+local s="(`s')/`max'"
+
+count
+if "`rsm'"=="" {
+ *edit
+ qui xi:poisson freq `vi' `ti', nocons iterate(30)
+ local ll=e(ll)
+ *set trace on
+
+ *lincom -(vi1mi1-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15)
+ *lincom -(vi1mi2-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15-vi1mi1)
+ *lincom -(vi1mi3-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15-vi1mi2)
+ *lincom -.5*(vi1mi1-(vi1mi2+vi2mi2+vi3mi2+vi4mi2+vi5mi2+vi6mi2+vi7mi2)/14)-.5*(vi1mi2-(vi1mi2+vi2mi2+vi3mi2+vi4mi2+vi5mi2+vi6mi2+vi7mi2)/14-vi1mi1)
+
+ qui matrix b=e(b)
+ local col=1
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ local bi`i'm`mi'=b[1,`col']
+ local ++col
+ }
+ }
+ *local s=`s'/`max'
+ *set trace on
+ forvalues i=1/`nbitems' {
+ local location`i'="0"
+ forvalues mi=1/`moda`i'' {
+ local delta`i'm`mi'=-(`bi`i'm`mi''-`mi'*`s'-`bi`i'm`=`mi'-1'')
+ if (`mi'==1) {
+ qui di "-(vi`i'mi`mi'-`s')"
+ local tdelta`i'_1 "-(vi`i'mi`mi'-`s')"
+ qui lincom -(vi`i'mi`mi'-`s')
+ local location`i' "`location`i''-(vi`i'mi`mi'-`s')"
+ }
+ else {
+ /*QUESTION : DOIT-ON MULTIPLIER `s' par `mi'*/
+ qui di " vi`i'mi`=`mi'-1'-vi`i'mi`mi'+`s'"
+ local tdelta`i'_`mi' " vi`i'mi`=`mi'-1'-vi`i'mi`mi'+`s'"
+ qui lincom vi`i'mi`=`mi'-1'-vi`i'mi`mi'+`s'
+ local location`i' "`location`i''+vi`i'mi`=`mi'-1'-vi`i'mi`mi'+`s'"
+ }
+ local delta`i'_`mi'=r(estimate)
+ local sedelta`i'_`mi'=r(se)
+ }
+ qui lincom (`location`i'')/`moda`i''
+ local delta`i'=r(estimate)
+ local sedelta`i'=r(se)
+ }
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ di "delta`i'_`mi' : `delta`i'_`mi'' (`sedelta`i'_`mi'')"
+ }
+ di "delta`i' : `delta`i'' (`sedelta`i'')"
+ }
+}
+else {
+ qui gen vmi2=vi1mi2+vi2mi2+vi3mi2
+ drop vi1mi2 vi2mi2 vi3mi2
+ edit
+ qui xi:poisson freq vi1mi1 vi2mi1 vi3mi1 vmi2 `ti', nocons
+ local ll=e(ll)
+ *set trace on
+
+ *lincom -(vi1mi1-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15)
+ *lincom -(vi1mi2-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15-vi1mi1)
+ *lincom -(vi1mi3-(vi1mi3+vi2mi3+vi3mi3+vi4mi3+vi5mi3)/15-vi1mi2)
+ *lincom -.5*(vi1mi1-(vi1mi2+vi2mi2+vi3mi2+vi4mi2+vi5mi2+vi6mi2+vi7mi2)/14)-.5*(vi1mi2-(vi1mi2+vi2mi2+vi3mi2+vi4mi2+vi5mi2+vi6mi2+vi7mi2)/14-vi1mi1)
+
+ forvalues i=1/`nbitems' {
+ local location`i'="0"
+ forvalues mi=1/`moda`i'' {
+* local delta`i'm`mi'=-(`bi`i'm`mi''-`mi'*`s'-`bi`i'm`=`mi'-1'')
+ if (`mi'==1) {
+ qui di "-(vi`i'mi1-vi2)"
+ local tdelta`i'_1 "-(vi`i'mi1-vi2)"
+ qui lincom -(vi`i'mi1-vi2)
+ local location`i' "`location`i''-(vi`i'mi1)"
+ }
+ else {
+ /*QUESTION : DOIT-ON MULTIPLIER `s' par `mi'*/
+ qui di " vi`i'mi`=`mi'-1'"
+ local tdelta`i'_`mi' " vi`i'mi`=`mi'-1'"
+ qui lincom vi`i'mi`=`mi'-1'
+ local location`i' "`location`i''+vi`i'mi`=`mi'-1'"
+ }
+ local delta`i'_`mi'=r(estimate)
+ local sedelta`i'_`mi'=r(se)
+ }
+ qui lincom (`location`i'')/`moda`i''
+ local delta`i'=r(estimate)
+ local sedelta`i'=r(se)
+ }
+ forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ di "delta`i'_`mi' : `delta`i'_`mi'' (`sedelta`i'_`mi'')"
+ }
+ di "delta`i' : `delta`i'' (`sedelta`i'')"
+ }
+}
+*set trace on
+matrix delta=J(`nbitems',`modamax',.)
+matrix sedelta=J(`nbitems',`modamax',.)
+forvalues i=1/`nbitems' {
+ forvalues mi=1/`moda`i'' {
+ matrix delta[`i',`mi']=`delta`i'_`mi''
+ matrix sedelta[`i',`mi']=`sedelta`i'_`mi''
+ }
+}
+*set trace on
+matrix b=delta
+matrix list delta
+*matrix delta=delta'
+*matrix sedelta=sedelta'
+return matrix b=delta
+return matrix sedelta=sedelta
+return scalar ll=`ll'
+restore
+
+
+
+*set trace on
+matrix list b
+*pcm item*, fixed(b)
+
+
+
+end
diff --git a/Modules/ado/personal/r/raschpower.ado b/Modules/ado/personal/r/raschpower.ado
new file mode 100644
index 0000000..1345c66
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower.ado
@@ -0,0 +1,908 @@
+*! version 5.12 : Novembre 19, 2021
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+* version 5.6 : April 10th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : corrections of bugs
+* version 5.7 : June 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : minor corrections
+* version 5.8 : July 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : correction of a bug when the variances are different in the 2 groups (transversal)
+* version 5.9 : September 26th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : fixed of a bug with the graph option (correlation could be greater than one)
+* version 5.10 : July 18th, 2019 (Jean-Benoit Hardouin) : filesave and dirsave options
+* version 5.11 : July 24th, 2019 (Jean-Benoit Hardouin) : pcm->pcmold
+* version 5.12 : July 24th, 2019 (Myriam Blanchin) : correction of bug (essai.dta)
+
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* Bastien Perrot, Bastien.perrot@univ-nantes.fr
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org - anaqol@sphere-nantes.fr
+*
+* Copyright 2010-2014, 2019 Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+*
+* 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1) min(real 0.25) step(real 1) max(real 9) FILESave DIRSave(string) pro]
+version 11
+
+if "`pro'"!="" {
+ di "START"
+}
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*
+if "`max'" == "" {
+ local max = 9 + `step'/2
+}
+else {
+ local max = `max' + `step'/2
+}*/
+
+forval v = `min'(`step')`max' {
+ local w = `v'
+}
+if `w' < `max' {
+ local max = `max' + `step'
+}
+if "`longitudinal'"!="" & `gvar'!=-1 {
+ local max = min(`max',0.99999) /* pour avoir des corrélations < 1 */
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'*`gamma'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ *qui save d:\tmp,replace
+ bysort group:su lt
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local tmpprob=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ *di "`dixj'% (`tmpprob')" _c
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ *prout
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else { /*if "`method'"!="GH"*/
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local sum=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'% (`sum')" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ qui gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ qui gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+/*
+if "`html'" == "" {
+ qui save "d:\essai.dta", replace
+}*/
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ *noi pcm item*, `fi' covariates(groupc)
+
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ *di "jk pcm item*, `fi' covariates(groupc) `fv'"
+ /********************************ESSAI 23 mai 2014*/
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`n1')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`n0')
+ qui gen group=0
+ qui append using `save1'
+ qui gen groupc=group-0.5
+ *di "ON A SIMULE"
+ **********************************FIN ESSAI 23 mai 2014*/
+
+ qui pcmold item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{ /*LONGITUDINAL*/
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local nbw:word count `var'
+ if `nbw' == 2 { /* variance commune */
+ local varc = ((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+ }
+ else {
+ local varc = `var'
+ }
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`varc'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`varc'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _c
+ if "`detail'"!="" {
+ di _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ local x = "`min'(`step')`max'"
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ forval var = `x' {
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ forval var = `x' {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = `x' {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step''))
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower.hlp b/Modules/ado/personal/r/raschpower.hlp
new file mode 100644
index 0000000..b15f494
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower.hlp
@@ -0,0 +1,78 @@
+{smcl}
+{* 6february2012}{...}
+{hline}
+help for {hi:raschpower}{right:Jean-Benoit Hardouin, Myriam Blanchin}
+{hline}
+
+{title:Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals}
+
+{p 8 14 2}{cmd:raschpower} [{cmd:,} {cmdab:n0}({it:#}) {cmdab:n1}({it:#})
+{cmdab:gamma}({it:#}) {cmdab:var}({it:# [#]}) {cmdab:d:ifficulties}({it:matrix}) {cmdab:m:ethod}({it:method}) {cmdab:det:ail} {cmdab:exp:ectedpower}({it:#})]
+
+
+{title:Description}
+
+{p 4 8 2}{cmd:raschpower} allows estimating the power of the Wald test comparing the means of two groups of patients in the context of the Rasch model or the partial-credit model. The estimation is based
+ on the estimation of the variance of the difference of the means based on the Cramer-Rao bound.
+
+{title:Options}
+
+{p 4 8 2}{cmd:n0} and {cmd:n1} indicates the numbers of individuals in the two groups [100 by default].
+
+{p 4 8 2}{cmd:gamma} indicates the group effect (difference between the two means) [0.5 by default].
+
+{p 4 8 2}{cmd:var} is the expected values of the variances of the latent trait (1 by default): if this option contains only one value, variances are considered as equal between the two groups; if this option contains two values, variances are considered as unequal between the two groups.
+
+{p 4 8 2}{cmdab:d:ifficulties} is a matrix containing the item parameters [one row per item, one column per positive modality - (-1.151, -0.987\-0.615, -0.325\-0.184, -0.043\0.246, 0.554\0.782, 1.724) by default].
+
+{p 4 8 2}{cmd:method}({it:method}) indicates the method for constructing data. ({it:method}) may be GH, MEAN, MEAN+GH or POPULATION+GH [default is method(GH) if number of patterns<500, method(MEAN+GH) if 500<=number of patterns<10000,
+method(MEAN) if 10000<=number of patterns<1000000, method(POPULATION+GH) otherwise].
+
+{p 8 14 2} {bf:GH}: The probability of all possible response patterns is estimated by Gauss-Hermite quadratures.
+
+{p 8 14 2} {bf:MEAN}: The mean of the latent trait for each group is used instead of Gauss-Hermite quadratures.
+
+{p 8 14 2} {bf:MEAN+GH}: In a first step, the MEAN method is used to determine the most probable patterns. In a second step, the probability of response patterns is estimated by Gauss-Hermite quadratures on the most probable patterns.
+
+{p 8 14 2} {bf:POPULATION+GH}: The most frequent response patterns are selected from a simulated population of 1,000,000 of individuals. The probability of the selected response patterns is estimated by Gauss-Hermite quadratures.
+
+{p 4 8 2}{cmd:detail} allows a comparison with the classical formula (for manifest variable).
+
+{p 4 8 2}{cmd:expectedpower} allows searching for a sample size in order to reach a fixed level of power (the obtained sample sizes take into account the ratio between $n0$ and $n1$).
+
+
+{title:Example}
+
+ {p 4 8 2}{cmd:. raschpower}
+
+ {p 4 8 2}{cmd:. raschpower, n0(200) n1(200) gamma(0.4) var(1.3)}
+
+ {p 4 8 2}{cmd:. matrix diff=(-1.47\-0.97\-.23\-0.12\0.02\0.1)}{p_end}
+ {p 4 8 2}{cmd:. raschpower, n0(127) n1(134) gamma(0.23) d(diff) var(2.58)}{p_end}
+
+ {p 4 8 2}{cmd:. matrix diff=(-0.328,-0.811,0.329\ 0.556,0.818,1.409\ 1.394,1.049,1.288\ 0.560,0.363,0.950)}{p_end}
+ {p 4 8 2}{cmd:. raschpower, d(diff) n0(167) n1(205) gamma(0.178) var(0.77) exp(0.8)}{p_end}
+
+
+{title:References}
+
+ {p 4 8 2}Hardouin J.B., Amri S., Feddag M., Sébille V. (2012) Towards Power And Sample Size Calculations For The Comparison Of Two Groups Of Patients With Item Response Theory Models. Statistics in Medicine, 31(11): 1277-1290.{p_end}
+ {p 4 8 2}Blanchin M., Hardouin J.B., Guillemin F., Falissard B., Sébille V. (2013) Power and sample size determination for the group comparison of patient-reported outcomes with Rasch family models. PLoS ONE, 8(2): e57279.{p_end}
+ {p 4 8 2}Feddag M.L., Blanchin M., Hardouin J.B., Sébille V. (2014) Power analysis on the time effect for the longitudinal Rasch model. Journal of Applied Measurement: (under press).{p_end}
+ {p 4 8 2}Guilleux A., Blanchin M., Hardouin J.B., Sébille V. (2014) Power and sample size determination in the Rasch model: Evaluation of the robustness of a numerical method to non-normality of the latent trait. Plos One, 9(1): e0083652.{p_end}
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}Myriam Blanchin, PhD, research assistant{p_end}
+{p 4 8 2}Bastien Perrot, biostatistician{p_end}
+{p 4 8 2}EA4275 "Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Emails:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 13 8 2}{browse "mailto:myriam.blanchin@univ-nantes.fr":myriam.blanchin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
diff --git a/Modules/ado/personal/r/raschpower33.ado b/Modules/ado/personal/r/raschpower33.ado
new file mode 100644
index 0000000..f83a15d
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower33.ado
@@ -0,0 +1,371 @@
+*! version 3.3 : October 2nd, 2012
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 3.3 : October 2nd, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2012 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(real 1) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1)]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d
+if "`difficulties'"=="" {
+ matrix `d'=[-1.151, -0.987\-0.615, -0.325\-0.184, -0.043\0.246, 0.554\0.782, 1.724]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`=`nbmodat'^`nbitems'*2' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if "`method'"=="" {
+ if `nbmodat'^`nbitems'*2<1000 {
+ local method GH
+ }
+ else if `nbmodat'^`nbitems'<10000 {
+ local method MEAN+GH
+ }
+ else if `nbmodat'^`nbitems'<1000000 {
+ local method MEAN
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+
+
+di in gr "Method: " in ye "`method'"
+di in gr "Number of individuals in the first group: " in ye `n0'
+di in gr "Number of individuals in the second group: " in ye `n1'
+di in green "Group effect: " in ye `gamma'
+di in gr "Variance of the latent trait: " in ye `var'
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+di in gr "Number of studied response's patterns: " in ye `=`nbmodat'^`nbitems'*2'
+
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ else {
+ qui simirt, clear pcm(`difficulties') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ qui keep if keep==1
+ qui count
+ local tmp=r(N)
+ di "Number of kept patterns:`tmp'"
+ local method GH
+ }
+ qui gen mean=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean=`n0'*`gamma'/(`n0'+`n1') if group==1
+
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ local int=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`d'[`j',1]
+ local sum "1+exp(x-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`j',`m']
+ local sum "`sum'+exp(`m'*x-`diff`m'')"
+ }
+ local int "(`int'*exp(`rep'*x-`diff`rep''))/(`sum')"
+ }
+ qui su mean in `i'
+ local mean=r(mean)
+ qui gausshermite `int',mu(`mean') sigma(`=sqrt(`var')') display
+ qui replace proba=r(int) in `i'
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues i=1/`nbitems' {
+ local diff0=0
+ local diff1=`d'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ local int=1
+ forvalues j=1/`nbitems' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`d'[`j',1]
+ local sum "1+exp(x-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`d'[`j',`m']
+ local sum "`sum'+exp(`m'*x-`diff`m'')"
+ }
+ local int "(`int'*exp(`rep'*x-`diff`rep''))/(`sum')"
+ }
+ qui su mean in `i'
+ local mean=r(mean)
+ qui gausshermite `int',mu(`mean') sigma(`=sqrt(`var')') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ qui gen eff=.
+ forvalues i=0/1 {
+ qui replace eff=proba*`n`i'' if group==`i'
+ }
+ qui replace eff=proba
+ qui keep item* eff group proba
+
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui gen eff2=.
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+qui gen groupc=group-.5
+if `nbmodat'==2 {
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ }
+
+ constraint 1 _cons=`=ln(`var')'
+ qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ tempname b V
+}
+else {
+ matrix `db'=`db''
+ *di "qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var')"
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var')
+
+}
+
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+
+
+ di
+ di
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local poweruni=1-normal(1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+ di in gr "{hline 91}"
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower4.ado b/Modules/ado/personal/r/raschpower4.ado
new file mode 100644
index 0000000..cdaa892
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower4.ado
@@ -0,0 +1,676 @@
+*! version 4 : January 30th, 2013
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2013 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar HTML(string)]
+version 11
+
+if "`html'" != "" {
+ di ""
+}
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+if "`longitudinal'"!="" & `nbmodat'>2{
+ di in red "{p}The {hi:longitudinal} option is not available with polytomous items{p_end}"
+ error 198
+ exit
+}
+if "`longitudinal'"==""{
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var=`var'
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ local var=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ matrix `dlong'=`d'
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+
+ if `=abs(`sumd')'>=`=2*sqrt(`var')'{
+ if "`html'" == ""{
+ di "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ else {
+ di "WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait.
"
+ }
+ }
+
+}
+else{
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix matvar=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if !_rc & colsof(`matvar')==2 & rowsof(`matvar')==2 & issymmetric(`matvar'){
+ matrix matvar=`matvar'
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a symmetric 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+if "`html'" == "" {
+ di in gr "Method: " in ye "`method'"
+
+ if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait: " in ye `var'
+ }
+ else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list matvar
+ }
+ di in gr "Number of items: " in ye `nbitems'
+ di in green "Difficulties parameters of the items: "
+}
+else {
+ di "Method: " in ye "`method'" "
"
+
+ if "`longitudinal'"==""{
+ di "Number of individuals in the first group: " in ye `n0' "
"
+ di "Number of individuals in the second group: " in ye `n1' "
"
+ di "Group effect: " in ye `gamma' "
"
+ di "Variance of the latent trait: " in ye `var' "
"
+ }
+ else{
+ di "Number of individuals at each time: " in ye `n0' "
"
+ di "Time effect: " in ye `gamma' "
"
+/*@TODO
+* di in gr "Variance matrix of the latent trait: " "
"
+* matrix list matvar
+*/
+ }
+ di "Number of items: " in ye `nbitems' "
"
+}
+
+tempname dd
+matrix `dd'=`d'
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`modalities'
+matrix rownames `dd'=`items'
+if "`html'" == "" {
+ matrix list `dd',noblank nohalf noheader
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+else {
+ //di in gr "Number of studied response's patterns: " in ye `nbpatmax' "
"
+}
+
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else {
+ if "`longitudinal'"==""{
+ qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`html'" == "" {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ }
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`var')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(matvar) display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`var')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) sigma(matvar) display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 {
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ }
+
+ constraint 1 _cons=`=ln(`var')'
+ qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ tempname b V
+ }
+ else {
+ matrix `db'=`db''
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var')
+
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+}
+else{
+ forvalues i=1/`nbitems'{
+ rename item`i' t1item`i'
+ }
+ forvalues i=`=`nbitems'+1'/`nbtotitems'{
+ rename item`i' t2item`=`i'-`nbitems''
+ }
+ qui gen i=_n
+ local list=""
+ forvalues i=1/`nbitems'{
+ local list="`list' t@item`i'"
+ }
+ qui reshape long `list', i(i) j(temps)
+ qui reshape long titem, i(i temps) j(item)
+ qui drop if titem==.
+
+ qui gen offset=0
+ local itemnb=1
+ forvalues t=1/`nbt'{
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`dlong'[`itemnb',1] if item==`i' & temps==`t'
+ local ++itemnb
+ }
+ }
+ gen t1=temps==1
+ gen t2=temps==2
+
+ matrix C=cholesky(matvar)
+ constraint define 1 [i1_1]t1=`=C[1,1]'
+ constraint define 2 [i1_2]t2=`=C[2,2]'
+ constraint define 3 [i1_2_1]_cons=`=C[2,1]'
+
+ eq b1:t1
+ eq b2:t2
+ qui gllamm titem t2,i(i) link(logit) nocons fam(bin) nrf(2) eq(b1 b2) constraints(1 2 3) iterate(20) trace offset(offset)
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+else {
+ di ""
+ di ""
+ di " | Estimation with the |
"
+ di " | Cramer-Rao bound | classical formula |
"
+}
+
+ if "`longitudinal'"==""{
+ if "`gammafixed'"=="" {
+ if "`html'" == "" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ else {
+ di "Estimated value of the group effect | " in ye %7.2f `gammaest' " |
"
+ }
+ }
+ if "`html'" == "" {
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ }
+ else {
+ di "Estimation of the s.e. of the group effect | " in ye %7.2f `se' " |
"
+ di "Estimation of the variance of the group effect | " in ye %10.4f `=`se'^2' " |
"
+ }
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ }
+ else{
+ if "`gammafixed'"=="" {
+ if "`html'" == "" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ else {
+ di "Estimated value of the time effect | " in ye %7.2f `gammaest' " |
"
+ }
+ }
+ if "`html'" == "" {
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ }
+ else {
+ di "Estimation of the s.e. of the time effect | " in ye %7.2f `se' " |
"
+ di "Estimation of the variance of the time effect | " in ye %10.4f `=`se'^2' " |
"
+ }
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=matvar[1,1]'-`=matvar[2,1]'))-1.96)
+ local clnsn=2*(`=matvar[1,1]'-`=matvar[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ }
+ if "`html'" == "" {
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ }
+ else {
+ di "Estimation of the power | " in ye %6.4f `poweruni' " | " in ye %6.4f `clpower' " |
"
+ di "Number of patients for a power of" %6.2f `=`poweruni'*100' "% | " in ye `n0' "/" `n1' " | " in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0'' " |
"
+ }
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`html'" == "" {
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ }
+ else {
+ di "Ratio of the number of patients | " in ye %6.2f `ratio' " |
"
+ }
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+ if "`html'" == "" {
+ di in gr "{hline 91}"
+ }
+ else {
+ di " | |
"
+ }
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower5.ado b/Modules/ado/personal/r/raschpower5.ado
new file mode 100644
index 0000000..1496037
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower5.ado
@@ -0,0 +1,582 @@
+*! version 5 : October 22th, 2013
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2013 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower5,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar DETail]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var=`var'
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ local var=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ matrix `dlong'=`d'
+
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`var')'{
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+
+}
+else{
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait: " in ye `var'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+if "`detail'"!=""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else {
+ if "`longitudinal'"==""{
+ qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`var')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`var')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 {
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ }
+
+ constraint 1 _cons=`=ln(`var')'
+ qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ tempname b V
+ }
+ else {
+ matrix `db'=`db''
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var')
+
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+
+ di
+ di
+ if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+ }
+
+ if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+ else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+ /* ceci est un commentaire */
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower51.ado b/Modules/ado/personal/r/raschpower51.ado
new file mode 100644
index 0000000..9e70e7a
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower51.ado
@@ -0,0 +1,651 @@
+*! version 5.1 : January 21th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower51,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar DETail]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+if "`detail'"!=""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mean(`=`n0'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mean(`=-`n1'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append usinf `save1'
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 {
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ }
+ if `var0'==`var1' {
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ constraint 1 _cons=`=sqrt(`var0')'
+ qui gllamm rep groupc ,nocons i(i) offset(offset) constraint(1) fam(bin) link(logit) nrf(1) trace
+ }
+ else {
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ qui gllamm rep groupc ,nocons i(i) offset(offset) constraint(1 2 3) fam(bin) link(logit) eqs(B0 B1) nrf(2) trace
+ }
+ tempname b V
+ }
+ else {
+ matrix `db'=`db''
+ if `var0'==`var1' {
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvar(`var0')
+ }
+ else {
+ qui pcm item*, fixed(`db') covariates(groupc) fixedmu fixedvargroupc(`var')
+ }
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+
+ di
+ di
+ if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+ }
+
+ if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+ else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower511.ado b/Modules/ado/personal/r/raschpower511.ado
new file mode 100644
index 0000000..9be0f0a
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower511.ado
@@ -0,0 +1,907 @@
+*! version 5.11 : July 24, 2019
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+* version 5.6 : April 10th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : corrections of bugs
+* version 5.7 : June 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : minor corrections
+* version 5.8 : July 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : correction of a bug when the variances are different in the 2 groups (transversal)
+* version 5.9 : September 26th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : fixed of a bug with the graph option (correlation could be greater than one)
+* version 5.10 : July 18th, 2019 (Jean-Benoit Hardouin) : filesave and dirsave options
+* version 5.10 : July 24th, 2019 (Jean-Benoit Hardouin) : pcm->pcmold
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* Bastien Perrot, Bastien.perrot@univ-nantes.fr
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org - anaqol@sphere-nantes.fr
+*
+* Copyright 2010-2014, 2019 Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+*
+* 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 raschpower,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1) min(real 0.25) step(real 1) max(real 9) FILESave DIRSave(string) pro]
+version 11
+
+if "`pro'"!="" {
+ di "START"
+}
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*
+if "`max'" == "" {
+ local max = 9 + `step'/2
+}
+else {
+ local max = `max' + `step'/2
+}*/
+
+forval v = `min'(`step')`max' {
+ local w = `v'
+}
+if `w' < `max' {
+ local max = `max' + `step'
+}
+if "`longitudinal'"!="" & `gvar'!=-1 {
+ local max = min(`max',0.99999) /* pour avoir des corrélations < 1 */
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'*`gamma'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ *qui save d:\tmp,replace
+ bysort group:su lt
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local tmpprob=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ *di "`dixj'% (`tmpprob')" _c
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ *prout
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else { /*if "`method'"!="GH"*/
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local sum=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'% (`sum')" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ qui gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ qui gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+if "`html'" == "" {
+ qui save "d:\essai.dta", replace
+}
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ *noi pcm item*, `fi' covariates(groupc)
+
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ *di "jk pcm item*, `fi' covariates(groupc) `fv'"
+ /********************************ESSAI 23 mai 2014*/
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`n1')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`n0')
+ qui gen group=0
+ qui append using `save1'
+ qui gen groupc=group-0.5
+ *di "ON A SIMULE"
+ **********************************FIN ESSAI 23 mai 2014*/
+
+ qui pcmold item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{ /*LONGITUDINAL*/
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local nbw:word count `var'
+ if `nbw' == 2 { /* variance commune */
+ local varc = ((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+ }
+ else {
+ local varc = `var'
+ }
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`varc'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`varc'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _c
+ if "`detail'"!="" {
+ di _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ local x = "`min'(`step')`max'"
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ forval var = `x' {
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ forval var = `x' {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = `x' {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ if "`filesave'"!="" {
+ qui local saving "saving(`dirsave'//planif,replace) nodraw"
+ }
+ else {
+ qui local saving
+ }
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step''))
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower52.ado b/Modules/ado/personal/r/raschpower52.ado
new file mode 100644
index 0000000..909ffae
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower52.ado
@@ -0,0 +1,692 @@
+*! version 5.2 : January 22th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower52,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }on
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+if "`detail'"!=""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mean(`=`n0'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mean(`=-`n1'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append usinf `save1'
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace
+ }
+ tempname b V/*LONGITUDINAL*/
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ *di "pcm item*, `fi' covariates(groupc) `fv'"
+ qui pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+
+ di
+ di
+ if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+ }
+
+ if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+ else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower53.ado b/Modules/ado/personal/r/raschpower53.ado
new file mode 100644
index 0000000..d1e81f2
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower53.ado
@@ -0,0 +1,695 @@
+*! version 5.3 : January 29th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower53,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail]
+version 11
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+matrix list `dd',noblank nohalf noheader
+if "`detail'"!=""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ di "pcm item*, `fi' covariates(groupc) `fv'"
+ noi pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+
+ di
+ di
+ if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+ }
+
+ if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+ else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+ }
+
+ if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+
+ return scalar EstGamma=`gammaest'
+ return scalar CRbound=`=`se'^2'
+ return scalar CRPower=`poweruni'
+ return scalar ClPower=`clpower'
+ return scalar ClSS=`clnsn'
+ return scalar Ratio=`ratio'
+ return scalar CronbachAlpha=`alpha'
+
+
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower54.ado b/Modules/ado/personal/r/raschpower54.ado
new file mode 100644
index 0000000..df91b8d
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower54.ado
@@ -0,0 +1,820 @@
+*! version 5.4 : March 28th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2th, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower54,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1)]
+version 11
+
+if "`html'" != "" {
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ *di "pcm item*, `fi' covariates(groupc) `fv'"
+ noi pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ qui raschpower54, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower54, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = 0.1(0.1)0.9 {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower54, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.4 0.7 0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.1[0.1]0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower55.ado b/Modules/ado/personal/r/raschpower55.ado
new file mode 100644
index 0000000..7494f92
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower55.ado
@@ -0,0 +1,822 @@
+*! version 5.5 : April 9th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : inequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower55,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1)]
+version 11
+
+if "`html'" != "" {
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else {
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ *di "pcm item*, `fi' covariates(groupc) `fv'"
+ noi pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = 0.1(0.1)0.9 {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.1[0.1]0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.1[0.1]0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower56.ado b/Modules/ado/personal/r/raschpower56.ado
new file mode 100644
index 0000000..adae592
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower56.ado
@@ -0,0 +1,852 @@
+*! version 5.7 : June 21th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+* version 5.6 : April 10th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : corrections of bugs
+* version 5.7 : June 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : minor corrections
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchi n, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower56,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1)]
+version 11
+
+if "`html'" != "" {
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'*`gamma'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ *qui save d:\tmp,replace
+ bysort group:su lt
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local tmpprob=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ *di "`dixj'% (`tmpprob')" _c
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ *prout
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else { /*if "`method'"!="GH"*/
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local sum=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'% (`sum')" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ qui gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ qui gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+qui save "d:\essai.dta", replace
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ *noi pcm item*, `fi' covariates(groupc)
+
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ *di "jk pcm item*, `fi' covariates(groupc) `fv'"
+ /********************************ESSAI 23 mai 2014*/
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`n1')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`n0')
+ qui gen group=0
+ qui append using `save1'
+ qui gen groupc=group-0.5
+ *di "ON A SIMULE"
+ **********************************FIN ESSAI 23 mai 2014*/
+
+ qui pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{ /*LONGITUDINAL*/
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`var'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`var'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _c
+ if "`detail'"!="" {
+ di _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ foreach var in 0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9 {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(0.25 0.5 0.75 1 1.5 2 2.5 3 3.5 4 5 6 7 8 9) xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = 0.1(0.1)0.9 {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower55, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.1[0.1]0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(0.1[0.1]0.9) xtitle(Correlation) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower58.ado b/Modules/ado/personal/r/raschpower58.ado
new file mode 100644
index 0000000..15827a5
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower58.ado
@@ -0,0 +1,878 @@
+*! version 5.8 : July 9th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+* version 5.6 : April 10th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : corrections of bugs
+* version 5.7 : June 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : minor corrections
+* version 5.8 : July 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : correction of a bug when the variances are different in the 2 groups (transversal)
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchi n, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower58,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1) min(real 0.25) step(real 1) max(real 9)]
+version 11
+
+if "`html'" != "" {
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*
+if "`max'" == "" {
+ local max = 9 + `step'/2
+}
+else {
+ local max = `max' + `step'/2
+}*/
+
+forval v = `min'(`step')`max' {
+ local w = `v'
+}
+if `w' < `max' {
+ local max = `max' + `step'
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'*`gamma'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ *qui save d:\tmp,replace
+ bysort group:su lt
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local tmpprob=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ *di "`dixj'% (`tmpprob')" _c
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ *prout
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else { /*if "`method'"!="GH"*/
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local sum=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'% (`sum')" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ qui gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ qui gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+if "`html'" == "" {
+ qui save "d:\essai.dta", replace
+}
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ *noi pcm item*, `fi' covariates(groupc)
+
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ *di "jk pcm item*, `fi' covariates(groupc) `fv'"
+ /********************************ESSAI 23 mai 2014*/
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`n1')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`n0')
+ qui gen group=0
+ qui append using `save1'
+ qui gen groupc=group-0.5
+ *di "ON A SIMULE"
+ **********************************FIN ESSAI 23 mai 2014*/
+
+ qui pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{ /*LONGITUDINAL*/
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local nbw:word count `var'
+ if `nbw' == 2 { /* variance commune */
+ local varc = ((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+ }
+ else {
+ local varc = `var'
+ }
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`varc'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`varc'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _c
+ if "`detail'"!="" {
+ di _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ local x = "`min'(`step')`max'"
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ forval var = `x' {
+ qui raschpower58, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ forval var = `x' {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower58, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = `x' {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower58, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation) ytitle(Power) name(planif_graph,replace)
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschpower59.ado b/Modules/ado/personal/r/raschpower59.ado
new file mode 100644
index 0000000..12f3469
--- /dev/null
+++ b/Modules/ado/personal/r/raschpower59.ado
@@ -0,0 +1,884 @@
+*! version 5.9 : September 26th, 2014
+*! Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot
+************************************************************************************************************
+* raschpower: Estimation of the power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+*
+* Version 1 : January 25th, 2010 (Jean-Benoit Hardouin)
+* Version 1.1 : January 26th, 2010 (Jean-Benoit Hardouin)
+* Version 1.2 : November 1st, 2010 (Jean-Benoit Hardouin)
+* version 1.3 : May 2nd, 2011 (Jean-Benoit Hardouin)
+* version 1.4 : July 7th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 1.5 : July 11th, 2011 (Jean-Benoit Hardouin) : minor corrections
+* version 2 : August 30th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : corrections
+* version 3 : October 18th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to the PCM, -method- option, -nbpatterns- options, changes in the presentation of the results
+* version 3.1 : October 25th, 2011 (Jean-Benoit Hardouin, Myriam Blanchin) : POPULATION+GH method
+* version 3.2 : February 6th, 2012 (Jean-Benoit Hardouin, Myriam Blanchin) : minor corrections
+* version 4 : January 30th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design
+* version 4.1 : June 3rd, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : detail option
+* version 5 : October 22th, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) : Extension to longitudinal design with polytomous items
+* version 5.1 : January 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.2 : January 22th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : unequal variance between groups
+* version 5.3 : January 29th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin) : correction of a bug
+* version 5.4 : April 4th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : HTML option, graph option, minor corrections for results display
+* version 5.5 : April 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : graph option for longitudinal design
+* version 5.6 : April 10th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : corrections of bugs
+* version 5.7 : June 21th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : minor corrections
+* version 5.8 : July 9th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : correction of a bug when the variances are different in the 2 groups (transversal)
+* version 5.9 : September 26th, 2014 (Jean-Benoit Hardouin, Myriam Blanchin, Bastien Perrot) : fixed of a bug with the graph option (correlation could be greater than one)
+*
+* Jean-benoit Hardouin, jean-benoit.hardouin@univ-nantes.fr
+* Myriam Blanchin, myriam.blanchin@univ-nantes.fr
+* EA 4275 "Biostatistics, Pharmacoepidemiology and Subjectives Measures in Health"
+* Faculty of Pharmaceutical Sciences - University of Nantes - France
+* http://www.sphere-nantes.org
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2010-2014 Jean-Benoit Hardouin, Myriam Blanchin
+*
+* 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 raschpower59,rclass
+syntax [varlist] [, n0(int 100) n1(int 100) Gamma(real .5) Difficulties(string) Var(string) Method(string) NBPatterns(int 2) nodata EXPectedpower(real -1) LONGitudinal freevar freeitems DETail HTML(string) graph gvar(real -1) gcorr(real -1) min(real 0.25) step(real 1) max(real 9)]
+version 11
+
+if "`html'" != "" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ di ""
+ di ""
+}
+
+tempfile raschpowerfile
+capture qui save "`raschpowerfile'",replace
+tempname db d dlong matvar
+
+/*******************************************************************************
+DEFINITION DES PARAMETRES
+*******************************************************************************/
+
+if "`graph'" != "" & "`longitudinal'" != "" {
+ if `gvar' != -1 & `gcorr' != -1 {
+ di in red "You cannot use both {hi:gvar} and {hi:gcorr}"
+ error 198
+ }
+ if `gvar' == -1 & `gcorr' == -1 {
+ di in red "You must precise values for {hi:gvar} or {hi:gcorr} if you use the {hi:graph} option"
+ error 198
+ }
+}
+
+if "`difficulties'"=="" {
+ matrix `d'=[-1\-0.5\0\0.5\1]
+}
+else {
+ matrix `d'=`difficulties'
+}
+local nbitems=rowsof(`d')
+local nbmodat=colsof(`d')+1
+
+if "`longitudinal'"==""{ /*CAS TRANSVERSAL*/
+ local nbt=1
+ local nbtotitems=`nbitems'
+ local nbpatmax=2*`nbmodat'^`nbitems'
+ if "`var'"==""{
+ local var=1
+ local var0=1
+ local var1=1
+ }
+ else{
+ capture confirm number `var'
+ if !_rc {
+ local var0=`var'
+ local var1=`var'
+ }
+ else{
+ local nbw:word count `var'
+ local grp=1
+ if `nbw'==2 {
+ local t1: word 1 of `var'
+ capture confirm number `t1'
+ if !_rc {
+ local t2: word 2 of `var'
+ capture confirm number `t2'
+ if !_rc {
+ local var0=`t1'
+ local var1=`t2'
+ local grp=2
+ }
+ }
+ }
+ if `nbw'!=2|`grp'==1 {
+ capture confirm matrix `var'
+ if !_rc & colsof(`matvar')==1 & rowsof(`matvar')==1{
+ matrix `matvar'=`var'
+ local var0=`matvar'[1,1]
+ local var1=`matvar'[1,1]
+ }
+ else{
+ di in red "{p}The {hi:var} option should contain a number or a 1x1 matrix for transversal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ }
+ }
+ matrix `dlong'=`d' /*DEMANDER A MYRIAM A QUOI CA SERT CAR ON EST EN TRANSVERSAL*/
+ local varc=((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+
+ local sumd=0
+ forvalues numit=1/`nbitems'{
+ local sumd=`sumd'+`d'[`numit',1]
+ }
+ local sumd=`sumd'/`nbitems'
+ if `=abs(`sumd')'>=`=2*sqrt(`varc')'{
+ if "`html'" == "" {
+ di in red "{p}WARNING: It is not recommended to use Raschpower when the gap between the global mean of the latent trait (fixed to 0) and the mean of the item parameters is greater than or equal to 2 standard deviation of the latent trait. {p_end}"
+ }
+ }
+
+}
+else{ /*CAS LONGITUDINAL*/
+ local nbt=2
+ local nbtotitems=2*`nbitems'
+ local nbpatmax=`nbmodat'^(`nbitems'*2)
+ local n1=0
+ local mean1=0
+ local mean2=`mean1'+`gamma'
+ if "`var'"==""{
+ matrix `matvar'=(1,0\0,1)
+ }
+ else{
+ matrix `matvar'=`var'
+ capture confirm matrix `matvar'
+ if _rc | colsof(`matvar')!=2 | rowsof(`matvar')!=2{
+ di in red "{p}The {hi:var} option should contain a 2x2 matrix for longitudinal studies{p_end}"
+ error 198
+ exit
+ }
+ }
+ matrix `dlong'=J(`nbtotitems',`=`nbmodat'-1',.)
+ matrix `dlong'[1,1]=`d'
+ matrix `dlong'[`=`nbitems'+1',1]=`d'
+}
+
+/*
+if "`max'" == "" {
+ local max = 9 + `step'/2
+}
+else {
+ local max = `max' + `step'/2
+}*/
+
+forval v = `min'(`step')`max' {
+ local w = `v'
+}
+if `w' < `max' {
+ local max = `max' + `step'
+}
+if "`longitudinal'"!="" & `gvar'!=-1 {
+ local max = min(`max',0.99999) /* pour avoir des corrélations < 1 */
+}
+
+/*******************************************************************************
+DEFINITION DE LA METHODE
+*******************************************************************************/
+
+if substr("`method'",1,3)=="pop" | substr("`method'",1,3)=="POP"{
+ local method POPULATION+GH
+}
+
+if "`method'"=="MEAN+GH"&`nbpatterns'*(`n1'+`n0')>=`nbpatmax' {
+ di in gr "The MEAN+GH will be inefficient compared to GH since the maximal number of pattern's responses"
+ di in gr "is lesser than the number of pattern retained by the MEAN+GH method."
+ di in gr "The -method- option is replaced by GH."
+ local method GH
+}
+else if ("`method'"=="MEAN+GH" | "`method'"=="MEAN") & `nbpatmax'>1000000{
+ di in red "The number of patterns is too high for the chosen method"
+ exit
+}
+else if "`method'"=="" {
+ if `nbpatmax'<2000 {
+ local method GH
+ }
+ else {
+ local method POPULATION+GH
+ }
+}
+
+if "`method'"!="MEAN+GH" & "`method'"!="MEAN" & "`method'"!="GH" & "`method'"!="POPULATION+GH"{
+ di in red "Invalid method name"
+ exit
+}
+
+/*******************************************************************************
+AFFICHAGE DES PARAMETRES
+*******************************************************************************/
+
+if "`longitudinal'"==""{
+ di in gr "Number of individuals in the first group: " in ye `n0'
+ di in gr "Number of individuals in the second group: " in ye `n1'
+ di in green "Group effect: " in ye `gamma'
+ di in gr "Variance of the latent trait in the first group: " in ye `var0'
+ di in gr "Variance of the latent trait in the second group: " in ye `var1'
+}
+else{
+ di in gr "Number of individuals at each time: " in ye `n0'
+ di in green "Time effect: " in ye `gamma'
+ di in gr "Variance matrix of the latent trait: "
+ matrix list `matvar',noheader
+ di
+}
+di in gr "Number of items: " in ye `nbitems'
+di in green "Difficulties parameters of the items: "
+tempname dd
+matrix `dd'=`d''
+local items
+forvalues i=1/`nbitems' {
+ local items "`items' item`i'"
+}
+local modalities
+forvalues i=1/`=`nbmodat'-1' {
+ local modalities "`modalities' delta_`i'"
+}
+
+matrix colnames `dd'=`items'
+matrix rownames `dd'=`modalities'
+
+
+di
+tempname ddt
+matrix `ddt' = `dd''
+matrix colnames `ddt'=`modalities'
+matrix rownames `ddt'=`items'
+if "`html'" != "" {
+ matrix list `ddt',noblank nohalf noheader /* affiche la matrice des difficultés dans l'autre sens */
+}
+else {
+ matrix list `dd',noblank nohalf noheader
+}
+di
+
+if "`detail'"!="" & "`html'" == ""{
+ di in gr "Method: " in ye "`method'"
+ di in gr "Number of studied response's patterns: " in ye `nbpatmax'
+}
+matrix `dd'=`d'
+local gamma=`gamma'
+
+local tmp=1
+qui matrix `db'=J(`=`nbitems'*(`nbmodat'-1)',1,.)
+forvalues j=1/`nbitems' {
+ forvalues m=1/`=`nbmodat'-1' {
+ qui matrix `db'[`tmp',1]=`d'[`j',`m']
+ local ++tmp
+ }
+}
+
+
+/*******************************************************************************
+CREATION DU DATASET ATTENDU
+*******************************************************************************/
+
+if "`data'"=="" {
+ clear
+ if "`method'"!="POPULATION+GH"{
+ local temp=`nbmodat'^(`nbtotitems')
+ qui range x 0 `=`temp'-1' `temp'
+ qui g t=x
+ loc i=`nbtotitems'
+ qui count if t>0
+ loc z=r(N)
+ qui while `z'>0 {
+ qui gen item`=`nbtotitems'-`i'+1'=floor(t/`nbmodat'^`=`i'-1')
+ qui replace t=mod(t,`nbmodat'^`=`i'-1')
+ qui count if t>0
+ loc z=r(N)
+ loc i=`i'-1
+ }
+ drop t
+ if "`longitudinal'"==""{
+ qui expand 2
+ qui gen group=0 in 1/`temp'
+ qui replace group=1 in `=`temp'+1'/`=2*`temp''
+ }
+ }
+ else { /*METHODE POPULATION (SIMULATION)*/
+ if "`longitudinal'"==""{
+ *qui simirt, clear pcm(`d') cov(`var') group(`=`n1'*`gamma'/(`n1'+`n0')') deltagroup(`gamma') nbobs(1000000)
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n1'/(`n1'+`n0')*1000000)')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`=round(`n0'/(`n1'+`n0')*1000000)')
+ qui gen group=0
+ qui append using `save1'
+ *qui save d:\tmp,replace
+ bysort group:su lt
+ qui drop lt1
+ qui contract item* group, freq(freq)
+ qui count
+ local patobs=r(N)
+ if `patobs'>=`=(`n0'+`n1')*`nbpatterns''{
+ qui gen keep=0
+ qui gsort +group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ qui gsort -group -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n1''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ else{
+ qui simirt, clear pcm(`dlong') covmat(`matvar') mu(`mean1' `mean2') dim(`nbitems' `nbitems') nbobs(1000000)
+ forvalues j=1/`nbitems'{
+ rename itemA`j' item`j'
+ rename itemB`j' item`=`nbitems'+`j''
+ }
+ qui drop lt1 lt2
+ qui contract item*, freq(freq)
+ local patobs=r(N)
+ if `patobs'>=`=`n0'*`nbpatterns''{
+ qui gen keep=0
+ qui gsort -freq
+ qui replace keep=1 in 1/`=`nbpatterns'*`n0''
+ }
+ else{
+ qui gen keep=1
+ }
+ }
+ qui keep if keep==1
+ qui count
+ local retain=r(N)
+ di "Number of kept patterns:`retain'"
+ local method GH
+ }
+ if "`longitudinal'"==""{
+ qui gen mean1=-`n1'*`gamma'/(`n0'+`n1') if group==0
+ qui replace mean1=`n0'*`gamma'/(`n0'+`n1') if group==1
+ qui gen var1=`var0' if group==0
+ qui replace var1=`var1' if group==1
+ }
+ else{
+ qui gen mean1=`mean1'
+ qui gen mean2=`mean2'
+ }
+ /*CALCUL DES PROBAS PAR PATTERNS DE REPONSE*/
+ if "`method'"=="GH" {
+ local temp=`nbmodat'^(`nbtotitems')
+ local diff0=0
+ qui gen proba=.
+ local dixj=10
+ qui count
+ local tmp=r(N)
+
+ forvalues i=1/`tmp' {
+ local dix=floor(`tmp'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local tmpprob=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ *di "`dixj'% (`tmpprob')" _c
+ di "`dixj'%" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ *prout
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display name(x1 x2)
+ qui replace proba=r(int) in `i'
+ }
+ }
+ di
+ }
+ else { /*if "`method'"!="GH"*/
+ qui gen proba=1
+ forvalues t=1/`nbt'{
+ forvalues i=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ local diff0=0
+ local diff1=`dlong'[`i',1]
+ qui gen eps0=1
+ qui gen eps1=exp(mean`t'-`diff1')
+ qui gen d=eps0+eps1
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`i',`m']
+ qui gen eps`m'=exp(`m'*mean`t'-`diff`m'')
+ qui replace d=d+eps`m'
+ }
+ local listeps
+ forvalues m=0/`=`nbmodat'-1' {
+ qui replace proba=proba*eps`m'/d if item`i'==`m'
+ local listeps `listeps' eps`m'
+ }
+ qui drop `listeps' d
+ }
+ }
+ if "`method'"=="MEAN+GH" {
+ set tracedepth 1
+ if "`longitudinal'"==""{
+ qui gen keep=0
+ qui gsort -group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n1'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui gsort +group -proba
+ local min=min(`=`nbmodat'^`nbitems'',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ qui su proba if group==0
+ local sumproba0=r(sum)*100
+ qui su proba if group==1
+ local sumproba1=r(sum)*100
+ }
+ else{
+ qui gen keep=0
+ qui gsort -proba
+ local min=min(`nbpatmax',`=`n0'*`nbpatterns'')
+ qui replace keep=1 in 1/`min'
+ qui keep if keep==1
+ }
+
+ qui drop keep proba
+ local diff0=0
+ qui gen proba=.
+ qui count
+ local nnew=r(N)
+ di in gr "Number of studied response's patterns for the GH step: " in ye `nnew'
+ if "`longitudinal'"==""{
+ di in gr "(" in ye %6.2f `sumproba0' in gr "% of the group 0 and " in ye %6.2f `sumproba1' in gr "% of the group 1)"
+ }
+ local dixj=10
+ forvalues i=1/`nnew' {
+ local dix=floor(`nnew'/10)
+ if mod(`i',`dix')==0 & "`html'"=="" {
+ qui su proba
+ local sum=r(sum)
+ if "`dixj'"!="10" {
+ di ".." _c
+ }
+ di "`dixj'% (`sum')" _c
+ local dixj=`dixj'+10
+ }
+ forvalues t=1/`nbt'{
+ local int`t'=1
+ forvalues j=`=(`t'-1)*`nbitems'+1'/`=`t'*`nbitems'' {
+ qui su item`j' in `i'
+ local rep=r(mean)
+ local diff0=0
+ local diff1=`dlong'[`j',1]
+ local sum "1+exp(x`t'-`diff1')"
+ forvalues m=2/`=`nbmodat'-1' {
+ local diff`m'=`diff`=`m'-1''+`dlong'[`j',`m']
+ local sum "`sum'+exp(`m'*x`t'-`diff`m'')"
+ }
+ local int`t' "(`int`t''*exp(`rep'*x`t'-`diff`rep''))/(`sum')"
+ }
+ }
+ if "`longitudinal'"==""{
+ qui su mean1 in `i'
+ local mean=r(mean)
+ qui su var1 in `i'
+ local vart=r(mean)
+ *di "qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)"
+ qui gausshermite `int1',mu(`mean') sigma(`=sqrt(`vart')') display name(x1)
+ qui replace proba=r(int) in `i'
+ }
+ else{
+ local int "`int1'*`int2'"
+ matrix mean=(`mean1',`mean2')
+ qui gausshermite `int',mu(mean) var(`matvar') display
+ qui replace proba=r(int) in `i'
+ }
+ }
+ }
+ }
+ qui gen eff=proba
+ qui gen eff2=.
+
+ if "`longitudinal'"==""{
+ qui keep item* eff* group proba
+ local p1=1/`n1'
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p1') if group==1
+ qui replace eff2=floor(eff/`p0') if group==0
+ qui replace eff=eff-eff2*(`p1'*group+`p0'*(1-group))
+ qui su eff2 if group==1
+ local aff1=r(sum)
+ qui su eff2 if group==0
+ local aff0=r(sum)
+
+ local unaff1=`n1'-`aff1'
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort + group - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+ qui gsort - group - eff
+ qui replace eff2=eff2+1 in 1/`unaff1'
+
+ qui drop if eff2==0
+ qui gsort group item*
+ qui expand eff2
+ }
+ else{
+ qui keep item* eff* proba
+ local p0=1/`n0'
+ qui replace eff2=floor(eff/`p0')
+ qui replace eff=eff-eff2*`p0'
+ qui su eff2
+ local aff0=r(sum)
+
+ local unaff0=`n0'-`aff0'
+ qui gen efftmp=eff2
+ qui gsort - eff
+ qui replace eff2=eff2+1 in 1/`unaff0'
+
+ qui drop if eff2==0
+ qui gsort item*
+ qui expand eff2
+ }
+ qui drop proba eff eff2
+}
+
+if "`html'" == "" {
+ qui save "d:\essai.dta", replace
+}
+qui alpha item*
+local alpha=r(alpha)
+
+if "`longitudinal'"==""{ /*TRANSVERSAL*/
+ qui gen groupc=-`n1'/(`n0'+`n1') if group==0
+ qui replace groupc=`n0'/(`n0'+`n1') if group==1
+ if `nbmodat'==2 { /*DICHOTOMOUS CASE*/
+ if "`freeitems'"=="" {
+ local offset "offset(offset)"
+ local items
+ }
+ else {
+ local offset
+ local items "item1-item`nbitems'"
+ }
+ qui gen i=_n
+
+ tempname diff
+ matrix `diff'=`dd''
+
+ qui reshape long item, i(i)
+ qui rename item rep
+ qui rename _j item
+
+ qui gen offset=0
+ forvalues i=1/`nbitems' {
+ qui replace offset=-`diff'[1,`i'] if item==`i'
+ qui gen item`i'=item==`i'
+ qui replace item`i'=-item`i'
+ }
+ if `var0'==`var1' { /*EQUAL VARIANCES*/
+ *constraint 1 _cons=`=ln(`var')'
+ *qui xtlogit rep groupc ,nocons i(i) offset(offset) constraint(1)
+ if "`freevar'"=="" {
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) nrf(1) trace iterate(100)
+ }
+ else {/*UNEQUAL VARIANCES*/
+ tempvar G0 G1
+ qui gen `G0'=group==0
+ qui gen `G1'=group==1
+ qui eq B0: `G0'
+ qui eq B1: `G1'
+ constraint 1 _cons=0
+ if "`freevar'"=="" { /*FIXED UNEQUAL VARIANCE*/
+ constraint 2 `G0'=`=sqrt(`var0')'
+ constraint 3 `G1'=`=sqrt(`var1')'
+ constraint 1 _cons=`=sqrt(`var0')'
+ local constvar "constraint(1 2 3)"
+ }
+ else { /*FREE UNEQUAL VARIANCES*/
+ local constvar "constraint(1)"
+ }
+ qui gllamm rep groupc `items',nocons i(i) `offset' `constvar' fam(bin) link(logit) eqs(B0 B1) nrf(2) trace iterate(100)
+ }
+ tempname b V/*LONGITUDINAL*/
+ local row = 1
+ }
+ else { /*POLYTOMOUS CASE*/
+ matrix `db'=`db''
+ if "`freeitems'"=="" {
+ local fi "fixed(`db') fixedmu"
+ local row=1
+ }
+ else {
+ local fi
+ local row=(`nbmodat'-1)*`nbitems'+1
+ }
+ if `var0'==`var1' {
+ if "`freevar'"=="" {
+ local fv "fixedvar(`var0')"
+ }
+ else {
+ local fv
+ *noi pcm item*, `fi' covariates(groupc)
+
+ }
+ }
+ else {
+ if "`freevar'"=="" {
+ local fv "fixedvargroupc(`var')"
+ }
+ else {
+ local fv "vargroupc"
+ }
+ }
+ *di "jk pcm item*, `fi' covariates(groupc) `fv'"
+ /********************************ESSAI 23 mai 2014*/
+ qui simirt, clear pcm(`d') cov(`var1') mu(`=`n0'*`gamma'/(`n1'+`n0')') nbobs(`n1')
+ qui gen group=1
+ tempfile save1
+ qui save `save1',replace
+ qui simirt, clear pcm(`d') cov(`var0') mu(`=-`n1'*`gamma'/(`n1'+`n0')') nbobs(`n0')
+ qui gen group=0
+ qui append using `save1'
+ qui gen groupc=group-0.5
+ *di "ON A SIMULE"
+ **********************************FIN ESSAI 23 mai 2014*/
+
+ qui pcm item*, `fi' covariates(groupc) `fv'
+ }
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,`row']
+ local se=`V'[`row',`row']^.5
+}
+else{ /*LONGITUDINAL*/
+ qui raschlong item*, nbt(`nbt') diff(`d') var(`matvar')
+ tempname b V
+ matrix `b'=e(b)
+ matrix `V'=e(V)
+ local gammaest=`b'[1,1]
+ local se=`V'[1,1]^.5
+ local n1=`n0'
+}
+local poweruni=1-normal(1.96-`gamma'/`se')
+
+if "`html'" == "" {
+ di
+ di
+}
+if "`detail'"!=""{
+ di in gr "{hline 91}"
+ di _col(60) "Estimation with the "
+ di _col(50) "Cramer-Rao bound" _col(75) "classical formula"
+ di in gr "{hline 91}"
+}
+
+if "`longitudinal'"==""{
+ local power=1-normal(1.96-`gamma'/`se')+normal(-1.96-`gamma'/`se')
+ local nbw:word count `var'
+ if `nbw' == 2 { /* variance commune */
+ local varc = ((`n0'-1)*`var0'+(`n1'-1)*`var1')/(`n0'+`n1'-2)
+ }
+ else {
+ local varc = `var'
+ }
+ local clpower=normal(sqrt(`n1'*`gamma'^2/((`n1'/`n0'+1)*`varc'))-1.96)
+ local clnsn=(`n1'/`n0'+1)/((`n1'/`n0')*(`gamma'/sqrt(`varc'))^2)*(1.96+invnorm(`poweruni'))^2
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the group effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the group effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(59) in ye `n0' "/" `n1' _col(77) in ye %7.2f `clnsn' "/" %7.2f `=`clnsn'*`n1'/`n0''
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+else{
+ local clpower=normal(sqrt(`n0'*`gamma'^2)/(2*(`=`matvar'[1,1]'-`=`matvar'[2,1]'))-1.96)
+ local clnsn=2*(`=`matvar'[1,1]'-`=`matvar'[2,1]')*(1.96+invnorm(`poweruni'))^2/(`gamma'^2)
+ local ratio=(`n0'+`n1')/(`clnsn'*(1+`n1'/`n0'))
+ if "`detail'"==""{
+ di in gr "{hline 65}"
+ di in green "Estimation of the variance of the group effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni'
+ di in gr "{hline 65}"
+ }
+ else{
+ if "`gammafixed'"=="" {
+ di in green "Estimated value of the time effect" _col(59) in ye %7.2f `gammaest'
+ }
+ di in green "Estimation of the s.e. of the time effect" _col(59) in ye %7.2f `se'
+ di in green "Estimation of the variance of the time effect" _col(56) in ye %10.4f `=`se'^2'
+ di in green "Estimation of the power" _col(60) in ye %6.4f `poweruni' _col(86) in ye %6.4f `clpower'
+ di in green "Number of patients for a power of" %6.2f `=`poweruni'*100' "%" _col(63) in ye `n0' _col(85) in ye %7.2f `clnsn'
+ di in green "Ratio of the number of patients" in ye %6.2f _col(68)`ratio'
+ di in gr "{hline 91}"
+ }
+}
+
+if `expectedpower'!=-1 {
+ qui sampsi `=-`gamma'/2' `=`gamma'/2', sd1(`=sqrt(`var')') sd2(`=sqrt(`var')') alpha(0.05) power(`expectedpower') ratio(`=`n1'/`n0'')
+ local expn_1=r(N_1)
+ local expn_2=r(N_2)
+ local expn2=`expn_1'*`ratio'
+ di in green "Number of patients for a power of" %6.2f `=`expectedpower'*100' "%" _col(51) in ye %7.2f `expn2' "/" %7.2f `=`expn2'*`n1'/`n0'' _c
+ if "`detail'"!="" {
+ di _col(77) in ye %7.2f `expn_1' "/" %7.2f `expn_2'
+ }
+}
+
+
+return scalar EstGamma=`gammaest'
+return scalar CRbound=`=`se'^2'
+return scalar CRPower=`poweruni'
+return scalar ClPower=`clpower'
+return scalar ClSS=`clnsn'
+return scalar Ratio=`ratio'
+return scalar CronbachAlpha=`alpha'
+
+
+if "`graph'" != "" {
+ local x = "`min'(`step')`max'"
+ matrix res=J(15,5,.)
+ matrix colnames res= n0 n1 gamma variance power
+ local l=1
+
+ if "`longitudinal'"==""{
+ forval var = `x' {
+ qui raschpower59, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var(`var') html(`html')
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step'')) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n0=`n0', n1=`n1', {&gamma}=`gamma'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step''))
+ }
+ }
+
+ else {
+ if `gcorr' != -1 {
+ local l=1
+ forval var = `x' {
+ local cov = `gcorr'*`var'
+ local matv "`var',`cov'" " \ `cov',`var'"
+ qui raschpower59, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`var',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power variance,sort), title("n=`n0', {&gamma}=`gamma', corr=`gcorr'") ylabel(0(0.2)1) xlabel(`x') xtitle(Variance of the latent variable, margin(top)) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step''))
+ }
+ }
+
+ if `gvar' != -1 {
+ matrix res=J(9,5,.)
+ matrix colnames res= n0 n1 gamma corr power
+ local l=1
+ forvalues corr = `x' {
+ local cov = `corr'*`gvar'
+ local matv "`gvar',`cov'" " \ `cov',`gvar'"
+ qui raschpower59, n0(`n0') n1(`n1') gamma(`gamma') difficulties(`d') var("`matv'") html(`html') `longitudinal'
+ qui matrix res[`l',1]=(`n0', `n1', `gamma',`corr',r(CRPower))
+ local ++l
+ }
+ clear
+ qui svmat res,names(col)
+ if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_planif_graph,replace) nodraw"
+ qui graph twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation, margin(top)) ytitle(Power) name(planif_graph,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_planif_graph.gph
+ qui graph export `c(tmpdir)'/`html'_planif_graph.eps, replace
+ di "
"
+ di ""
+ }
+ else {
+ twoway (connected power corr,sort), title("n=`n0', {&gamma}=`gamma', var=`gvar'") ylabel(0(0.2)1) xlabel(`x') xtitle(Correlation) ytitle(Power) name(planif_graph,replace) xscale(range(`min' `=`max'+`step''))
+ }
+ }
+ }
+
+//di in gr "Method: " in ye "`method'"
+
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+capture qui use `raschpowerfile',clear
+
+end
diff --git a/Modules/ado/personal/r/raschres.ado b/Modules/ado/personal/r/raschres.ado
new file mode 100644
index 0000000..507e93c
--- /dev/null
+++ b/Modules/ado/personal/r/raschres.ado
@@ -0,0 +1,235 @@
+*! Version 1.2 June 3, 2013
+************************************************************************************************************
+* Stata program : raschres
+* Analysis of the residuals of the Rasch model
+* Version 1 : June 16, 2010
+* Version 1.1 : July 15, 2011
+* Version 1.2 : June 3, 2013 /*formatting outputs*/
+*
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* EA4275 - SPHERE
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2010-2013 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 raschres,rclass
+syntax varlist [if] [in] , diff(string) theta(varname) [genres(string) genfit(string) vargroup(varname) PCAres DETails]
+tempfile saveraschres
+if "`if'"!=""|"`in'"!="" {
+ *keep `if' `in'
+}
+*qui save `saveraschres',replace
+
+tempname res
+
+qui count
+local ntotal=r(N)
+tokenize `varlist'
+local nbitems: word count `varlist'
+qui tempname score lt
+qui genscore `varlist',score(`score')
+qui gen `lt'=`theta'
+forvalues i=1/`nbitems' {
+ local z2`i'=0
+}
+
+forvalues i=1/`nbitems'{
+ qui tempname p`i' res`i'
+ qui gen `p`i''=exp(`lt'-`diff'[1,`i'])/(1+exp(`lt'-`diff'[1,`i']))
+ qui gen `res'`i'=(1-`p`i'')/sqrt(`p`i''*(1-`p`i'')) if ``i''==1
+ qui replace `res'`i'=(0-`p`i'')/sqrt(`p`i''*(1-`p`i'')) if ``i''==0
+}
+su
+local chi2=0
+forvalues i=1/`nbitems' {
+ qui tempname res2
+ qui gen `res2'`i'=`res'`i'^2
+ qui su `res2'`i'
+ local chi2=`chi2'+`r(sum)'
+ label variable `res'`i' "``i''"
+}
+su
+tempname cor Ev
+matrix `cor'=J(`nbitems',`nbitems',.)
+local list
+forvalues i=1/`nbitems' {
+ forvalues j=1/`nbitems' {
+ qui corr `res'`i' `res'`j'
+ matrix `cor'[`i',`j']=r(rho)
+ }
+ local list "`list' ``i''"
+}
+matrix colname `cor'=`list'
+matrix rowname `cor'=`list'
+qui pca `res'*
+matrix `Ev'=e(Ev)
+
+tempname lt2 ltcl group df nbmiss rep total
+qui egen `nbmiss'=rowmiss(`varlist')
+qui gen `rep'=`nbitems'-`nbmiss'
+qui gen `lt2'=`lt' if `score'!=0&`score'!=`rep'
+if "`vargroup'"=="" {
+ qui gengroup `lt2', newvar(`group') cont det minsize(33)
+}
+else {
+ qui `group'=`vargroup'
+}
+qui su `group'
+local maxgroup=r(max)
+
+if "`details'"!="" {
+ di "{hline 42}"
+ di _col(12) "Min" _col(29) "Max"
+ di "{dup 42:-}"
+ di "" _col(8) "" _col(14) "Latent" _col(28) "" _col(31) "Latent" _col(53) ""
+ di "Group" _col(8) "Score" _col(15) "trait" _col(25) "Score" _col(32) "trait" _col(42) "n"
+ di "{hline 42}"
+ forvalues i=1/`maxgroup' {
+ qui count if `group'==`i'
+ local n`i'=r(N)
+ qui su `score' if `group'==`i'
+ local scoremin`i'=r(min)
+ local scoremax`i'=r(max)
+ qui su `lt' if `group'==`i'
+ local ltmin`i'=r(min)
+ local ltmax`i'=r(max)
+ di "`i'" _col(9) %4.0f `scoremin`i'' _col(14) %6.3f `ltmin`i'' _col(26) %4.0f `scoremax`i'' _col(31) %6.3f `ltmax`i'' _col(39) %4.0f `n`i''
+ }
+ di "{hline 42}"
+}
+
+local nj=0
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=.
+ local nj=`nj'+r(N)
+}
+qui gen `df'=(`nj'-(`ntotal' + `nbitems' - 1 ))/`nj'*`rep'
+qui gen `total' =`score'
+local mult=(`nj'-(`ntotal' + `nbitems' - 1 ))/`nj'
+
+
+forvalues i=1/`nbitems' {
+ qui count if (`total'!=0&`total'!=`rep')&``i''!=.
+ local mult`i'=r(N)
+ local df`i'=`mult'*`mult`i''
+ tempname res2`i'
+ qui gen `res2`i''=(`res'`i')^2
+ qui su `res2`i'' if `total'!=0&`total'!=`rep'
+ local sumsq`i'=r(sum)
+ local fit`i'=(`sumsq`i''-`df`i'')/sqrt(2*`df`i'')
+}
+
+qui gen `ltcl'=.
+forvalues g=1/`maxgroup' {
+ qui su `lt' if `group'==`g'
+ local ltgroup`g'=r(mean)
+ local N`g'=r(N)
+ qui replace `ltcl'=`ltgroup`g'' if `group'==`g'
+}
+forvalues i=1/`nbitems' {
+ local chi`i'=0
+ forvalues g=1/`maxgroup' {
+ qui su ``i'' if `group'==`g'
+ local po`i'_`g'=r(mean)
+ local pe`i'_`g'=exp(`ltgroup`g''-`diff'[1,`i'])/(1+exp(`ltgroup`g''-`diff'[1,`i']))
+ local std`i'_`g'=2*`N`g''*(`po`i'_`g''-`pe`i'_`g'')^2/sqrt(.5*(`po`i'_`g''+`pe`i'_`g'')*(1-.5*(`po`i'_`g''+`pe`i'_`g'')))
+ local chi`i'=`chi`i''+`std`i'_`g''
+ }
+ di "chi item ``i'' = `chi`i''"
+}
+
+local chisq=0
+tempname y2 vy2
+qui gen `y2'=0
+qui gen `vy2'=0
+forvalues i=1/`nbitems' {
+ qui replace `y2'=`y2'+`res'`i'^2 if ``i''!=.
+ qui replace `vy2'=`vy2'+2*tanh((`lt2'-`diff'[1,`i'])/2)*sinh(`lt2'-`diff'[1,`i']) if ``i''!=.
+ tempname y2`i' vy2`i'
+ qui gen `y2`i''=`res'`i'^2
+ qui su `y2`i'' if `total'!=0&`total'!=`rep'&``i''!=.
+ local sumy2`i'=r(sum)
+ qui tab `ltcl'
+ qui gen `vy2`i''=2*tanh((`lt2'-`diff'[1,`i'])/2)*sinh(`lt2'-`diff'[1,`i'])
+ di "item ``i''"
+ su `vy2`i'' if `total'!=0&`total'!=`rep'&``i''!=.
+ local sumvy2`i'=r(sum)
+ local fit`i'=(`sumy2`i''-`df`i'')/sqrt(`sumvy2`i'')
+ local fit2`i'=`df`i''*(ln(`sumy2`i'')-ln(`df`i''))/sqrt(`sumvy2`i'')
+ local chisq`i'=0
+ forvalues g=1/`maxgroup' {
+ qui su `y2`i'' if `group'==`g'&``i''!=.
+ local sumy2`i'_g`g'=r(sum)
+ local n`i'g`g'=r(N)
+ qui su `vy2`i'' if `group'==`g'&``i''!=.
+ local sumvy2`i'_g`g'=r(sum)
+ local fit`i'_g`g'=(`sumy2`i'_g`g''-`n`i'g`g'')/sqrt(`sumvy2`i'_g`g'')
+ local chisq`i'=`chisq`i''+(`fit`i'_g`g'')^2
+ }
+ local chisq=`chisq'+`chisq`i''
+ /*fit2 est l'équivalent de FitResid et chisq est correct*/
+}
+local RMSEA=sqrt(`chisq'/((`nbitems'*(`maxgroup'-1)-1)*(`ntotal'-1)))
+
+di in gr "{hline 55}"
+di in gr "Items" _col(18) "FitResid" _col(31) "ChiSq" _col(42) "df" _col(55) "p"
+di in gr "{hline 55}"
+forvalues i=1/`nbitems' {
+ di in ye abbrev("``i''",18) _col(19) %7.3f `fit2`i'' _col(30) %6.2f `chisq`i'' _col(40) %4.0f `=`maxgroup'-1' _col(50) %6.4f 1-chi2(`=`maxgroup'-1',`chisq`i'')
+}
+di in gr "{dup 55:-}"
+di in ye "Total" _col(30) %6.2f `chisq' _col(40) %4.0f `=(`maxgroup'-1)*`nbitems'' _col(50) %6.4f 1-chi2(`=(`maxgroup'-1)*`nbitems'',`chisq`i'')
+di in ye "RMSEA" _col(30) %6.4f `RMSEA'
+di in gr "{hline 55}"
+di
+
+if "`pcares'"!="" {
+ di "{hline 36}"
+ di "Correlation matrix between residuals"
+ di "{hline 36}"
+ matrix list `cor',noheader format(%5.3f)
+ di
+ di "{hline 28}"
+ di "Eigenvalues of the residuals"
+ di "{hline 28}"
+ matrix rowname `Ev'=Eigenvalues
+ tempname Evp E
+ matrix `Evp'=`Ev'/`nbitems'
+ matrix `E'=`Ev' \ `Evp'
+ matrix rowname `E'=Eigenvalues Proportion
+matrix list `E',noheader format(%5.3f)
+}
+
+*use `saveraschres', clear
+local dfind=`df'/`ntotal'*`nbitems'
+if "`genfit'"!="" {
+ qui gen `genfit'=`df'*(ln(`y2')-log(`df'))/sqrt(`vy2') `if' `in'
+}
+if "`genres'"!="" {
+ forvalues i=1/`nbitems' {
+ qui gen `genres'`i'=`res'`i' `if' `in'
+ }
+}
+
+end
diff --git a/Modules/ado/personal/r/raschres.hlp b/Modules/ado/personal/r/raschres.hlp
new file mode 100644
index 0000000..0a9a2aa
--- /dev/null
+++ b/Modules/ado/personal/r/raschres.hlp
@@ -0,0 +1,54 @@
+{smcl}
+{* 3june2013}{...}
+{hline}
+help for {hi:raschres}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Test of fit of the Rasch model using tests similar to RUMM based on residuals}
+
+{p 8 14 2}{cmd:raschres} {varlist} {cmd:,} {cmdab:diff}({it:vector}) {cmdab:theta}({it:varname}) [ {cmdab:genres}({it:string}) {cmdab:genfit}({it:newvarname})
+{cmdab:vargroup}({it:varname}) {cmdab:PCA:res} {cmdab:det:ails}]
+
+{title:Description}
+
+{p 4 8 2}{cmd:raschres} allows estimating similar tests than the RUMM software in order to test the fit of the dataset to a Rasch model, or to evaluate the
+unidimensionality of the data using a Principal Components Analysis (PCA) on the residuals. {cmd:raschres} is available only for dichotomous items.
+
+{title:Options}
+
+{p 4 8 2}{cmd:diff} is required and defines a (1xJ) vector of values corresponding to the estimations of the difficulty parameters
+
+{p 4 8 2}{cmd:theta} is required and defines a variable containing the estimated values of the latent trait for each individual of the sample.
+
+{p 4 8 2}{cmd:genres} allows creating new variables containing the residuals (one new variable per item). This option must contain a prefix which will be given to
+each new variable.
+
+{p 4 8 2}{cmd:genfit} create a new variable containing a fit index for each individual.
+
+{p 4 8 2}{cmd:vargroup} defines a variable containing the affectation between groups of individuals in order to compute fit statistics.
+
+{p 4 8 2} {cmd:pcares} allows providing a PCA on the residuals.
+
+{p 4 8 2} {cmd:details} allows obtaining more detailed results.
+
+{title:Example}
+
+ {p 4 8 2}{cmd:. matrix diff=(-1.47,-0.97,-.23,-0.12,0.02,0.1)}{p_end}
+ {p 4 8 2}{cmd:. raschres items*, diff(diff) theta(theta)}{p_end}
+
+ {p 4 8 2}{cmd:. raschres items*, diff(diff) theta(theta) genfit(fit) genres(res)}{p_end}
+
+ {p 4 8 2}{cmd:. raschres items*, diff(diff) theta(theta) PCA det}{p_end}
+
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA4275 "Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Emails:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
diff --git a/Modules/ado/personal/r/raschtest v8.10.1.ado b/Modules/ado/personal/r/raschtest v8.10.1.ado
new file mode 100644
index 0000000..bd9fc19
--- /dev/null
+++ b/Modules/ado/personal/r/raschtest v8.10.1.ado
@@ -0,0 +1,206 @@
+*! version 8.10.1 15july2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+* Version 8.3 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option*/
+* Version 8.6 (2012-11-19) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*PNG option*/
+* Version 8.10 (2019-06-05) : Jean-Benoit Hardouin /*EXTENSION option*/
+* Version 8.10.1 (2019-06-15) : Jean-Benoit Hardouin /*NOSTAND option*/
+*
+* Required modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2003-2012, 2019 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) GENRes(string) EXTension(string) graphclose docx(string) noSTand]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genres'"!="" {
+ local gensresv8 "genres(`genres')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+raschtestv7 `varlist' `if' `in' , id(`id') html(`html') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genresv8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8' `png' extension(`extension') `graphclose' docx(`docx') `stand'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/raschtest.ado b/Modules/ado/personal/r/raschtest.ado
new file mode 100644
index 0000000..bd9fc19
--- /dev/null
+++ b/Modules/ado/personal/r/raschtest.ado
@@ -0,0 +1,206 @@
+*! version 8.10.1 15july2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+* Version 8.3 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option*/
+* Version 8.6 (2012-11-19) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*PNG option*/
+* Version 8.10 (2019-06-05) : Jean-Benoit Hardouin /*EXTENSION option*/
+* Version 8.10.1 (2019-06-15) : Jean-Benoit Hardouin /*NOSTAND option*/
+*
+* Required modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2003-2012, 2019 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) GENRes(string) EXTension(string) graphclose docx(string) noSTand]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genres'"!="" {
+ local gensresv8 "genres(`genres')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+raschtestv7 `varlist' `if' `in' , id(`id') html(`html') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genresv8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8' `png' extension(`extension') `graphclose' docx(`docx') `stand'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/raschtest.hlp b/Modules/ado/personal/r/raschtest.hlp
new file mode 100644
index 0000000..5628958
--- /dev/null
+++ b/Modules/ado/personal/r/raschtest.hlp
@@ -0,0 +1 @@
+.h raschtestv7
diff --git a/Modules/ado/personal/r/raschtestv7.ado b/Modules/ado/personal/r/raschtestv7.ado
new file mode 100644
index 0000000..63d21c3
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv7.ado
@@ -0,0 +1,2570 @@
+*! version 8.10.2 24september2019
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+* Version 8.6 (2012-11-20) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.7 (2013-05-28) : Jean-Benoit Hardouin /*Correction of a bug in the covariates option with ss1 and ss3*/
+* Version 8.8 (2014-02-27) : Jean-Benoit Hardouin /*Correction of a bug when the null or the parfect score have a frequency of 0 (no test)*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*png option (graphs in png), information curve by item*/
+* Version 8.10 (2019-07-05) : Jean-Benoit Hardouin /*extension option (graphs with the chosen extension) who replaces the png option, docx option*/
+* Version 8.10.1 (2019-07-15) : Jean-Benoit Hardouin /*nostand option*/
+* Version 8.10.2 (2019-09-24) : Jean-Benoit Hardouin /*correction of a small bug*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.20 (ssc describe gllamm)
+* gllapred version 2.3.8 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2014 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) extension(string) GRAPHClose DOCX(string) noSTand]
+
+local covariables `covariates'
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("Graphical outputs of the raschtest module")
+}
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+if "`html'"!="" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local draw
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+if "`extension'"!=""&"`extension'"!="png"&"`extension'"!="eps"&"`extension'"!="ps"&"`extension'"!="svg"&"`extension'"!="wmf"&"`extension'"!="png"&"`extension'"!="emf"&"`extension'"!="pdf"&"`extension'"!="tif" {
+ di in red "The {hi:extension} option can not contain the value `extension'. Please correct it."
+ error 198
+ exit
+}
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ local nbobserv=r(N)
+
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ local nbobserv=e(N)
+ *di "nombre d'obs:`nbobserv'"
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempfile Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+if "`html'" != "" {
+ di ""
+}
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ }
+ else {
+ di "Estimation method: Conditional maximum likelihood (CML)
"
+ }
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ }
+ else {
+ di "Estimation method: Marginal maximum likelihood (MML)
"
+ }
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+if "`html'" == "" {
+ di in green "Number of items: " in yellow `nbitems'
+ di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+ }
+}
+else {
+ di "Number of items: " `nbitems' "
"
+ di "Number of groups: " `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di " (`nbtest' of them are used to compute the statistics of test)"
+ }
+ di "
"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+if "`html'" == "" {
+ di in green "Number of individuals: " in yellow `N'
+ di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+ if "`ld'"=="" {
+ di in green " (removed)"
+ }
+ else {
+ di
+ }
+ di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+}
+else {
+ di "Number of individuals: `N'
"
+ di "Number of individuals with missing values: " `nbindmiss'
+ if "`ld'"=="" {
+ di " (removed)"
+ }
+ di "
"
+ di "Number of individuals with nul or perfect score: " `=`effscore0'+`effscore`nbgroups''' "
"
+}
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ }
+}
+else {
+ if "`html'" == "" {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ di
+ }
+ else {
+ di "Marginal log-likelihood: " %-13.4f `ll' "
"
+ di "Log-likelihood: " %-13.4f `globalll' ""
+ }
+}
+
+if "`html'" == "" {
+ noi di in green _col(16) "Difficulty" `conttest'
+ if "`test'"!="NONE"&"`stand'"=="" {
+ di in green _col(58) "Standardized"
+ }
+ if "`test'"!="NONE"&"`stand'"!="" {
+ di
+ }
+ noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+ }
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+ di ""
+ di " | Difficulty | | "
+ if "`test'"!="NONE" {
+ di " | Standardized | "
+ }
+ di "
"
+ di "Items | parameters | std Err. | "
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di "`namewp' | df | p-value | Outfit | Infit | "
+ if "`method'"=="cml" {
+ di "U | "
+ }
+ }
+ di "
"
+}
+
+forvalues i=1/`nbitems' {
+ if "`html'" == "" {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ }
+ else {
+ di "" %12s abbrev("``i''`fixed`i''" ,12) " | " %8.5f `beta`i'' " | " %6.5f `sd`i'' " | "
+ }
+ if "`test'"!="NONE" {
+ if "`html'" == "" {
+ if "`stand'"=="" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+* di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfit`i'' _col(65) %6.3f `infit`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ else {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfit`i'' _col(65) %6.3f `infit`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ }
+ else {
+ if "`stand'"=="" {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfitstd`i'' " | " %6.3f `infitstd`i'' " | "
+ }
+ else {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfit`i'' " | " %6.3f `infit`i'' " | "
+ }
+ }
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ if "`stand'"=="" {
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ }
+ else {
+ matrix `itemfit'[`i',4]=`outfit`i''
+ matrix `itemfit'[`i',5]=`infit`i''
+ }
+
+ if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in ye _col(72) %6.3f `U`i''
+ }
+ else {
+ di "" %6.3f `U`i'' " | "
+ }
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+ }
+}
+if "`html'" == "" {
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+}
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ if "`html'" == "" {
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+ }
+ else {
+ di "`descwp' | | `namewp'= | " %8.3f `globalfit'[1,1] " | " %3.0f `globalfit'[1,2] " | " %6.4f `globalfit'[1,3] " | | |
"
+ if "`method'"=="cml" {
+ di "Andersen LR test | | Z= | " %8.3f `AndersenZ'[1,1] " | " %3.0f `AndersenZ'[1,2] " | " %6.4f `AndersenZ'[1,3] " | | |
"
+ }
+ di "
"
+ }
+}
+
+if "`html'" == "" {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+ }
+
+ di
+}
+else {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di "*: The difficulty parameter of this item had been fixed to 0
"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di "The mean of the difficulty parameters is fixed to 0
"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di "You have groups of scores with less than 30 individuals. The tests can be invalid.
"
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test.
"
+ }
+ di ""
+}
+
+if "`html'" == "" {
+ if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+ }
+}
+else {
+ if "`method'"!="cml" {
+ di ""
+ di ""
+ di "Parameters | Coef. | std Err. | z | P>|z| |
"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di "Sigma | " %8.5f `sig' " | " %6.5f `sesig' " | " %6.3f `zsig' " | " %7.4f `pzsig' " |
"
+ }
+}
+
+
+
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=r(N_obs)
+ *di "nbobs=`nbobs'"
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di in green "{dup 85:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local nbobs=r(N_obs)
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`nbobs'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1
+ *di "local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1 (cov:`covariablesss1')"
+ local ss1`i'=`var`i''*`df`i''
+ *di "cov : `covariablesss1' var=`var`i'' df=`df`i''"
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `ss1`i'' _col(25) %12.3f `=`ss1`=`i'-1''-`ss1`i''' _col(47) %4.0f `df`i'' _col(63) %8.3f `var`i'' _col(81) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 85}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=e(N_obs)
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ local ss3ref=`=`sig'^2*(`df0'-`nbcovariables')'
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `ss3ref' _col(25) %12.3f `=`ss30'-`ss3ref'' _col(47) %4.0f `=`df0'-`nbcovariables'' _col(63) %8.3f `sig'^2 _col(81) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 85:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ *ereturn list
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local nbobs=e(N)
+ local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)
+ *di "local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)"
+ local ss3s`i'=`vars`i''*`dfs`i''
+ local vara`i'=`sig'^2
+ local dfa`i'=`nbobs'-(`nbitems'+1)-1-`nbcovariables'
+ local ss3a`i'=`vara`i''*`dfa`i''
+ *di "cov : `covariablesss3' var=`vars`i'' df=`dfs`i''"
+ di _col(2) %12s in green abbrev("`covariable`i''",12) _col(15) in ye %12.3f `ss3s`i'' _col(25) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(47) %4.0f `=`df0'-`nbcovariables'+1' _col(63) %8.3f `vars`i'' _col(80) %6.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 85}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ if "`html'" == "" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di ""
+ di ""
+ di "Group | Score | Ability parameters | std Err. | Freq. | Expected Score | "
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ di "ll | "
+ }
+ di "
"
+ }
+
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ if "`html'" == "" {
+ di in green _col(17) "{dup `line':-}"
+ }
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ if "`html'" == "" {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ }
+ else {
+ di "" %5s "`gr'" " | " %5s "`s'" " | " `format1' `theta`nonul'' " | " `format1' `sdtheta`nonul'' " | " %4.0f `nbrealscore`s'' " | " % 4.2f `expscore`nonul'' " | " %11.4f `tmp' " | "
+ }
+ local nonul=`nonul'+1
+ }
+ }
+ if "`html'" == "" {
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di "
"
+ }
+}
+
+if "`method'"=="mml"|"`method'"=="gee" {
+ if "`html'" == "" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+ }
+ else {
+ di ""
+ di ""
+ di ""
+ di "Mean variance of the error | " %10.4f `meanse2' " |
"
+ local sig2=`sig'^2
+ di "Estimated variance of the latent trait | " %10.4f `sig2' " |
"
+ local psi2=1-`meanse2'/`sig2'
+ di "Personal Separation Index (PSI) | " %10.4f `psi2' " |
"
+ di "Adjusted PSI on covariates (PSIadj) | " %10.4f `psi' " |
"
+ di "
"
+ }
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ if "`html'"=="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+ }
+ else {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di in gr ""
+ di in gr "Group: `g' from `liminf`g'' to `limsup`g'' (n=`nbscore`g'')"
+ di in gr "Item | Observed | Expected | Scaled |
"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di "``j'' | " %4.0f `Obs2'[`j',`g'] " | " %6.2f `Th2'[`j',`g'] " | " %7.4f `tmp' " |
"
+ }
+ di "Contribution to the `namewp' statistics: | " %8.4f `test`g''[1,1] " |
"
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di " | " %4.0f `nbrealscore`h'' " | " %6.2f `ci`h'' " | " %7.4f `tmp' " |
"
+ local tmp=`tmp'^2
+ di "Contribution to the `namewp' statistics: | " %8.4f `tmp' " |
"
+ }
+ di "
"
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_icc_``i''"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , `htmlregion' name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') xsize(12) ysize(9) `draw'
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save icc``i'' "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_icc_``i''.eps, replace
+ di ""
+
+ }
+ *set trace on
+ if "`filessave'"!="" {
+ qui graph save icc``i'' "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ graph close
+ }
+ *qui graph use `dirsave'\\icc``i''
+ qui graph export `dirsave'\\icc``i''.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ putdocx image `dirsave'\\icc``i''.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ forvalues i=1/`nbitems' {
+ tempvar info``i''
+ }
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ local gphbyitem
+ forvalues i=1/`nbitems' {
+ qui gen `info``i'''=exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ label variable `info``i''' "``i''"
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ local gphbyitem `gphbyitem' `info``i'''
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_information"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ *set trace on
+ local saving "`dirsave'\\information"
+ graph twoway (line `info' `latent') , `htmlregion' name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save information "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\information
+ qui graph export `dirsave'\\information.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\information.`extension', width(4)
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save information "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_information.eps, replace
+ di ""
+ }
+ local saving "`dirsave'\\inf_items"
+ graph twoway (line `gphbyitem' `latent') , `htmlregion' name(inf_items,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the items") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save inf_items "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\inf_items
+ qui graph export `dirsave'\\inf_items.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\inf_items.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), `htmlregion' name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstd' `id'), `htmlregion' name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfit "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfitind
+ qui graph export `dirsave'\\outfit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfit.`extension', width(4)
+ }
+
+ }
+ qui graph save infit "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infitind
+ qui graph export `dirsave'\\infit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infit.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',`htmlregion' name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstdj' `betap',`htmlregion' name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfititem "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfititem.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfititems
+ qui graph export `dirsave'\\outfititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfititems.`extension', width(4)
+ }
+ }
+ qui graph save infititem "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infititems.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infititems
+ qui graph export `dirsave'\\infititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infititems.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_map"
+ }
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), `htmlregion' name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save graph "`saving'" , `replace'
+ if "`extension'"!="" {
+ *qui graph use `dirsave'\\graph
+ qui graph export `dirsave'\\graph.`extension' , `replace'
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("In this dataset, there are `r(N)' models")
+
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\graph.`extension', width(4)
+ }
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save graph "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_map.eps, replace
+ di ""
+ }
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or more modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+return scalar N_obs=`nbobserv'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+if "`docx'"!="" {
+*set trace on
+ putdocx save "`dirsave'\\`docx'.docx", replace
+ putdocx clear
+}
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/raschtestv7.hlp b/Modules/ado/personal/r/raschtestv7.hlp
new file mode 100644
index 0000000..812a57f
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv7.hlp
@@ -0,0 +1,222 @@
+{smcl}
+{* 5june2019}{...}
+{hline}
+help for {hi:raschtest} and {hi:raschtestv7}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Estimation of the parameters of a Rasch model, tests and specific graphs}
+
+{p 8 14 2}{cmd:raschtestv7} {it:varlist} [{cmd:if} {it:exp}] [{cmd:in} {it:range}]
+, {cmdab:id}({it:varname}) [{cmdab:meth:od}({it:keyword}) {cmdab:nold} {cmdab:iterate}({it:#})
+{cmdab:t:est}({it:keyword}) {cmdab:diff:iculties}({it:vector})
+{cmdab:mean:diff} {cmdab:d:etails} {cmd:group}({it:numlist}) {cmdab:autog:roup}
+{cmdab:cov:ariates}({it:varlist}[,{cmd: ss1 ss3}])
+{cmdab:dir:save}({it:directory}) {cmdab:files:save} {cmd:png} {cmdab:pause}
+{cmdab:rep:lace} {cmdab:nodraw} {cmdab:icc}
+{cmdab:inf:ormation} {cmdab:split:test} {cmdab:fit:graph}
+{cmdab:genlt}({it:newvarname}[,{cmdab:rep:lace}]) {cmdab:gensco:re}({it:newvarname})
+{cmd:genfit}({it:newvarlist}) {cmd:genres}({it:string})
+{cmdab:com:p}({it:varname})
+{cmdab:dif}({it:varlist})
+{cmdab:tr:ace} {cmdab:time}]
+
+{p 8 14 2}{cmd:raschtest} {it:varlist} [{cmd:if} {it:exp}] [{cmd:in} {it:range}]
+[, {it:options_of_raschtestv7} {cmdab:gra:ph}]
+
+{p 8 14 2}{it:varlist} is a list of two existing binary variables or more.
+
+{title:Description}
+
+{p 4 8 2}{cmd:raschtest} estimates the parameters of a Rasch model. The estimation
+method can be chosen between conditional maximum likelihood (CML), marginal
+maximum likelihood (MML) and generalized estimating equations (GEE). {cmd:raschtest}
+offer a set of tests, to valuate the fit of the data to the Rasch model, or detect
+non homogeneous items (Andersen Z test, First order test (Q1, R1c, R1m, or Wright
+Panchapakesan), U test, Split test) and indexes (OUTFIT and INFIT per items or per
+individuals). Several graphical representations can be easily obtained: comparison
+of the observed and theorical Item Characteristic Curves (ICC), Map difficulty
+parameters/Scores, results of the split tests, and information function (for the scale and by item).
+
+{title:Options}
+
+{p 4 8 2}{cmd:method} specifies the used method to estimate the difficulty
+parameter among CML ({cmd:method}({it:cml}) - by default), MML ({cmd:method}({it:mml}))
+or GEE ({cmd:method}({it:gee})).
+
+{p 4 8 2}{cmd:nold} avoids the Listwise Deletion of the individuals with missing data.
+By default, all the individuals with one or more missing data are omited.
+
+{p 4 8 2}{cmd:iterate} allows defining the maximal number of iterations of the maximisation algorithm.
+By default, this number is fixed to 200.
+
+{p 4 8 2}{cmd:test} specifies the tests to use among {cmd:test}({it:R}) (by
+default, for the R1c or the R1m test), {cmd:test}({it:WP}) (for the Wright-
+Panchapakesan test) and {cmd:test}({it:Q}) (for the Q1 test).
+
+{p 4 8 2}{cmd:difficulties} allows fixing the values of the difficulties parameters of the items.
+The vector must be a row vector and must contain as many values as items.
+This option is available only with {cmd:method}({it:mml}).
+
+{p 4 8 2}{cmd:meandiff} centers the difficulty parameters (only with
+{cmd:method}({it:cml})): by default for the CML estimations, the difficulty
+parameter to the last item is fixed to 0. With {cmd:meandiff}, only the
+diagonal elements of the covariance matrix of these parameters are estimated.
+
+{p 4 8 2}{cmd:details} displays for each group of scores a table containing the
+observed and expected number of positive responses and the contribution of this
+group to the global first-order statistic.
+
+{p 4 8 2}{cmd:group} specifies groups of scores, by defining the superior
+limits of each group (note that the score "0" and this one corresponding to the
+number of items are always isolated).
+
+{p 4 8 2}{cmd:autogroup} automatically creates groups of scores (with at least
+30 individuals per group).
+
+{p 4 8 2}{cmd:covariates} allows introducing covariates on the model. The {cmd:ss1} and
+{cmd:ss3} options allows computing the type 1 and type 3 sums of squares to explain the
+variance of the latent trait by these covariates. This option is available only with {cmd:method}({it:mml}).
+
+{p 4 8 2}{cmd:dirsave} specifies the directory where the graphs will be saved
+(by default, the directory defined in c(pwd)).
+
+{p 4 8 2}{cmd:filessave} saves all the graphs in .gph files (by default, the
+graphs are not saved).
+
+{p 4 8 2}{cmd:png} saves all the graphs in .png files.
+
+{p 4 8 2}{cmd:pause} allows to made a pause between the displaying of each graph.
+
+{p 4 8 2}{cmd:replace} specifies that the existing graphical files will be
+replaced.
+
+{p 4 8 2}{cmd:nodraw} avoids displaying of the graphs.
+
+{p 4 8 2}{cmd:icc} displays, for each item, the observed and expected (under the Rasch
+model) ICC in a graph.
+
+{p 4 8 2}{cmd:graph} represents in the same graph the distributions of the
+difficulty parameters, this one of the scores, and [with {cmd:method}({it:mml}) or
+{cmd:method}({it:gee})] the expected distribution of the latent trait, in
+function of the latent trait.
+
+{p 4 8 2}{cmd:information} represents the information function for the set of
+the items in function of the latent trait.
+
+{p 4 8 2}{cmd:splittest} represents, for each item, the CML estimations of the
+difficulty parameters for the others items in the two sub-samples defined by
+the individuals who have positively respond to the splitting item for the first
+group, and by the individuals who have negatively respond to the splitting item
+for the second one.
+
+{p 4 8 2}{cmd:fitgraph} represents four graphs. The first one concerns the
+OUTFIT indexes for each item, the second one, the INFIT indexes for each item,
+the third one the OUTFIT indexes for each individual, and the last one the
+INFIT indexes for each individual.
+
+{p 4 8 2}{cmd:genlt} creates a new variable containing, for each individual,
+the estimated value of the latent trait. The {cmd:replace} option allows replacing
+an existing variable.
+
+{p 4 8 2}{cmd:genscore} creates a new variable containing, for each individual,
+the value of the score.
+
+{p 4 8 2}{cmd:genres} creates new variables containing, for each individual,
+the value of the residuals. This option defines the prefix to these new variables
+which will be followed by the name of each item.
+
+{p 4 8 2}{cmd:genfit} creates several new variables. {it:newvarlist}
+contains two words. The first one represents "outfit" and the second one "infit".
+This option generates two variables with this names for the OUTFIT and INFIT
+indexes for each individual, and the variables "outfitXX" (by replacing "outfit"
+by the first word) for the contribution of the item XX to the OUTFIT index (Note
+that the new variables contain unstandardized OUTFIT and INFIT indices, even
+the program displays standardized statistics in the results table and with the
+{cmd:fitgraph} option).
+
+{p 4 8 2}{cmd:comp} tests the equality of the means of the latent trait for two
+groups of individuals defined by a binary variable (only with {cmd:method}({it:mml})
+or {cmd:method}({it:gee})).
+
+{p 4 8 2}{cmd:dif} tests the Differential Item Functioning (DIF) on a list of
+variables by likelihood ration tests. For each variable defined in the list,
+the items parameters are estimated in each groups defined by this variable,
+and the test considers the null assumption: the estimations are the same in each group.
+The statistic of the test follows a chi-square distribution under the null assumption.
+The variable defined in the {cmd:dif} option must have 10 or less modalities, coded
+from 0 or 1 to an integer k<=10. This option is available only with {cmd:method}({it:cml}).
+
+{p 4 8 2}{cmd:trace} displays more outputs during the running of the module.
+
+{p 4 8 2}{cmd:time} displays the number of seconds to run the module.
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:e(N)}: Number of observations
+
+{p 4 8 2}{cmd:e(ll)}: (Marginal) Log-likelihood
+
+{p 4 8 2}{cmd:e(cll)}: Conditional log-likelihood
+
+{p 4 8 2}{cmd:e(AIC)}: Akaike Information Criterion
+
+{p 4 8 2}{cmd:e(PSI)} and {cmd:e(PSIadj)}: Personal Separation Indexes (only for {cmd:meth}({it:mml})
+
+{p 4 8 2}{cmd:e(sigma)}: Estimated standard deviation of the latent trait
+
+{p 4 8 2}{cmd:e(sesigma)}: Standard error of the estimated standard deviation of the latent trait
+
+{p 4 8 2}{cmd:e(beta)}: Estimated difficulty parameters
+
+{p 4 8 2}{cmd:e(Varbeta)}: Covariance matrix of the estimated difficulty parameters
+
+{p 4 8 2}{cmd:e(theta)}: Estimated values for the latent trait for each value of the score
+
+{p 4 8 2}{cmd:e(Varbeta)}: Covariance matrix for the estimated values for the latent trait for each value of the score
+
+{p 4 8 2}{cmd:e(itemFit)}: Statistics of fit for each item (first order statistic, degree of freedom, p-value, OUTFIT index, INFIT index, and (if {cmd:method}({it:cml})) U-test statistic
+
+{p 4 8 2}{cmd:e(globalFit)}: Global first order test (statistic, degrees of freedom, p-value)
+
+{p 4 8 2}{cmd:e(AndersenZ)}: Andersen LR Z test (first order statistic, degree of freedom, p-value) (if {cmd:method}({it:cml}))
+
+{p 4 8 2}{cmd:e(DIF)}: DIF LR Z test (statistic, degree of freedom, p-value for each variable defined in {cmd:dif}) (if {cmd:method}({it:cml}))
+
+{p 4 8 2}{cmd:e(Zcomp)} and {cmd:e(pZcomp)}: Statistics of test and associated p-value for the test of comparison of the two population defined with the {cmd:comp} option.
+
+{p 4 8 2}{cmd:e(betacovariates)}, {cmd:e(Vbetacovariates)}, {cmd:e(zcovariates)} and {cmd:e(pcovariates)}: respectivelly the estimated values of the parameters associated to the covariates, the covariance matrix of the estimations, the statistics of the tests to compare the parameters to 0 and the associated p-values (only with the {cmd:covariates} option)
+
+{title:Examples}
+
+{p 4 8 2}{cmd: . raschtest item1-item9, id(id)} /*estimates the parameters by CML approach*/
+
+{p 4 8 2}{cmd: . raschtest item*, id(id) method(gee) information icc dirsave(c:\graphs) filesnames(graphs)}
+/*estimates the parameters by GEE, draw the information graph and the ICCs and
+save the graphical representations under gph files*/
+
+{p 4 8 2}{cmd: . raschtest item1 item4 item7 item 18 item23 item35-item39 , id(id) group(2 3 4 5) test(WP) split graph}
+/*creates groups of score (1 and 2, 3, 4, 5 and more) to compute the Wright
+Panchapakesan tests, computes the split test, and represent the map difficulty
+parameters/scores*/
+
+{p 4 8 2}{cmd: . matrix diff=(-1,-.5,0,.5,1)}{p_end}
+{p 4 8 2}{cmd: . raschtest item1-item5 , id(id) diff(diff) covariable(group sex age,ss1 ss3) nold}
+/*difficulties parameters are fixed, 3 covariables are introduced, no listwise deletion*/
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD-HDR, associate professor{p_end}
+{p 4 8 2}INSERM UMR 1246-SPHERE "Methods in Patients Centered Outcomes and Health Research"{p_end}
+{p 4 8 2}Nantes University - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}Intitute of Research in Health 2{p_end}
+{p 4 8 2}22 boulevard BĂ©noni-Goullin{p_end}
+{p 4 8 2}44200 Nantes - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help xtlogit}, {help clogit} and {help geekel2d} and {help gllamm} if installed.{p_end}
+
diff --git a/Modules/ado/personal/r/raschtestv787.ado b/Modules/ado/personal/r/raschtestv787.ado
new file mode 100644
index 0000000..db9efba
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv787.ado
@@ -0,0 +1,2422 @@
+*! version 8.7 28 May 2013
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+* Version 8.6 (2012-11-20) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.7 (2013-05-28) : Jean-Benoit Hardouin /*Correction of a bug in the covariates option with ss1 and ss3*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.20 (ssc describe gllamm)
+* gllapred version 2.3.8 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string)]
+
+local covariables `covariates'
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+if "`html'"!="" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local draw
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ local nbobserv=r(N)
+
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ local nbobserv=e(N)
+ *di "nombre d'obs:`nbobserv'"
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempfile Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+if "`html'" != "" {
+ di ""
+}
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ }
+ else {
+ di "Estimation method: Conditional maximum likelihood (CML)
"
+ }
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ }
+ else {
+ di "Estimation method: Marginal maximum likelihood (MML)
"
+ }
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+if "`html'" == "" {
+ di in green "Number of items: " in yellow `nbitems'
+ di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+ }
+}
+else {
+ di "Number of items: " `nbitems' "
"
+ di "Number of groups: " `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di " (`nbtest' of them are used to compute the statistics of test)"
+ }
+ di "
"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+if "`html'" == "" {
+ di in green "Number of individuals: " in yellow `N'
+ di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+ if "`ld'"=="" {
+ di in green " (removed)"
+ }
+ else {
+ di
+ }
+ di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+}
+else {
+ di "Number of individuals: `N'
"
+ di "Number of individuals with missing values: " `nbindmiss'
+ if "`ld'"=="" {
+ di " (removed)"
+ }
+ di "
"
+ di "Number of individuals with nul or perfect score: " `=`effscore0'+`effscore`nbgroups''' "
"
+}
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ }
+}
+else {
+ if "`html'" == "" {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ di
+ }
+ else {
+ di "Marginal log-likelihood: " %-13.4f `ll' "
"
+ di "Log-likelihood: " %-13.4f `globalll' ""
+ }
+}
+
+if "`html'" == "" {
+ noi di in green _col(16) "Difficulty" `conttest'
+ if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+ }
+ noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+ }
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+ di ""
+ di " | Difficulty | | "
+ if "`test'"!="NONE" {
+ di " | Standardized | "
+ }
+ di "
"
+ di "Items | parameters | std Err. | "
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di "`namewp' | df | p-value | Outfit | Infit | "
+ if "`method'"=="cml" {
+ di "U | "
+ }
+ }
+ di "
"
+}
+
+forvalues i=1/`nbitems' {
+ if "`html'" == "" {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ }
+ else {
+ di "" %12s abbrev("``i''`fixed`i''" ,12) " | " %8.5f `beta`i'' " | " %6.5f `sd`i'' " | "
+ }
+ if "`test'"!="NONE" {
+ if "`html'" == "" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ else {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfitstd`i'' " | " %6.3f `infitstd`i'' " | "
+ }
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in ye _col(72) %6.3f `U`i''
+ }
+ else {
+ di "" %6.3f `U`i'' " | "
+ }
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+ }
+}
+if "`html'" == "" {
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+}
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ if "`html'" == "" {
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+ }
+ else {
+ di "`descwp' | | `namewp'= | " %8.3f `globalfit'[1,1] " | " %3.0f `globalfit'[1,2] " | " %6.4f `globalfit'[1,3] " | | |
"
+ if "`method'"=="cml" {
+ di "Andersen LR test | | Z= | " %8.3f `AndersenZ'[1,1] " | " %3.0f `AndersenZ'[1,2] " | " %6.4f `AndersenZ'[1,3] " | | |
"
+ }
+ di "
"
+ }
+}
+
+if "`html'" == "" {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+ }
+
+ di
+}
+else {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di "*: The difficulty parameter of this item had been fixed to 0
"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di "The mean of the difficulty parameters is fixed to 0
"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di "You have groups of scores with less than 30 individuals. The tests can be invalid.
"
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test.
"
+ }
+ di ""
+}
+
+if "`html'" == "" {
+ if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+ }
+}
+else {
+ if "`method'"!="cml" {
+ di ""
+ di ""
+ di "Parameters | Coef. | std Err. | z | P>|z| |
"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di "Sigma | " %8.5f `sig' " | " %6.5f `sesig' " | " %6.3f `zsig' " | " %7.4f `pzsig' " |
"
+ }
+}
+
+
+
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=r(N_obs)
+ *di "nbobs=`nbobs'"
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di in green "{dup 85:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local nbobs=r(N_obs)
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`nbobs'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1
+ *di "local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1 (cov:`covariablesss1')"
+ local ss1`i'=`var`i''*`df`i''
+ *di "cov : `covariablesss1' var=`var`i'' df=`df`i''"
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `ss1`i'' _col(25) %12.3f `=`ss1`=`i'-1''-`ss1`i''' _col(47) %4.0f `df`i'' _col(63) %8.3f `var`i'' _col(81) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 85}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=e(N_obs)
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ local ss3ref=`=`sig'^2*(`df0'-`nbcovariables')'
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `ss3ref' _col(25) %12.3f `=`ss30'-`ss3ref'' _col(47) %4.0f `=`df0'-`nbcovariables'' _col(63) %8.3f `sig'^2 _col(81) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 85:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ *ereturn list
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local nbobs=e(N)
+ local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)
+ *di "local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)"
+ local ss3s`i'=`vars`i''*`dfs`i''
+ local vara`i'=`sig'^2
+ local dfa`i'=`nbobs'-(`nbitems'+1)-1-`nbcovariables'
+ local ss3a`i'=`vara`i''*`dfa`i''
+ *di "cov : `covariablesss3' var=`vars`i'' df=`dfs`i''"
+ di _col(2) %12s in green abbrev("`covariable`i''",12) _col(15) in ye %12.3f `ss3s`i'' _col(25) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(47) %4.0f `=`df0'-`nbcovariables'+1' _col(63) %8.3f `vars`i'' _col(80) %6.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 85}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ if "`html'" == "" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di ""
+ di ""
+ di "Group | Score | Ability parameters | std Err. | Freq. | Expected Score | "
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ di "ll | "
+ }
+ di "
"
+ }
+
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ if "`html'" == "" {
+ di in green _col(17) "{dup `line':-}"
+ }
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ if "`html'" == "" {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ }
+ else {
+ di "" %5s "`gr'" " | " %5s "`s'" " | " `format1' `theta`nonul'' " | " `format1' `sdtheta`nonul'' " | " %4.0f `nbrealscore`s'' " | " % 4.2f `expscore`nonul'' " | " %11.4f `tmp' " | "
+ }
+ local nonul=`nonul'+1
+ }
+ }
+ if "`html'" == "" {
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di "
"
+ }
+}
+
+if "`method'"=="mml"|"`method'"=="gee" {
+ if "`html'" == "" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+ }
+ else {
+ di ""
+ di ""
+ di ""
+ di "Mean variance of the error | " %10.4f `meanse2' " |
"
+ local sig2=`sig'^2
+ di "Estimated variance of the latent trait | " %10.4f `sig2' " |
"
+ local psi2=1-`meanse2'/`sig2'
+ di "Personal Separation Index (PSI) | " %10.4f `psi2' " |
"
+ di "Adjusted PSI on covariates (PSIadj) | " %10.4f `psi' " |
"
+ di "
"
+ }
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ if "`html'"=="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+ }
+ else {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di in gr ""
+ di in gr "Group: `g' from `liminf`g'' to `limsup`g'' (n=`nbscore`g'')"
+ di in gr "Item | Observed | Expected | Scaled |
"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di "``j'' | " %4.0f `Obs2'[`j',`g'] " | " %6.2f `Th2'[`j',`g'] " | " %7.4f `tmp' " |
"
+ }
+ di "Contribution to the `namewp' statistics: | " %8.4f `test`g''[1,1] " |
"
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di " | " %4.0f `nbrealscore`h'' " | " %6.2f `ci`h'' " | " %7.4f `tmp' " |
"
+ local tmp=`tmp'^2
+ di "Contribution to the `namewp' statistics: | " %8.4f `tmp' " |
"
+ }
+ di "
"
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_icc_``i''"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , `htmlregion' name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') xsize(12) ysize(9) `draw'
+ if "html"=="" {
+ pause
+ }
+ else {
+ qui graph save icc``i'' "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_icc_``i''.eps, replace
+ di ""
+
+ }
+ if "`filessave'"!="" {
+ qui graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_information"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ *set trace on
+ graph twoway (line `info' `latent') , `htmlregion' name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save information "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_information.eps, replace
+ di ""
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), `htmlregion' name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstd' `id'), `htmlregion' name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfit "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfit.eps, replace
+ }
+ qui graph save infit "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infit.eps, replace
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',`htmlregion' name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstdj' `betap',`htmlregion' name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfititem "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfititem.eps, replace
+ }
+ qui graph save infititem "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infititem.eps, replace
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_map"
+ }
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), `htmlregion' name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save graph "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_map.eps, replace
+ di ""
+ }
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+return scalar N_obs=`nbobserv'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/raschtestv7v8.10.1.ado b/Modules/ado/personal/r/raschtestv7v8.10.1.ado
new file mode 100644
index 0000000..ca3ed1c
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv7v8.10.1.ado
@@ -0,0 +1,2568 @@
+*! version 8.10.1 15july2019
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+* Version 8.6 (2012-11-20) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.7 (2013-05-28) : Jean-Benoit Hardouin /*Correction of a bug in the covariates option with ss1 and ss3*/
+* Version 8.8 (2014-02-27) : Jean-Benoit Hardouin /*Correction of a bug when the null or the parfect score have a frequency of 0 (no test)*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*png option (graphs in png), information curve by item*/
+* Version 8.10 (2019-07-05) : Jean-Benoit Hardouin /*extension option (graphs with the chosen extension) who replaces the png option, docx option*/
+* Version 8.10.1 (2019-07-15) : Jean-Benoit Hardouin /*nostand option*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.20 (ssc describe gllamm)
+* gllapred version 2.3.8 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2014 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) extension(string) GRAPHClose DOCX(string) noSTand]
+
+local covariables `covariates'
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("Graphical outputs of the raschtest module")
+}
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+if "`html'"!="" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local draw
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+if "`extension'"!=""&"`extension'"!="png"&"`extension'"!="eps"&"`extension'"!="ps"&"`extension'"!="svg"&"`extension'"!="wmf"&"`extension'"!="png"&"`extension'"!="emf"&"`extension'"!="pdf"&"`extension'"!="tif" {
+ di in red "The {hi:extension} option can not contain the value `extension'. Please correct it."
+ error 198
+ exit
+}
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ local nbobserv=r(N)
+
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ local nbobserv=e(N)
+ *di "nombre d'obs:`nbobserv'"
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=1/`=`nbgroups'-1' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempfile Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+if "`html'" != "" {
+ di ""
+}
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ }
+ else {
+ di "Estimation method: Conditional maximum likelihood (CML)
"
+ }
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ }
+ else {
+ di "Estimation method: Marginal maximum likelihood (MML)
"
+ }
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+if "`html'" == "" {
+ di in green "Number of items: " in yellow `nbitems'
+ di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+ }
+}
+else {
+ di "Number of items: " `nbitems' "
"
+ di "Number of groups: " `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di " (`nbtest' of them are used to compute the statistics of test)"
+ }
+ di "
"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+if "`html'" == "" {
+ di in green "Number of individuals: " in yellow `N'
+ di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+ if "`ld'"=="" {
+ di in green " (removed)"
+ }
+ else {
+ di
+ }
+ di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+}
+else {
+ di "Number of individuals: `N'
"
+ di "Number of individuals with missing values: " `nbindmiss'
+ if "`ld'"=="" {
+ di " (removed)"
+ }
+ di "
"
+ di "Number of individuals with nul or perfect score: " `=`effscore0'+`effscore`nbgroups''' "
"
+}
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ }
+}
+else {
+ if "`html'" == "" {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ di
+ }
+ else {
+ di "Marginal log-likelihood: " %-13.4f `ll' "
"
+ di "Log-likelihood: " %-13.4f `globalll' ""
+ }
+}
+
+if "`html'" == "" {
+ noi di in green _col(16) "Difficulty" `conttest'
+ if "`test'"!="NONE"&"`stand'"=="" {
+ di in green _col(58) "Standardized"
+ }
+ if "`test'"!="NONE"&"`stand'"!="" {
+ di
+ }
+ noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+ }
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+ di ""
+ di " | Difficulty | | "
+ if "`test'"!="NONE" {
+ di " | Standardized | "
+ }
+ di "
"
+ di "Items | parameters | std Err. | "
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di "`namewp' | df | p-value | Outfit | Infit | "
+ if "`method'"=="cml" {
+ di "U | "
+ }
+ }
+ di "
"
+}
+
+forvalues i=1/`nbitems' {
+ if "`html'" == "" {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ }
+ else {
+ di "" %12s abbrev("``i''`fixed`i''" ,12) " | " %8.5f `beta`i'' " | " %6.5f `sd`i'' " | "
+ }
+ if "`test'"!="NONE" {
+ if "`html'" == "" {
+ if "`stand'"=="" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ else {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfit`i'' _col(65) %6.3f `infit`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ }
+ else {
+ if "`stand'"=="" {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfitstd`i'' " | " %6.3f `infitstd`i'' " | "
+ }
+ else {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfit`i'' " | " %6.3f `infit`i'' " | "
+ }
+ }
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ if "`stand'"=="" {
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ }
+ else {
+ matrix `itemfit'[`i',4]=`outfit`i''
+ matrix `itemfit'[`i',5]=`infit`i''
+ }
+
+ if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in ye _col(72) %6.3f `U`i''
+ }
+ else {
+ di "" %6.3f `U`i'' " | "
+ }
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+ }
+}
+if "`html'" == "" {
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+}
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ if "`html'" == "" {
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+ }
+ else {
+ di "`descwp' | | `namewp'= | " %8.3f `globalfit'[1,1] " | " %3.0f `globalfit'[1,2] " | " %6.4f `globalfit'[1,3] " | | |
"
+ if "`method'"=="cml" {
+ di "Andersen LR test | | Z= | " %8.3f `AndersenZ'[1,1] " | " %3.0f `AndersenZ'[1,2] " | " %6.4f `AndersenZ'[1,3] " | | |
"
+ }
+ di "
"
+ }
+}
+
+if "`html'" == "" {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+ }
+
+ di
+}
+else {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di "*: The difficulty parameter of this item had been fixed to 0
"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di "The mean of the difficulty parameters is fixed to 0
"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di "You have groups of scores with less than 30 individuals. The tests can be invalid.
"
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test.
"
+ }
+ di ""
+}
+
+if "`html'" == "" {
+ if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+ }
+}
+else {
+ if "`method'"!="cml" {
+ di ""
+ di ""
+ di "Parameters | Coef. | std Err. | z | P>|z| |
"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di "Sigma | " %8.5f `sig' " | " %6.5f `sesig' " | " %6.3f `zsig' " | " %7.4f `pzsig' " |
"
+ }
+}
+
+
+
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=r(N_obs)
+ *di "nbobs=`nbobs'"
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di in green "{dup 85:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local nbobs=r(N_obs)
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`nbobs'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1
+ *di "local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1 (cov:`covariablesss1')"
+ local ss1`i'=`var`i''*`df`i''
+ *di "cov : `covariablesss1' var=`var`i'' df=`df`i''"
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `ss1`i'' _col(25) %12.3f `=`ss1`=`i'-1''-`ss1`i''' _col(47) %4.0f `df`i'' _col(63) %8.3f `var`i'' _col(81) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 85}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=e(N_obs)
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ local ss3ref=`=`sig'^2*(`df0'-`nbcovariables')'
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `ss3ref' _col(25) %12.3f `=`ss30'-`ss3ref'' _col(47) %4.0f `=`df0'-`nbcovariables'' _col(63) %8.3f `sig'^2 _col(81) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 85:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ *ereturn list
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local nbobs=e(N)
+ local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)
+ *di "local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)"
+ local ss3s`i'=`vars`i''*`dfs`i''
+ local vara`i'=`sig'^2
+ local dfa`i'=`nbobs'-(`nbitems'+1)-1-`nbcovariables'
+ local ss3a`i'=`vara`i''*`dfa`i''
+ *di "cov : `covariablesss3' var=`vars`i'' df=`dfs`i''"
+ di _col(2) %12s in green abbrev("`covariable`i''",12) _col(15) in ye %12.3f `ss3s`i'' _col(25) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(47) %4.0f `=`df0'-`nbcovariables'+1' _col(63) %8.3f `vars`i'' _col(80) %6.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 85}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ if "`html'" == "" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di ""
+ di ""
+ di "Group | Score | Ability parameters | std Err. | Freq. | Expected Score | "
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ di "ll | "
+ }
+ di "
"
+ }
+
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ if "`html'" == "" {
+ di in green _col(17) "{dup `line':-}"
+ }
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ if "`html'" == "" {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ }
+ else {
+ di "" %5s "`gr'" " | " %5s "`s'" " | " `format1' `theta`nonul'' " | " `format1' `sdtheta`nonul'' " | " %4.0f `nbrealscore`s'' " | " % 4.2f `expscore`nonul'' " | " %11.4f `tmp' " | "
+ }
+ local nonul=`nonul'+1
+ }
+ }
+ if "`html'" == "" {
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di "
"
+ }
+}
+
+if "`method'"=="mml"|"`method'"=="gee" {
+ if "`html'" == "" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+ }
+ else {
+ di ""
+ di ""
+ di ""
+ di "Mean variance of the error | " %10.4f `meanse2' " |
"
+ local sig2=`sig'^2
+ di "Estimated variance of the latent trait | " %10.4f `sig2' " |
"
+ local psi2=1-`meanse2'/`sig2'
+ di "Personal Separation Index (PSI) | " %10.4f `psi2' " |
"
+ di "Adjusted PSI on covariates (PSIadj) | " %10.4f `psi' " |
"
+ di "
"
+ }
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ if "`html'"=="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+ }
+ else {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di in gr ""
+ di in gr "Group: `g' from `liminf`g'' to `limsup`g'' (n=`nbscore`g'')"
+ di in gr "Item | Observed | Expected | Scaled |
"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di "``j'' | " %4.0f `Obs2'[`j',`g'] " | " %6.2f `Th2'[`j',`g'] " | " %7.4f `tmp' " |
"
+ }
+ di "Contribution to the `namewp' statistics: | " %8.4f `test`g''[1,1] " |
"
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di " | " %4.0f `nbrealscore`h'' " | " %6.2f `ci`h'' " | " %7.4f `tmp' " |
"
+ local tmp=`tmp'^2
+ di "Contribution to the `namewp' statistics: | " %8.4f `tmp' " |
"
+ }
+ di "
"
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_icc_``i''"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , `htmlregion' name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') xsize(12) ysize(9) `draw'
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save icc``i'' "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_icc_``i''.eps, replace
+ di ""
+
+ }
+ *set trace on
+ if "`filessave'"!="" {
+ qui graph save icc``i'' "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ graph close
+ }
+ *qui graph use `dirsave'\\icc``i''
+ qui graph export `dirsave'\\icc``i''.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ putdocx image `dirsave'\\icc``i''.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ forvalues i=1/`nbitems' {
+ tempvar info``i''
+ }
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ local gphbyitem
+ forvalues i=1/`nbitems' {
+ qui gen `info``i'''=exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ label variable `info``i''' "``i''"
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ local gphbyitem `gphbyitem' `info``i'''
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_information"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ *set trace on
+ local saving "`dirsave'\\information"
+ graph twoway (line `info' `latent') , `htmlregion' name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save information "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\information
+ qui graph export `dirsave'\\information.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\information.`extension', width(4)
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save information "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_information.eps, replace
+ di ""
+ }
+ local saving "`dirsave'\\inf_items"
+ graph twoway (line `gphbyitem' `latent') , `htmlregion' name(inf_items,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the items") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save inf_items "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\inf_items
+ qui graph export `dirsave'\\inf_items.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\inf_items.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), `htmlregion' name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstd' `id'), `htmlregion' name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfit "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfitind
+ qui graph export `dirsave'\\outfit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfit.`extension', width(4)
+ }
+
+ }
+ qui graph save infit "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infitind
+ qui graph export `dirsave'\\infit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infit.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',`htmlregion' name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstdj' `betap',`htmlregion' name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfititem "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfititem.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfititems
+ qui graph export `dirsave'\\outfititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfititems.`extension', width(4)
+ }
+ }
+ qui graph save infititem "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infititems.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infititems
+ qui graph export `dirsave'\\infititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infititems.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_map"
+ }
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), `htmlregion' name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save graph "`saving'" , `replace'
+ if "`extension'"!="" {
+ *qui graph use `dirsave'\\graph
+ qui graph export `dirsave'\\graph.`extension' , `replace'
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("In this dataset, there are `r(N)' models")
+
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\graph.`extension', width(4)
+ }
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save graph "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_map.eps, replace
+ di ""
+ }
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or more modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+return scalar N_obs=`nbobserv'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+if "`docx'"!="" {
+*set trace on
+ putdocx save "`dirsave'\\`docx'.docx", replace
+ putdocx clear
+}
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/raschtestv7v8.10.ado b/Modules/ado/personal/r/raschtestv7v8.10.ado
new file mode 100644
index 0000000..4328488
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv7v8.10.ado
@@ -0,0 +1,2547 @@
+*! version 8.10 5july2019
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+* Version 8.6 (2012-11-20) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.7 (2013-05-28) : Jean-Benoit Hardouin /*Correction of a bug in the covariates option with ss1 and ss3*/
+* Version 8.8 (2014-02-27) : Jean-Benoit Hardouin /*Correction of a bug when the null or the parfect score have a frequency of 0 (no test)*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*png option (graphs in png), information curve by item*/
+* Version 8.10 (2019-07-05) : Jean-Benoit Hardouin /*extension option (graphs with the chosen extension) who replaces the png option, docx option*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.20 (ssc describe gllamm)
+* gllapred version 2.3.8 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2014 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) extension(string) GRAPHClose DOCX(string)]
+
+local covariables `covariates'
+
+if "`docx'"!="" {
+ putdocx clear
+ putdocx begin
+ putdocx paragraph
+ putdocx text ("Graphical outputs of the raschtest module")
+}
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+if "`html'"!="" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local draw
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+if "`extension'"!=""&"`extension'"!="png"&"`extension'"!="eps"&"`extension'"!="ps"&"`extension'"!="svg"&"`extension'"!="wmf"&"`extension'"!="png"&"`extension'"!="emf"&"`extension'"!="pdf"&"`extension'"!="tif" {
+ di in red "The {hi:extension} option can not contain the value `extension'. Please correct it."
+ error 198
+ exit
+}
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ local nbobserv=r(N)
+
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ local nbobserv=e(N)
+ *di "nombre d'obs:`nbobserv'"
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=1/`=`nbgroups'-1' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempfile Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+if "`html'" != "" {
+ di ""
+}
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ }
+ else {
+ di "Estimation method: Conditional maximum likelihood (CML)
"
+ }
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ }
+ else {
+ di "Estimation method: Marginal maximum likelihood (MML)
"
+ }
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+if "`html'" == "" {
+ di in green "Number of items: " in yellow `nbitems'
+ di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+ }
+}
+else {
+ di "Number of items: " `nbitems' "
"
+ di "Number of groups: " `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di " (`nbtest' of them are used to compute the statistics of test)"
+ }
+ di "
"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+if "`html'" == "" {
+ di in green "Number of individuals: " in yellow `N'
+ di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+ if "`ld'"=="" {
+ di in green " (removed)"
+ }
+ else {
+ di
+ }
+ di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+}
+else {
+ di "Number of individuals: `N'
"
+ di "Number of individuals with missing values: " `nbindmiss'
+ if "`ld'"=="" {
+ di " (removed)"
+ }
+ di "
"
+ di "Number of individuals with nul or perfect score: " `=`effscore0'+`effscore`nbgroups''' "
"
+}
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ }
+}
+else {
+ if "`html'" == "" {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ di
+ }
+ else {
+ di "Marginal log-likelihood: " %-13.4f `ll' "
"
+ di "Log-likelihood: " %-13.4f `globalll' ""
+ }
+}
+
+if "`html'" == "" {
+ noi di in green _col(16) "Difficulty" `conttest'
+ if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+ }
+ noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+ }
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+ di ""
+ di " | Difficulty | | "
+ if "`test'"!="NONE" {
+ di " | Standardized | "
+ }
+ di "
"
+ di "Items | parameters | std Err. | "
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di "`namewp' | df | p-value | Outfit | Infit | "
+ if "`method'"=="cml" {
+ di "U | "
+ }
+ }
+ di "
"
+}
+
+forvalues i=1/`nbitems' {
+ if "`html'" == "" {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ }
+ else {
+ di "" %12s abbrev("``i''`fixed`i''" ,12) " | " %8.5f `beta`i'' " | " %6.5f `sd`i'' " | "
+ }
+ if "`test'"!="NONE" {
+ if "`html'" == "" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ else {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfitstd`i'' " | " %6.3f `infitstd`i'' " | "
+ }
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in ye _col(72) %6.3f `U`i''
+ }
+ else {
+ di "" %6.3f `U`i'' " | "
+ }
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+ }
+}
+if "`html'" == "" {
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+}
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ if "`html'" == "" {
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+ }
+ else {
+ di "`descwp' | | `namewp'= | " %8.3f `globalfit'[1,1] " | " %3.0f `globalfit'[1,2] " | " %6.4f `globalfit'[1,3] " | | |
"
+ if "`method'"=="cml" {
+ di "Andersen LR test | | Z= | " %8.3f `AndersenZ'[1,1] " | " %3.0f `AndersenZ'[1,2] " | " %6.4f `AndersenZ'[1,3] " | | |
"
+ }
+ di "
"
+ }
+}
+
+if "`html'" == "" {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+ }
+
+ di
+}
+else {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di "*: The difficulty parameter of this item had been fixed to 0
"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di "The mean of the difficulty parameters is fixed to 0
"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di "You have groups of scores with less than 30 individuals. The tests can be invalid.
"
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test.
"
+ }
+ di ""
+}
+
+if "`html'" == "" {
+ if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+ }
+}
+else {
+ if "`method'"!="cml" {
+ di ""
+ di ""
+ di "Parameters | Coef. | std Err. | z | P>|z| |
"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di "Sigma | " %8.5f `sig' " | " %6.5f `sesig' " | " %6.3f `zsig' " | " %7.4f `pzsig' " |
"
+ }
+}
+
+
+
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=r(N_obs)
+ *di "nbobs=`nbobs'"
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di in green "{dup 85:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local nbobs=r(N_obs)
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`nbobs'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1
+ *di "local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1 (cov:`covariablesss1')"
+ local ss1`i'=`var`i''*`df`i''
+ *di "cov : `covariablesss1' var=`var`i'' df=`df`i''"
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `ss1`i'' _col(25) %12.3f `=`ss1`=`i'-1''-`ss1`i''' _col(47) %4.0f `df`i'' _col(63) %8.3f `var`i'' _col(81) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 85}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=e(N_obs)
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ local ss3ref=`=`sig'^2*(`df0'-`nbcovariables')'
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `ss3ref' _col(25) %12.3f `=`ss30'-`ss3ref'' _col(47) %4.0f `=`df0'-`nbcovariables'' _col(63) %8.3f `sig'^2 _col(81) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 85:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ *ereturn list
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local nbobs=e(N)
+ local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)
+ *di "local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)"
+ local ss3s`i'=`vars`i''*`dfs`i''
+ local vara`i'=`sig'^2
+ local dfa`i'=`nbobs'-(`nbitems'+1)-1-`nbcovariables'
+ local ss3a`i'=`vara`i''*`dfa`i''
+ *di "cov : `covariablesss3' var=`vars`i'' df=`dfs`i''"
+ di _col(2) %12s in green abbrev("`covariable`i''",12) _col(15) in ye %12.3f `ss3s`i'' _col(25) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(47) %4.0f `=`df0'-`nbcovariables'+1' _col(63) %8.3f `vars`i'' _col(80) %6.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 85}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ if "`html'" == "" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di ""
+ di ""
+ di "Group | Score | Ability parameters | std Err. | Freq. | Expected Score | "
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ di "ll | "
+ }
+ di "
"
+ }
+
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ if "`html'" == "" {
+ di in green _col(17) "{dup `line':-}"
+ }
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ if "`html'" == "" {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ }
+ else {
+ di "" %5s "`gr'" " | " %5s "`s'" " | " `format1' `theta`nonul'' " | " `format1' `sdtheta`nonul'' " | " %4.0f `nbrealscore`s'' " | " % 4.2f `expscore`nonul'' " | " %11.4f `tmp' " | "
+ }
+ local nonul=`nonul'+1
+ }
+ }
+ if "`html'" == "" {
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di "
"
+ }
+}
+
+if "`method'"=="mml"|"`method'"=="gee" {
+ if "`html'" == "" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+ }
+ else {
+ di ""
+ di ""
+ di ""
+ di "Mean variance of the error | " %10.4f `meanse2' " |
"
+ local sig2=`sig'^2
+ di "Estimated variance of the latent trait | " %10.4f `sig2' " |
"
+ local psi2=1-`meanse2'/`sig2'
+ di "Personal Separation Index (PSI) | " %10.4f `psi2' " |
"
+ di "Adjusted PSI on covariates (PSIadj) | " %10.4f `psi' " |
"
+ di "
"
+ }
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ if "`html'"=="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+ }
+ else {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di in gr ""
+ di in gr "Group: `g' from `liminf`g'' to `limsup`g'' (n=`nbscore`g'')"
+ di in gr "Item | Observed | Expected | Scaled |
"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di "``j'' | " %4.0f `Obs2'[`j',`g'] " | " %6.2f `Th2'[`j',`g'] " | " %7.4f `tmp' " |
"
+ }
+ di "Contribution to the `namewp' statistics: | " %8.4f `test`g''[1,1] " |
"
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di " | " %4.0f `nbrealscore`h'' " | " %6.2f `ci`h'' " | " %7.4f `tmp' " |
"
+ local tmp=`tmp'^2
+ di "Contribution to the `namewp' statistics: | " %8.4f `tmp' " |
"
+ }
+ di "
"
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_icc_``i''"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , `htmlregion' name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') xsize(12) ysize(9) `draw'
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save icc``i'' "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_icc_``i''.eps, replace
+ di ""
+
+ }
+ *set trace on
+ if "`filessave'"!="" {
+ qui graph save icc``i'' "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ graph close
+ }
+ *qui graph use `dirsave'\\icc``i''
+ qui graph export `dirsave'\\icc``i''.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ putdocx image `dirsave'\\icc``i''.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ forvalues i=1/`nbitems' {
+ tempvar info``i''
+ }
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ local gphbyitem
+ forvalues i=1/`nbitems' {
+ qui gen `info``i'''=exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ label variable `info``i''' "``i''"
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ local gphbyitem `gphbyitem' `info``i'''
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_information"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ *set trace on
+ local saving "`dirsave'\\information"
+ graph twoway (line `info' `latent') , `htmlregion' name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save information "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\information
+ qui graph export `dirsave'\\information.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\information.`extension', width(4)
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save information "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_information.eps, replace
+ di ""
+ }
+ local saving "`dirsave'\\inf_items"
+ graph twoway (line `gphbyitem' `latent') , `htmlregion' name(inf_items,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the items") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save inf_items "`saving'" , `replace'
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\inf_items
+ qui graph export `dirsave'\\inf_items.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\inf_items.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), `htmlregion' name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstd' `id'), `htmlregion' name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfit "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfitind
+ qui graph export `dirsave'\\outfit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfit.`extension', width(4)
+ }
+
+ }
+ qui graph save infit "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infit.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infitind
+ qui graph export `dirsave'\\infit.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infit.`extension', width(4)
+ }
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',`htmlregion' name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstdj' `betap',`htmlregion' name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfititem "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfititem.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\outfititems
+ qui graph export `dirsave'\\outfititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\outfititems.`extension', width(4)
+ }
+ }
+ qui graph save infititem "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infititems.eps, replace
+ }
+ if "`extension'"!="" {
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+ *qui graph use `dirsave'\\infititems
+ qui graph export `dirsave'\\infititems.`extension', `replace'
+ if "`docx'"!="" {
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\infititems.`extension', width(4)
+ }
+
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_map"
+ }
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), `htmlregion' name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ qui graph save graph "`saving'" , `replace'
+ if "`extension'"!="" {
+ *qui graph use `dirsave'\\graph
+ qui graph export `dirsave'\\graph.`extension' , `replace'
+ if "`docx'"!="" {
+ putdocx paragraph
+ putdocx text ("In this dataset, there are `r(N)' models")
+
+ putdocx paragraph, halign(center)
+ qui putdocx image `dirsave'\\graph.`extension', width(4)
+ }
+ if "`graphclose'"!="" {
+ qui graph close
+ }
+
+ }
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save graph "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_map.eps, replace
+ di ""
+ }
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or more modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+return scalar N_obs=`nbobserv'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+if "`docx'"!="" {
+*set trace on
+ putdocx save "`dirsave'\\`docx'.docx", replace
+ putdocx clear
+}
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/raschtestv7v88.ado b/Modules/ado/personal/r/raschtestv7v88.ado
new file mode 100644
index 0000000..228b5a3
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv7v88.ado
@@ -0,0 +1,2423 @@
+*! version 8.8 27 Februar 2014
+*! Jean-Benoit Hardouin
+*************************************************************************************************************
+* Raschtestv7: Rasch model, fit tests and graphical representations
+* Corresponds to the version 8 of Raschtest (http://freeirt.org) for Stata7
+*
+* Historic:
+* Version 2.1 (2003-07-10): Jean-Benoit Hardouin
+* Version 3.1 (2004-01-02) : Jean-Benoit Hardouin
+* Version 7.1 (2005-03-30) : Jean-Benoit Hardouin
+* Version 7.2.1 (2005-05-21) : Jean-Benoit Hardouin
+* Version 7.3.1 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.3.2 (2005-10-05) : Jean-Benoit Hardouin /*correction for the *genlt* option with *method(cml)**/
+* Version 7.3.3 (2005-12-21) : Jean-Benoit Hardouin /*correction if scores are not represented with method(mml) or method(gee)*/
+* Version 7.4.1 (2006-01-17) : Jean-Benoit Hardouin /*Standardized OUTFIT and INFIT, DIF option*/
+* Version 7.4.2 (2006-03-21) : Jean-Benoit Hardouin /*Avoids a bug when the temporary files are saved in a directory containing special characters*/
+* Version 7.4.3 (2006-11-15) : Jean-Benoit Hardouin /*Avoids a bug when the directory defined in the dirsave option contains special characters*/
+* Version 7.5.1 (2007-04-20) : Jean-Benoit Hardouin /*Return results of the comp option*/
+* Version 7.6.1 (2008-06-26) : Jean-Benoit Hardouin /*Nold option, corrects a bug with the genlt option*/
+* Version 7.6.2 (2009-03-01) : Jean-Benoit Hardouin /*Correction of the SE of the latent trait, graph option, correction of a bug with the if option, PSI in MML*/
+* Version 8.1 (2009-06-24) : Jean-Benoit Hardouin /*DIFFICULTIES option, COVARIATES option*/
+* Version 8.2 (2009-07-15) : Jean-Benoit Hardouin /*Correction of a bug with CML*/
+* Version 8.3 (2009-12-19) : Jean-Benoit Hardouin /*correction of a bug with DIFFICULTIES and COVARIATES options together*/
+* Version 8.4 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option */
+* Version 8.5 (2011-12-20) : Jean-Benoit Hardouin /*Correction for the ss1 and ss3 suboptions of the COVARIATES option */
+* Version 8.6 (2012-11-20) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.7 (2013-05-28) : Jean-Benoit Hardouin /*Correction of a bug in the covariates option with ss1 and ss3*/
+* Version 8.8 (2014-02-27) : Jean-Benoit Hardouin /*Correction of a bug when the null or the parfect score have a frequency of 0 (no test)*/
+*
+* Needed modules :
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.20 (ssc describe gllamm)
+* gllapred version 2.3.8 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2014 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+DEFINITION / SYNTAX
+***********************************************************************************************************/
+
+
+program define raschtestv7,rclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GENRES(string) GRAph v8 COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string)]
+
+local covariables `covariates'
+
+if "`if'"=="" {
+ local if "if 1"
+}
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Tests of conformity"
+}
+if "`v8'"=="" {
+ version 7.0
+}
+else {
+ version 8.0
+}
+if "`html'"!="" {
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local draw
+}
+
+local st = "$S_TIME"
+local nbitems : word count `varlist'
+marksample touse ,novarlist
+if "`covariables'"!="" {
+ tokenize "`covariables'",parse(" ,")
+ local i=1
+ local tcovariables
+ while "``i''"!=","&"``i''"!="" {
+ local covariable`i' ``i''
+ local tcovariables `tcovariables' ``i''
+ local ++i
+ }
+ local nbcovariables=`i'-1
+ local ss1
+ local ss3
+ if "``i''"=="," {
+ forvalues j=`=`i'+1'/`=`i'+2' {
+ if "``j''"=="ss1" {
+ local ss1 ss1
+ }
+ else if "``j''"=="ss3" {
+ local ss3 ss3
+ }
+ else if "``j''"=="" {
+* di in green "option `j' vide"
+ }
+ else {
+ di in red "Invalid option in the {hi:covariables} option"
+ error 198
+ }
+ }
+ local i=`i'+3
+ if "``i''"!="" {
+ di in red "There is too much options in the {hi:covariates} option."
+ error 198
+ }
+ }
+ local covariables `tcovariables'
+}
+else {
+ local nbcovariables=0
+}
+
+isid `id'
+tokenize `varlist'
+
+local bad
+forvalues i=1/`nbitems' {
+ qui count if ``i''!=0&``i''!=1&``i''!=.
+ local N=r(N)
+ if `N'>0 {
+ local bad `bad' ``i''
+ }
+}
+if "`bad'"!="" {
+ di in red "The item(s) {hi:`bad'} is(are) not binary item(s) (with responses 0 or 1)."
+ exit
+}
+
+
+
+if "`method'"=="" {
+ local method cml
+}
+if "`test'"=="" {
+ local test R
+}
+local method=lower("`method'")
+local test=upper("`test'")
+if "`method'"!="mml"&"`method'"!="cml"&"`method'"!="gee" {
+ di in red "Uncorrect method option."
+ error 198
+ exit
+}
+
+if "`test'"!="R"&"`test'"!="Q"&"`test'"!="WP"&"`test'"!="NONE" {
+ di in red "Uncorrect test option."
+ error 198
+ exit
+}
+
+if "`genfit'"!="" {
+ local nbwordgenfit:word count `genfit'
+ if `nbwordgenfit'!=2 {
+ di in red "Uncorrect genfit option."
+ di in red "This option must contain exactly two words"
+ error 198
+ exit
+ }
+}
+
+
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!=""|"`genres'"!="" {
+ capture confirm new variable `genfit' `genscore' `genres'
+ if "`genfit'"!="" {
+ local o:word 1 of `genfit'
+ forvalues i=1/`nbitems' {
+ confirm new variable `o'``i''
+ }
+ }
+ if "`genlt'"!="" {
+ local 0 `genlt'
+ gettoken left 0: 0,parse(",")
+ gettoken right 0: 0,parse(",")
+ local genlt `left'
+ local replacegenlt `0'
+ local length=length("`replacegenlt'")
+ if `length'>=3&substr("`replacegenlt'",1,`length')==substr("replace",1,`length') {
+ local replacegenlt replace
+ }
+ if "`replacegenlt'"!="replace"&"`replacegenlt'"!="" {
+ di "Not allowed option in the {hi:genlt} option"
+ error 198
+ }
+ else if "`replacegenlt'"=="" {
+ confirm new variable `genlt'
+ }
+ }
+}
+
+preserve
+
+tempfile saveraschtest
+qui save `saveraschtest'
+qui keep if `touse'==1
+
+if "`autogroup'"!=""&"`group'"!="" {
+ di in green "The autogroup and the group options cannot be defined in the same time"
+ di in green "Only the group option is retained."
+ local autogroup
+}
+
+if "`autogroup'"!="" {
+ tempvar autoscore
+ qui genscore `varlist',score(`autoscore')
+
+ tempname matscore tmp
+ matrix `matscore'=J(`=`nbitems'-1',3,0)
+ forvalues i=1/`=`nbitems'-1' {
+ matrix `matscore'[`i',1]=`i'
+ matrix `matscore'[`i',2]=`i'
+ qui count if `autoscore'==`i'
+ matrix `matscore'[`i',3]=r(N)
+ }
+ local stop=0
+ local j=0
+ while `j'<=`=`nbitems'-3'&`stop'!=1 {
+ local j=`j'+1
+ local scoretogroup=99999999
+ local rowtogroup1=0
+ local rowtogroup2=0
+ local stop=1
+ forvalues i=1/`=`nbitems'-`j'' {
+ if `matscore'[`i',1]>=0 & `matscore'[`i',3]<30 & `matscore'[`i',3]<`scoretogroup' {
+ local scoretogroup=`matscore'[`i',3]
+ local rowtogroup1=`i'
+ local stop=0
+ }
+ }
+ if `stop'!=1 {
+ if `rowtogroup1'>1&`rowtogroup1'<`=`nbitems'-`j'' {
+ if `matscore'[`=`rowtogroup1'-1',1]<`matscore'[`=`rowtogroup1'+1',1] {
+ local rowtogroup2=`rowtogroup1'
+ local rowtogroup1=`rowtogroup1'-1
+ }
+ else {
+ local rowtogroup2=`rowtogroup1'+1
+ }
+ }
+ else if `rowtogroup1'==1 {
+ local rowtogroup2=2
+ }
+ else if `rowtogroup1'==`=`nbitems'-`j'' {
+ local rowtogroup2=`nbitems'-`j'
+ local rowtogroup1=`nbitems'-`j'-1
+ }
+ matrix `tmp'=`matscore'
+ matrix `matscore'=J(`=`nbitems'-`j'',3,0)
+ if `rowtogroup1'!=1 {
+ matrix `matscore'[1,1]=`tmp'[1..`=`rowtogroup1'-1',1..3]
+ }
+ matrix `matscore'[`rowtogroup1',1]=`tmp'[`rowtogroup1',1]
+ matrix `matscore'[`rowtogroup1',2]=`tmp'[`rowtogroup2',2]
+ matrix `matscore'[`rowtogroup1',3]=`tmp'[`rowtogroup1',3]+`tmp'[`rowtogroup2',3]
+ if `rowtogroup2'!=`=`nbitems'-`j'' {
+ matrix `matscore'[`rowtogroup2',1]=`tmp'[`=`rowtogroup2'+1'..`=`nbitems'-`j'',1..3]
+ }
+ }
+ }
+ local nbrows=rowsof(`matscore')-1
+ local thresholds
+ forvalues i=1/`nbrows' {
+ local tmp=`matscore'[`i',2]
+ local thresholds `thresholds' `tmp'
+ }
+ local group `thresholds'
+}
+
+
+if "`group'"=="" {
+ forvalues i=1/`=`nbitems'-1' {
+ local group "`group' `i'"
+ }
+}
+local nbgroups:word count `group'
+local groupmax:word `nbgroups' of `group'
+if `groupmax'>=`nbitems' {
+ di in red "You cannot form a group with the higher possible score."
+ di in red "The higher possible value of the group option is `=`nbitems'-1'."
+ di in red "Please correct your group option."
+ error 198
+ exit
+}
+else {
+ if `groupmax'!=`=`nbitems'-1' {
+ local group "`group' `=`nbitems'-1'"
+ local nbgroups=`nbgroups'+1
+ }
+}
+local nbgroups=`nbgroups'+1
+
+if "`dirsave'"!=""&"`filessave'"=="" {
+ di in ye "If you want to save yours graphs, use the filessave option"
+}
+if "`filessave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave "`c(pwd)'"
+ }
+ di in ye "The graphs files will be saved in `dirsave'"
+}
+if "`dirsave'"!="" {
+ if "`filesave'"=="" {
+ local filesave "filesave"
+ }
+}
+
+
+if "`pause'"!=""&"`draw'"=="" {
+ pause on
+}
+
+if "`difficulties'"!="" {
+ capture confirm matrix `difficulties'
+ if _rc!=0 {
+ di in red "The vector `difficulties' defined in the {hi:difficulties} option does not exist."
+ error 198
+ exit
+ }
+}
+
+if "`difficulties'"!=""&"`method'"!="mml" {
+ di in red "The {hi:difficulties} option can be defined only for MML method."
+ error 198
+ exit
+}
+
+if "`covariables'"!=""&"`method'"!="mml" {
+ di in red "The {hi:covariables} option can be defined only for MML method."
+ error 198
+ exit
+}
+if "`covariables'"!=""&"`comp'"!="" {
+ di in red "The {hi:covariables} and {hi:comp} options can be defined jointly."
+ error 198
+ exit
+}
+
+
+
+
+
+/***********************************************************************************************************
+POSSIBLE TEST
+***********************************************************************************************************/
+
+if ("`icc'"!=""|"`fitgraph'"!=""|"`splittest'"!=""|"`details'"!="")&"`test'"=="NONE" {
+ di in green "You cannot use the {hi:details}, {hi:icc}, {hi:fitgraph} or {hi:splittest} options if you use {hi:test(none)}."
+ di in green "These options are ignored."
+ local details
+ local icc
+ local fitgraph
+ local splittest
+}
+if "`comp'"!=""&"`method'"=="cml" {
+ di in green "You cannot compare two populations ({hi:comp} option) with the CML estimation method"
+ di in green "This option is ignored."
+ local comp
+}
+if "`method'"!="cml"&"`test'"=="WP" {
+ di in green "The Wright-Panchapakesan test is not authorized with MML or GEE."
+ di in green "The WP tests are replaced by Van den Wollenberg Q tests."
+ local test Q
+}
+if "`method'"=="gee"&"`ld'"!="" {
+ di in green "You cannot use the {hi:nold} option with the GEE method of estimation"
+ di in green "This option is ignored."
+ local ld
+}
+
+
+if "`test'"==""|"`test'"=="R" {
+ local test "R"
+ if "`method'"=="cml" {
+ local namewp "R1c"
+ local descwp "R1c test"
+ }
+ else {
+ local namewp="R1m"
+ local descwp "R1m test"
+ }
+}
+if `nbitems'>999999|"`test'"=="WP" {
+ local namewp " Y"
+ local descwp "Wright-Panchapakesan Y test"
+ local q2
+}
+ else if "`test'"=="Q" {
+ local namewp " Q1"
+ local descwp "Van den Wollenberg Q1 test"
+}
+
+if "`method'"!="cml"&"`meandiff'"!="" {
+ di in green "The {hi:meandiff} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local meandiff
+}
+
+if "`method'"!="cml"&"`splittests'"!="" {
+ di in green "The {hi:splittests} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local splittests
+}
+if "`method'"!="cml"&"`dif'"!="" {
+ di in green "The {hi:dif} option is not available with MML or GEE."
+ di in green "This option is ignored."
+ local dif
+}
+
+/***********************************************************************************************************
+SCORES AND GROUPS
+************************************************************************************************************/
+
+qui count if `touse'==1
+local N=r(N)
+
+qui keep `varlist' `comp' `covariables' `id' `touse'
+
+tempname rep item
+tempvar score realscore
+qui genscore `varlist',score(`score')
+qui count if `score'==.&`touse'==1
+local nbindmiss=r(N)
+
+if "`ld'"=="" {
+ qui drop if `score'==.
+}
+forvalues i=1/`nbitems' {
+ rename ``i'' `rep'`i'
+}
+
+
+
+local liminf0=0
+local limsup0=0
+local liminf`nbgroups'=`nbitems'
+local limsup`nbgroups'=`nbitems'
+
+
+local recode
+forvalues i=1/`=`nbgroups'-1' {
+ if `i'!= 1{
+ local liminf`i' : word `=`i'-1' of `group'
+ }
+ else {
+ local liminf1=0
+ }
+ local liminf`i'=`liminf`i''+1
+ local limsup`i':word `i' of `group'
+
+ local recode "`recode' `liminf`i''/`limsup`i''=`i'"
+}
+qui gen `realscore'=`score'
+qui recode `score' `recode' `nbitems'=`nbgroups'
+
+local smallgroup=0
+
+forvalues i=0/`nbgroups' {
+ qui count if `score'==`i'
+ local effscore`i'=r(N)
+ if `i'!=0&`i'!=`nbgroups'&`effscore`i''<30 {
+ local smallgroup=1
+ }
+}
+/***********************************************************************************************************
+ESTIMATION OF THE DIFFICULTY PARAMETERS
+************************************************************************************************************/
+if "`trace'"!="" {
+ di in green "*** Estimation of the difficulty parameters"
+}
+
+
+if "`covariables'"!=""&"`difficulties'"=="" {
+ forvalues i=1/`nbcovariables' {
+ qui su `covariable`i''
+ local mean`covariable`i''=r(mean)
+ qui replace `covariable`i''=`covariable`i''-`mean`covariable`i'''
+ }
+}
+
+tempname ll coef var beta Vbeta est
+
+if "`method'"=="gee" {
+ qui geekel2d `rep'1-`rep'`nbitems',ll
+ local nbobserv=r(N)
+
+ if `r(error)'==1 {
+ di "The variance of the latent trait probably is too high to made the GEE a efficient method to estimate the parameters."
+ error 499
+ exit
+ }
+ scalar `ll'=r(ll)
+ local nbind=r(N)
+ matrix `coef'=r(b)
+ matrix `est'=`coef'
+ matrix `est'[1,`=`nbitems'+1']=sqrt(`est'[1,`=`nbitems'+1'])
+ matrix `var'=r(V)
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ local sig=sqrt(`coef'[1,`=`nbitems'+1'])
+ local sesig=sqrt(`var'[`=`nbitems'+1',`=`nbitems'+1'])/sqrt(`nbind')/(`sig'*2)
+}
+
+qui reshape long `rep', i(`id') j(`item')
+
+tempvar diff tl
+gen `diff'=0
+
+forvalues i=1/`nbitems' {
+ qui gen `rep'`i'=`item'==`i'
+ qui replace `rep'`i'=-`rep'`i'
+}
+
+
+if "`method'"=="mml" {
+ if "`difficulties'"==""{
+ qui xtlogit `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') nocons iterate(`iterate')
+ matrix `est'=e(b)
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`est'[1,`=`nbitems'+`nbcovariables'+1']/2)
+ }
+ else {
+ tempname offset b
+ qui gen `offset'=0
+ forvalues i=1/`nbitems' {
+ qui replace `offset'=-(`difficulties'[1,`i']) if `item'==`i'
+ }
+ qui gllamm `rep' `covariables' , offset(`offset') i(`id') nocons iterate(`iterate') link(logit) fam(bin)
+ matrix `b'=e(b)
+ matrix `est'=`difficulties',`b'
+ matrix `est'[1,`=`nbitems'+`nbcovariables'+1']=exp(`b'[1,`=`nbcovariables'+1']/2)
+ }
+}
+else if "`method'"=="cml" {
+ qui clogit `rep' `rep'1-`rep'`=`nbitems'-1' , group(`id')
+}
+
+
+if "`method'"!="gee" {
+ if "`difficulties'"=="" {
+ matrix `coef'=e(b)
+ matrix `var'=e(V)
+ }
+ else {
+ matrix `coef'=`difficulties'
+ matrix `var'=J(`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1',.)
+ matrix `var'[`=`nbitems'+1',`=`nbitems'+1']=e(V)
+ }
+ scalar `ll'=e(ll)
+ local nbind=e(N)/`nbitems'
+ local nbobserv=e(N)
+ *di "nombre d'obs:`nbobserv'"
+
+ if "`meandiff'"!="" {
+ matrix `var'=J(`nbitems',`nbitems',.)
+ matrix `coef'=J(1,`nbitems',.)
+ local param
+ local lin `rep'1
+ forvalues j=2/`=`nbitems'-1' {
+ local lin `lin'+`rep'`j'
+ }
+ local lin (`lin')/`nbitems'
+
+ forvalues j=1/`=`nbitems'-1' {
+ qui lincom `rep'`j'-`lin'
+ matrix `coef'[1,`j']=`r(estimate)'
+ matrix `var'[`j',`j']=`r(se)'^2
+ }
+ qui lincom -`lin'
+ matrix `coef'[1,`nbitems']=`r(estimate)'
+ matrix `var'[`nbitems',`nbitems']=`r(se)'^2
+ }
+ if "`method'"=="mml" {
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ tempname betacov Vbetacov
+ if "`difficulties'"=="" {
+ matrix `beta'=`coef'[1,1..`nbitems']
+ matrix `Vbeta'=`var'[1..`nbitems',1..`nbitems']
+ if "`covariables'"!="" {
+ matrix `betacov'=`coef'[1,`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ matrix `Vbetacov'=`var'[`=`nbitems'+1'..`=`nbitems'+`nbcovariables'',`=`nbitems'+1'..`=`nbitems'+`nbcovariables'']
+ }
+ local sig=e(sigma_u)
+ local sesig=sqrt(`var'[`=`nbitems'+`nbcovariables'+1',`=`nbitems'+`nbcovariables'+1'])*`sig'/2
+ }
+ else {
+ tempname tmp
+ matrix `tmp'=e(b)
+ matrix `beta'=`difficulties'
+ if "`covariables'"!="" {
+ matrix `betacov'=`tmp'[1,1..`nbcovariables']
+ }
+ local sig=`tmp'[1,`=`nbcovariables'+1']
+ matrix `tmp'=e(V)
+ local sesig=sqrt(`tmp'[`=`nbcovariables'+1',`=`nbcovariables'+1'])
+ matrix `Vbeta'=J(`nbitems',`nbitems',.)
+ if "`covariables'"!="" {
+ matrix `Vbetacov'=`tmp'[1..`nbcovariables',1..`nbcovariables']
+ }
+ }
+ }
+ else if "`method'"=="cml"&"`meandiff'"==""{
+ matrix `beta'=`coef'[1,1..`=`nbitems'-1']
+ matrix `Vbeta'=`var'[1..`=`nbitems'-1',1..`=`nbitems'-1']
+ }
+ else if "`method'"=="cml"&"`meandiff'"!=""{
+ matrix `beta'=`coef'
+ matrix `Vbeta'=`var'
+ }
+}
+
+if ("`method'"=="mml"|"`method'"=="gee") {
+ local colnames
+ forvalues i=1/`nbitems' {
+ local colnames "`colnames' `rep':`rep'`i'"
+ }
+ forvalues i=1/`nbcovariables'{
+ local tmp:word `i' of `covariables'
+ local colnames "`colnames' `rep':`tmp'"
+ }
+ local id2=substr("`id'",1,4)
+ local colnames "`colnames' `id2'1:_cons"
+ matrix colnames `est'=`colnames'
+
+ qui gllamm `rep' `rep'1-`rep'`nbitems' `covariables', i(`id') allc nocons family(binom) link(logit) trace from(`est') eval
+ tempname u
+ qui gllapred `u',u fsample
+
+ forvalues i=1/`nbcovariables' {
+ local tmp:word `i' of `covariables'
+ qui replace `u'm1=`u'm1+`betacov'[1,`i']*(`tmp')/*+`mean`covariable`i''')*/
+ }
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',0)
+ qui su `u'm1 if `rep'1==-1
+ local vartheta=r(Var)
+ qui gen `u's2=`u's1^2
+ qui su `u's2 if `rep'1==-1
+ local meanse2=r(mean)
+ local psi=1-`meanse2'/(`meanse2'+`vartheta')
+ forvalues s=0/`nbitems' {
+ qui su `u'm1 if `realscore'==`s'
+ local theta`s'=r(mean)
+ qui su `u's1 if `realscore'==`s'
+ local sdtheta`s'=r(mean)
+ matrix `theta'[1,`=`s'+1']=`theta`s''
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=`sdtheta`s''
+ }
+ if "`genlt'"!="" {
+ tempfile ltsave ltsavetmp
+ qui save `ltsavetmp', replace
+ qui keep if `rep'1==-1
+ qui keep `u'm1 `u's1 `id'
+ qui sort `id'
+ qui save `ltsave'
+ qui use `ltsavetmp'
+ }
+}
+
+forvalues i=1/`nbitems' {
+ if `i'==`nbitems'&"`method'"=="cml"&"`meandiff'"=="" {
+ local beta`i'=0
+ local sd`i' .
+ local fixed`i' "*"
+ }
+ else {
+ local beta`i'=`coef'[1,`i']
+ local sd`i'=sqrt(`var'[`i',`i'])
+ }
+ qui replace `diff'=-`beta`i'' if `item'==`i'
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATIONS
+***********************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ if "`trace'"!="" {
+ di in green "*** Test of comparison of two populations"
+ }
+ qui inspect `comp'
+ local unique=r(N_unique)
+ if `unique'== 2 {
+ qui su `comp'
+ local mincomp=r(min)
+ local maxcomp=r(max)
+ tempname bmin bmax
+ qui xtlogit `rep' if `comp'==`mincomp',offset(`diff') i(`id')
+ matrix `bmin'=e(b)
+ local meanmin=`bmin'[1,1]
+ local varmin=e(sigma_u)^2
+ local llmin=e(ll)
+ local Nmin=e(N_g)
+ qui xtlogit `rep' if `comp'==`maxcomp',offset(`diff') i(`id')
+ matrix `bmax'=e(b)
+ local meanmax=`bmax'[1,1]
+ local varmax=e(sigma_u)^2
+ local llmax=e(ll)
+ local Nmax=e(N_g)
+ local Zcomp=(`meanmin'-`meanmax')/sqrt(`varmin'/`Nmin'+`varmax'/`Nmax')
+ local pvalue=1-norm(abs(`Zcomp'))
+ }
+ else {
+ di "It is impossible to compare more than two populations"
+ di "The comparison process is not run"
+ local comp
+ }
+}
+
+/***********************************************************************************************************
+ESTIMATION OF THE ABILITY PARAMETERS / CML
+************************************************************************************************************/
+if `nbitems'>=2 {
+ if "`trace'"!="" {
+ di in green "*** Estimation of the ability parameters"
+ }
+ if "`method'"=="cml" {
+ tempfile verytmp
+ qui save `verytmp',replace
+ drop _all
+ qui set obs 20001
+ qui gen theta=(_n-10001)/1000
+ qui gen A=1
+ forvalues j=1/`nbitems' {
+ qui gen u`j'=exp(theta-`beta`j'')
+ qui gen p`j'=u`j'/(1+u`j')
+ qui gen a`j'=1/u`j'
+ qui replace A=A*a`j'
+ qui gen i`j'=u`j'/(1+u`j')^2
+ qui gen j`j'=(u`j'*(1-u`j'))/(1+u`j')^3
+ }
+ qui egen P=rsum(p*)
+ qui egen I=rsum(i*)
+ qui egen J=rsum(j*)
+ qui gen V=1/I^2*(I+J^2)/(4*I^2)
+ qui gen V2=1/I
+ tempname theta sdtheta
+ matrix `theta'=J(1,`=`nbitems'+1',0)
+ matrix `sdtheta'=J(`=`nbitems'+1',`=`nbitems'+1',.)
+ forvalues s=0/`nbitems' {
+ qui gen f`s'=abs(`s'-P+.5*J/I)
+ qui sort f`s'
+ matrix `theta'[1,`=`s'+1']=theta[1]
+ matrix `sdtheta'[`=`s'+1',`=`s'+1']=sqrt(V2[1])
+ }
+ use "`verytmp'",replace
+ }
+ qui gen `tl'=0
+ forvalues s=0/`nbitems' {
+ local theta`s'=`theta'[1,`=`s'+1']
+ qui replace `tl'=`theta`s'' if `realscore'==`s'
+ local sdtheta`s'=`sdtheta'[`=`s'+1',`= `s'+1']
+ }
+ tempname pred
+ qui gen `pred'=log(exp(`rep'*(`tl'+`diff'))/(1+exp(`tl'+`diff')))
+
+ qui su `pred'
+ local globalll=r(sum)
+
+ local nulscore=0
+ forvalues i=1/`=`nbgroups'-1' {
+ qui count if `score'==`i'&`item'==1
+ local nbscore`i'=r(N)
+ if `nbscore`i''==0 {
+ local nulscore=1
+ }
+ }
+ if `nulscore' {
+ di in green "{p}At least one group of scores concerns none individuals. Tests will be not computed.{p_end}"
+ di in green "{p}Use the {hi:group} or the {hi:autogroup} options.{p_end}"
+ local test "NONE"
+ local details
+ local icc
+ local fitgraph
+ local splittest
+ }
+ forvalues i=0/`nbitems' {
+ qui count if `realscore'==`i'&`item'==1
+ local nbrealscore`i'=r(N)
+ }
+}
+
+/***********************************************************************************************************
+TESTS OF THE FIRST ORDER
+************************************************************************************************************/
+
+tempname Pi
+matrix define `Pi'=J(`nbitems',`=`nbitems'-1',0)
+if "`test'"!="NONE" {
+ qui drop if `score'==.
+ if "`trace'"!="" {
+ di in green "*** Tests of the first order"
+ }
+ tempname Obs Obs2 Th Th2
+
+ matrix define `Obs'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Obs2'=J(`nbitems',`=`nbgroups'-1',0)
+ matrix define `Th'=J(`nbitems',`=`nbitems'-1',0)
+ matrix define `Th2'=J(`nbitems',`=`nbgroups'-1',0)
+ local listofitemsc
+
+ /* Estimation of the gamma symetrical functions*/
+ local c0 "1"
+ local c`nbitems' "`nbitems'*x"
+ forvalues j=1/`nbitems' {
+ local listini`j'
+ local listofitemsc "`listofitemsc' `beta`j''"
+ local c0 `c0'*(1+exp(x-`beta`j''))
+ local c`nbitems' `c`nbitems''-`beta`j''
+ forvalues k=1/`nbitems' {
+ local listini`j'k`k'
+ if `k'!=`j' {
+ local listini`j' "`listini`j'' `beta`k''"
+ }
+ forvalues l=1/`nbitems' {
+ if `l'!=`j'&`l'!=`k' {
+ local listini`j'k`k' "`listini`j'k`k'' `beta`l''"
+ }
+ }
+ }
+ }
+
+ gammasym `listofitemsc'
+
+ /*Estimation, for each value of the score s of the probability to respond to each item (Pi) and of the theorical number of positive responses (Ths) and of theorical number of positive respond per item pair (Ws)*/
+ forvalues s=1/`nbitems' {
+ local denom`s'=r(gamma`s')
+ tempname W`s'
+ matrix define `W`s''=J(`nbitems',`nbitems',0)
+ }
+ tempvar prob prob2 z y v z2 y2 v2 c r q e
+ qui gen `prob'=.
+ qui gen `prob2'=.
+ forvalues j=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui count if `rep'==1&`item'==`j'&`realscore'==`s'
+ matrix `Obs'[`j',`s']=r(N)
+ if "`test'"!="WP" {
+ gammasym `listini`j''
+ local num`j'=r(gamma`=`s'-1')
+ if "`method'"=="cml"|"`test'"=="Q" {
+ matrix `Pi'[`j',`s']=exp(-`beta`j'')*`num`j''/`denom`s''
+ }
+ else {
+ gausshermite exp(`s'*x)/(`c0'), sigma(`sig')
+ local int`s'=r(int)
+ if "`test'"=="R"&`nbrealscore`s''!=0{
+ local tmp=exp(-`beta`j'')*`num`j''*`int`s''*`nbind'/`nbrealscore`s''
+ matrix `Pi'[`j',`s']=`tmp'
+ }
+ else if `nbrealscore`s''==0 {
+ matrix `Pi'[`j',`s']=0
+ }
+ }
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ if `s'>=2 {
+ gammasym `listini`j'k`k''
+ local num`j'k`k'=r(gamma`=`s'-2')
+ if "`method'"=="cml" {
+ matrix `W`s''[`j',`k']=`nbrealscore`s''*exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''/`denom`s''
+ }
+ else {
+ matrix `W`s''[`j',`k']=exp(-`beta`j'')*exp(-`beta`k'')*`num`j'k`k''*`int`s''*`nbind'
+ }
+ matrix `W`s''[`k',`j']=`W`s''[`j',`k']
+ }
+ }
+ }
+ }
+ else if "`test'"=="WP" {
+ matrix `Pi'[`j',`s']=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j''))
+ }
+ matrix `Th'[`j',`s']=`Pi'[`j',`s']*`nbrealscore`s''
+ qui replace `prob'=`Pi'[`j',`s'] if `realscore'==`s'&`item'==`j'
+ qui replace `prob2'=exp(`theta`s''-`beta`j'')/(1+exp(`theta`s''-`beta`j'')) if `realscore'==`s'&`item'==`j'
+ matrix `W`s''[`j',`j']=`nbrealscore`s''*`Pi'[`j',`s']
+ if "`test'"!="R" {
+ matrix `W`s''[`j',`j']=`W`s''[`j',`j']*abs(1-`Pi'[`j',`s'])
+ }
+ }
+ }
+ qui gen `v2'=abs(`prob'*(1-`prob'))
+ qui gen `z2'=(`rep'-`prob')^2
+ qui gen `y2'=`z2'/`v2'
+ qui gen `c'=abs(`prob'*(1-`prob')*(`prob'^3+(1-`prob')^3))
+ qui gen `r'=`c'/(`v2')^2
+ qui gen `e'=`c'-(`v2')^2
+
+ forvalues j=1/`nbitems' {
+ qui su `y2' if `item'==`j'
+ local outfit`j'=r(mean)
+ qui su `r' if `item'==`j'
+ local Voutfit`j'=r(sum)
+ local Voutfit`j'=`Voutfit`j''/(`nbind')^2-1/`nbind'
+ local outfitstd`j'=(`outfit`j''^(1/3)-1)*(3/sqrt(`Voutfit`j''))-sqrt(`Voutfit`j'')/3
+
+ qui su `z2' if `item'==`j'
+ local n=r(sum)
+ qui su `v2' if `item'==`j'
+ local d=r(sum)
+ local infit`j'=`n'/`d'
+ qui su `e' if `item'==`j'
+ local sume=r(sum)
+ local Vinfit`j'=`sume'/(`d')^2
+ local infitstd`j'=(`infit`j''^(1/3)-1)*(3/sqrt(`Vinfit`j''))-sqrt(`Vinfit`j'')/3
+ }
+ tempname tmp stattest testitems
+
+ /*Estimation, by scores group g, of the theorical number of positive response (Th2g) and of the positive respond to each items pair (W2g)*/
+ scalar `stattest'=0
+ forvalues g=1/`=`nbgroups'-1' {
+ tempname W2`g' d2`g'
+ matrix define `W2`g''=J(`nbitems',`nbitems',0)
+ forvalues s=`liminf`g''/`limsup`g'' {
+ forvalues j=1/`nbitems' {
+ matrix `Obs2'[`j',`g']=`Obs2'[`j',`g']+`Obs'[`j',`s']
+ matrix `Th2'[`j',`g']=`Th2'[`j',`g']+`Th'[`j',`s']
+ if "`test'"=="R" {
+ forvalues k=`=`j'+1'/`nbitems' {
+ matrix `W2`g''[`j',`k']=`W2`g''[`j',`k']+`W`s''[`j',`k']
+ matrix `W2`g''[`k',`j']=`W2`g''[`j',`k']
+ }
+ }
+ matrix `W2`g''[`j',`j']=`W2`g''[`j',`j']+`W`s''[`j',`j']
+ }
+ }
+
+ /*Estimation of the d2g vectors*/
+ matrix `d2`g''=`Obs2'[1..`nbitems',`g']-`Th2'[1..`nbitems',`g']
+
+ /*Estimation of the influences on the test of each item (testitemsg matrix) and of the test statistic (stattest)*/
+ tempname test`g' testitems`g'
+ matrix `test`g''=`d2`g'''*syminv(`W2`g'')*`d2`g''
+ capture matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ if _rc!=0 {
+ matrix `tmp'=J(`nbitems',`nbitems',0)
+ forvalues j=1/`nbitems' {
+ matrix `tmp'[`j',`j']=`W2`g''[`j',`j']
+ }
+ di in green "Group `g' (`liminf`g''/`limsup`g''): The weight matrix is not positive-definite, the diagonal matrix is used to estimate the contribution of the items on the `wpname' statistic"
+ matrix list `tmp'
+ matrix `testitems`g''=cholesky(syminv(`tmp'))*`d2`g''
+ }
+ else {
+ matrix `testitems`g''=cholesky(syminv(`W2`g''))*`d2`g''
+ }
+ scalar `stattest'=`stattest'+`test`g''[1,1]
+ }
+ matrix `testitems'=J(`nbitems',1,0)
+ forvalues j=1/`nbitems' {
+ forvalues g=1/`=`nbgroups'-1' {
+ matrix `testitems'[`j',1]=`testitems'[`j',1]+`testitems`g''[`j',1]^2
+ }
+ }
+
+ /*Adaptation for the Q1 statistic*/
+ if "`test'"=="Q" {
+ scalar `stattest'=`stattest'*`=`nbitems'-1'/`nbitems'
+ }
+
+ /*Correction for R1m and Q1m*/
+ if ("`test'"=="R"|"`test'"=="Q")&("`method'"=="mml"|"`method'"=="gee") {
+ local c`nbitems' exp(`c`nbitems'')/(`c0')
+ local c0 1/(`c0')
+ gausshermite `c0', sigma(`sig')
+ local ci0=r(int)*`nbind'
+ gausshermite `c`nbitems'',sigma(`sig')
+ local ci`nbitems'=`nbind'*r(int)
+ scalar `stattest'=`stattest'+(`nbrealscore0'-`ci0')^2/`ci0'+(`nbrealscore`nbitems''-`ci`nbitems'')^2/`ci`nbitems''
+ }
+
+
+
+/***********************************************************************************************************
+TESTS U
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests U"
+ }
+
+ local quartile=`nbind'/4
+ local c1=0
+ local n1=0
+ while `n1'<`quartile' {
+ local c1=`c1'+1
+ local n1=`n1'+`nbrealscore`c1''
+ }
+ local c2=`nbitems'
+ local n2=0
+ while `n2'<`quartile' {
+ local c2=`c2'-1
+ local n2=`n2'+`nbrealscore`c2''
+ }
+ forvalues j=1/`nbitems' {
+ local zu1=0
+ local zu2=0
+ forvalues s=1/`c1' {
+ local zu1=`zu1'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ forvalues s=`c2'/`=`nbitems'-1' {
+ local zu2=`zu2'+`nbrealscore`s''*(`Obs'[`j',`s']/`nbrealscore`s''-`Pi'[`j',`s'])/sqrt(`nbrealscore`s''*`Pi'[`j',`s']*(1-`Pi'[`j',`s']))
+ }
+ local U`j'=(`zu1'-`zu2')/sqrt(`c1'+`nbitems'-`c2')
+ }
+ }
+
+
+
+/***********************************************************************************************************
+TESTS OF THE SECOND ORDER /*undocumented in beta test*/
+************************************************************************************************************/
+
+ if "`q2'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Tests of the second order"
+ }
+
+ tempfile Q2file
+ qui save "`Q2file'",replace
+ qui use "`saveraschtest'",replace
+
+ qui keep if `touse'==1
+ gen `score'=0
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'
+ rename ``i'' `rep'`i'
+ qui replace `score'=`score'+`rep'`i'
+ }
+ qui recode `score' `recode'
+
+ forvalues i=1/`nbitems' {
+ local Q2i`i'=0
+ forvalues j=`=`i'+1'/`nbitems' {
+ local listinci`i'j`j'
+ forvalues k=1/`nbitems' {
+ if `k'!=`i'&`k'!=`j' {
+ local listinci`i'j`j' "`listinci`i'j`j'' `beta`k''"
+ }
+ }
+ }
+ }
+
+ local Q2tot=0
+ forvalues k=2/`=`nbitems'-1' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `k'==1 {
+ local num=0
+ }
+ else {
+ gammasym `listinci`i'j`j''
+ local num=r(gamma`=`k'-2')
+ }
+ local athi`i'j`j'k`k'=exp(-`beta`i'')*exp(-`beta`j'')*`num'/`denom`k''
+ local bthi`i'j`j'k`k'=`nbth`i's`k''-`athi`i'j`j'k`k''
+ local cthi`i'j`j'k`k'=`nbth`j's`k''-`athi`i'j`j'k`k''
+ local dthi`i'j`j'k`k'=1-`athi`i'j`j'k`k''-`bthi`i'j`j'k`k''-`cthi`i'j`j'k`k''
+ }
+ }
+ }
+ forvalues k=1/`=`nbgroups'-1' {
+ local Q2`k'=0
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`j'+1'/`nbitems' {
+ qui count if `rep'`i'==1&`rep'`j'==1&`score'==`k'
+ local aempi`i'j`j'k`k'=r(N)
+ local ath2i`i'j`j'k`k'=0
+ local bth2i`i'j`j'k`k'=0
+ local cth2i`i'j`j'k`k'=0
+ local dth2i`i'j`j'k`k'=0
+ }
+ }
+ if `limsup`k''!=1 {
+ forvalues l=`liminf`k''/`limsup`k'' {
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ if `l'!=1 {
+ local ath2i`i'j`j'k`k'=`ath2i`i'j`j'k`k''+`athi`i'j`j'k`l''*`nbrealscore`l''
+ local bth2i`i'j`j'k`k'=`bth2i`i'j`j'k`k''+`bthi`i'j`j'k`l''*`nbrealscore`l''
+ local cth2i`i'j`j'k`k'=`cth2i`i'j`j'k`k''+`cthi`i'j`j'k`l''*`nbrealscore`l''
+ local dth2i`i'j`j'k`k'=`dth2i`i'j`j'k`k''+`dthi`i'j`j'k`l''*`nbrealscore`l''
+ }
+ }
+ }
+ }
+ forvalues i=1/`=`nbitems'-1' {
+ forvalues j=`=`i'+1'/`nbitems' {
+ local d2i`i'j`j'k`k'=(`aempi`i'j`j'k`k''-`ath2i`i'j`j'k`k'')^2
+ local Q2i`i'j`j'k`k'=`d2i`i'j`j'k`k''/`ath2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`bth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`cth2i`i'j`j'k`k''+`d2i`i'j`j'k`k''/`dth2i`i'j`j'k`k''
+ local Q2i`i'=`Q2i`i''+`Q2i`i'j`j'k`k''
+ local Q2i`j'=`Q2i`j''+`Q2i`i'j`j'k`k''
+ local Q2`k'=`Q2`k''+`Q2i`i'j`j'k`k''
+ }
+ }
+ }
+ local Q2tot=`Q2tot'+`Q2`k''
+ }
+ forvalues i=1/`nbitems' {
+ di in green "Item ``i'' : Q2 = `Q2i`i''"
+ }
+ local Q2=`Q2tot'*(`nbitems'-3)/(`nbitems'-1)
+ di in green "Q2 = `Q2tot'"
+ qui use "`Q2file'",replace
+ }
+
+/***********************************************************************************************************
+TEST LR Z
+************************************************************************************************************/
+
+ if "`method'"=="cml" {
+ if "`trace'"!="" {
+ di in green "*** Tests LR of Andersen"
+ }
+ local ssll=0
+ tempfile Zfile
+ qui save "`Zfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ gen `score'=0
+ forvalues j=1/`nbitems' {
+ qui replace `score'=`score'+``j''
+ }
+ qui recode `score' `recode' `nbitems'=`nbgroups'
+ forvalues i=1/`=`nbgroups'-1' {
+ if `effscore`i''>0 {
+ qui raschtestv7 `varlist' if `score'==`i', test(NONE) `ld' id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ use "`Zfile'",replace
+ tempname AndersenZ
+ matrix define `AndersenZ'=(`Z',`=(`nbgroups'-2)*(`nbitems'-1)',1-chi2(`=(`nbitems'-1)*(`nbgroups'-2)',`Z'))
+ }
+}
+
+
+/***********************************************************************************************************
+DISPLAYING RESULTS WITH TESTS
+************************************************************************************************************/
+if "`html'" != "" {
+ di ""
+}
+
+if "`test'"!="NONE" {
+ local conttest= "_c"
+}
+di
+tempname itemfit globalfit
+matrix `globalfit'=J(1,3,0)
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Conditional maximum likelihood (CML)"
+ }
+ else {
+ di "Estimation method: Conditional maximum likelihood (CML)
"
+ }
+ local nbtest=`nbgroups'-1
+ local line=77
+}
+else if "`method'"=="mml"{
+ if "`html'" == "" {
+ di in green "Estimation method: " in yellow "Marginal maximum likelihood (MML)"
+ }
+ else {
+ di "Estimation method: Marginal maximum likelihood (MML)
"
+ }
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+else if "`method'"=="gee" {
+ di in green "Estimation method: " in yellow "Generalized Estimating Equations (GEE)"
+ local nbtest=`nbgroups'+1
+ local line=70
+}
+if "`test'"=="NONE" {
+ local line=35
+}
+
+if "`html'" == "" {
+ di in green "Number of items: " in yellow `nbitems'
+ di in green "Number of groups: " in yellow `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di in green " (" in yellow "`nbtest'" in green " of them are used to compute the statistics of test)"
+ }
+}
+else {
+ di "Number of items: " `nbitems' "
"
+ di "Number of groups: " `=`nbgroups'+1' `conttest'
+ if "`test'"!="NONE" {
+ di " (`nbtest' of them are used to compute the statistics of test)"
+ }
+ di "
"
+}
+if "`method'"=="cml" {
+ local nbind=`nbind'+`effscore0'+`effscore`nbgroups''
+ local cont "_c"
+ matrix `itemfit'=J(`nbitems',6,0)
+}
+else {
+ local cont
+ matrix `itemfit'=J(`nbitems',5,0)
+}
+local missing=`N'-`nbind'
+if "`html'" == "" {
+ di in green "Number of individuals: " in yellow `N'
+ di in green "Number of individuals with missing values: " in yellow `nbindmiss' _c
+ if "`ld'"=="" {
+ di in green " (removed)"
+ }
+ else {
+ di
+ }
+ di in green "Number of individuals with nul or perfect score: " in yellow `=`effscore0'+`effscore`nbgroups'''
+}
+else {
+ di "Number of individuals: `N'
"
+ di "Number of individuals with missing values: " `nbindmiss'
+ if "`ld'"=="" {
+ di " (removed)"
+ }
+ di "
"
+ di "Number of individuals with nul or perfect score: " `=`effscore0'+`effscore`nbgroups''' "
"
+}
+if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in green "Conditional log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ }
+}
+else {
+ if "`html'" == "" {
+ di in green "Marginal log-likelihood: " in yellow %-13.4f `ll'
+ di in green "Log-likelihood: " in yellow %-13.4f `globalll'
+ di
+ }
+ else {
+ di "Marginal log-likelihood: " %-13.4f `ll' "
"
+ di "Log-likelihood: " %-13.4f `globalll' ""
+ }
+}
+
+if "`html'" == "" {
+ noi di in green _col(16) "Difficulty" `conttest'
+ if "`test'"!="NONE" {
+ di in green _col(58) "Standardized"
+ }
+ noi di in green _col(9) "Items" _col(16) "parameters" _col(28) "std Err." `conttest'
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di _col(41) "`namewp'" _col(47) "df" _col(50) "p-value" _col(58) "Outfit" _col(66) "Infit" `cont'
+ if "`method'"=="cml" {
+ di in green _col(77) "U"
+ }
+ }
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+ di ""
+ di " | Difficulty | | "
+ if "`test'"!="NONE" {
+ di " | Standardized | "
+ }
+ di "
"
+ di "Items | parameters | std Err. | "
+ if "`test'"!="NONE" {
+ local varin=int(2/sqrt(`nbind')*100)/100
+ local varout=int(6/sqrt(`nbind')*100)/100
+ di "`namewp' | df | p-value | Outfit | Infit | "
+ if "`method'"=="cml" {
+ di "U | "
+ }
+ }
+ di "
"
+}
+
+forvalues i=1/`nbitems' {
+ if "`html'" == "" {
+ noi di in yellow _col(3) %12s abbrev("``i''`fixed`i''" ,12) in yellow _col(18) %8.5f `beta`i'' _col(29) %6.5f `sd`i'' `conttest'
+ }
+ else {
+ di "" %12s abbrev("``i''`fixed`i''" ,12) " | " %8.5f `beta`i'' " | " %6.5f `sd`i'' " | "
+ }
+ if "`test'"!="NONE" {
+ if "`html'" == "" {
+ di _col(36) %8.3f `testitems'[`i',1] _col(46) %3.0f `=`nbgroups'-2' _col(51) %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) _col(58) %6.3f `outfitstd`i'' _col(65) %6.3f `infitstd`i'' /*_col(72) %6.3f `outfit`i'' _col(79) %6.3f `infit`i''*/ `cont'
+ }
+ else {
+ di "" %8.3f `testitems'[`i',1] " | " %3.0f `=`nbgroups'-2' " | " %6.4f 1-chi2(`=`nbgroups'-2',`testitems'[`i',1]) " | " %6.3f `outfitstd`i'' " | " %6.3f `infitstd`i'' " | "
+ }
+ matrix `itemfit'[`i',1]=`testitems'[`i',1]
+ matrix `itemfit'[`i',2]=`=`nbgroups'-2'
+ matrix `itemfit'[`i',3]=1-chi2(`=`nbgroups'-2',`testitems'[`i',1])
+ matrix `itemfit'[`i',4]=`outfitstd`i''
+ matrix `itemfit'[`i',5]=`infitstd`i''
+ if "`method'"=="cml" {
+ if "`html'" == "" {
+ di in ye _col(72) %6.3f `U`i''
+ }
+ else {
+ di "" %6.3f `U`i'' " | "
+ }
+ matrix `itemfit'[`i',6]=`U`i''
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+ }
+}
+if "`html'" == "" {
+ di in green "{hline `line'}"
+}
+else {
+ di ""
+}
+if "`test'"!="NONE" {
+ if "`method'"=="cml" {
+ local df=(`nbgroups'-2)*(`nbitems'-1)
+ }
+ else {
+ local df=(`nbgroups'-1)*(`nbitems'-1)-1
+ }
+ matrix `globalfit'=(`stattest',`df',1-chi2(`df',`stattest'))
+ if "`html'" == "" {
+ noi di in green _col(6) "`descwp'" _col(32) in gr "`namewp'=" _col(36) in ye %8.3f `globalfit'[1,1] _col(46) %3.0f `globalfit'[1,2] _col(51) %6.4f `globalfit'[1,3]
+ if "`method'"=="cml" {
+ noi di in green _col(6) "Andersen LR test" _col(34) "Z=" in yellow _col(36) %8.3f `AndersenZ'[1,1] _col(46) %3.0f `AndersenZ'[1,2] _col(51) %6.4f `AndersenZ'[1,3]
+ }
+ di in green "{hline `line'}"
+ }
+ else {
+ di "`descwp' | | `namewp'= | " %8.3f `globalfit'[1,1] " | " %3.0f `globalfit'[1,2] " | " %6.4f `globalfit'[1,3] " | | |
"
+ if "`method'"=="cml" {
+ di "Andersen LR test | | Z= | " %8.3f `AndersenZ'[1,1] " | " %3.0f `AndersenZ'[1,2] " | " %6.4f `AndersenZ'[1,3] " | | |
"
+ }
+ di "
"
+ }
+}
+
+if "`html'" == "" {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di in green "*: The difficulty parameter of this item had been fixed to 0"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di in green "The mean of the difficulty parameters is fixed to 0"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di in green "You have groups of scores with less than 30 individuals. The tests can be invalid."
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di in green "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test."
+ }
+
+ di
+}
+else {
+ if "`method'"=="cml"&"`meandiff'"==""{
+ di "*: The difficulty parameter of this item had been fixed to 0
"
+ }
+ if "`method'"=="cml"&"`meandiff'"!=""{
+ di "The mean of the difficulty parameters is fixed to 0
"
+ }
+ if `smallgroup'==1&"`test'"!="NONE" {
+ di "You have groups of scores with less than 30 individuals. The tests can be invalid.
"
+ }
+ if "`method'"!="cml"&"`test'"=="Q" {
+ di "The Q statistics is approximated in the `method' approach. It is preferable to use the R1m test.
"
+ }
+ di ""
+}
+
+if "`html'" == "" {
+ if "`method'"!="cml" {
+ di in green "{hline 56}"
+ noi di in green _col(5) "Parameters" _col(21) "Coef." _col(28) "std Err." _col(43) "z" _col(52) "P>|z|"
+ di in green "{hline 56}"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di in green _col(10) in yellow "Sigma" _col(18) %8.5f `sig' _col(29) %6.5f `sesig' _col(38) %6.3f `zsig' _col(50) %7.4f `pzsig'
+ di in green "{hline 56}"
+ }
+}
+else {
+ if "`method'"!="cml" {
+ di ""
+ di ""
+ di "Parameters | Coef. | std Err. | z | P>|z| |
"
+ local zsig=`sig'/`sesig'
+ local pzsig=2*(1-norm(abs(`zsig')))
+ di "Sigma | " %8.5f `sig' " | " %6.5f `sesig' " | " %6.3f `zsig' " | " %7.4f `pzsig' " |
"
+ }
+}
+
+
+
+*set trace on
+if "`covariables'"!="" {
+ tempname zcovariates pcovariates
+ matrix `zcovariates'=J(1,`nbcovariables',0)
+ matrix `pcovariates'=J(1,`nbcovariables',0)
+ forvalues i=1/`nbcovariables' {
+ local tmp :word `i' of `covariables'
+ local zcov=`betacov'[1,`i']/`Vbetacov'[`i',`i']^.5
+ local pzcov=2*(1-norm(abs(`zcov')))
+ matrix `zcovariates'[1,`i']=`zcov'
+ matrix `pcovariates'[1,`i']=`pzcov'
+ di in green _col(3) %12s in yellow abbrev("`tmp'",12) _col(18) %8.5f `betacov'[1,`i'] _col(29) %6.5f `Vbetacov'[`i',`i']^.5 _col(38) %6.3f `zcov' _col(50) %7.4f `pzcov'
+ }
+ di in green "{hline 56}"
+ local difficulties2
+ if "`difficulties'"!="" {
+ local difficulties2 diff(`difficulties')
+ }
+ if "`ss1'"!="" {
+ tempfile ss1save
+ qui save `ss1save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=r(N_obs)
+ *di "nbobs=`nbobs'"
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss10=`var0'*(`df0')
+ local ss1c0=0
+ di
+ di in green "Type 1 Sum of Squares (sequential)"
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss10' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di in green "{dup 85:-}"
+ local covariablesss1
+ forvalues i=1/`nbcovariables' {
+ local covariablesss1 `covariablesss1' `covariable`i''
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss1') test(none) `ld' `difficulties2'
+ local nbobs=r(N_obs)
+ local sigma`i'=r(sigma)
+ local var`i'=`sigma`i''^2
+ local nbcovtmp:word count `covariablesss1'
+ *di " ss1`i'=`var`i''*`=`nbobs'-(`nbitems'+1+`nbcovtmp')-1'"
+ local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1
+ *di "local df`i'=`nbobs'-(`nbitems'+1+`nbcovtmp')-1 (cov:`covariablesss1')"
+ local ss1`i'=`var`i''*`df`i''
+ *di "cov : `covariablesss1' var=`var`i'' df=`df`i''"
+ di _col(2) %12s in yellow abbrev("`covariable`i''",12) _col(15) %12.3f in ye `ss1`i'' _col(25) %12.3f `=`ss1`=`i'-1''-`ss1`i''' _col(47) %4.0f `df`i'' _col(63) %8.3f `var`i'' _col(81) %5.3f (`=`ss1`=`i'-1''-`ss1`i''')/`ss10'
+ }
+ di in green "{hline 85}"
+ qui use `ss1save'
+ }
+ if "`ss3'"!="" {
+ tempfile ss3save
+ qui save `ss3save'
+ qui use `saveraschtest'
+ qui keep if `touse'==1
+ if "`ss1'"=="" {
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') test(none) `ld' `difficulties2'
+ local sigma0=r(sigma)
+ local var0=`sigma0'^2
+ local nbobs=e(N_obs)
+ local df0=`nbobs'-(`nbitems'+1)-1
+ local ss30=`var0'*(`df0')
+ }
+ else {
+ local ss30=`ss10'
+ }
+ local ss3ref=`=`sig'^2*(`df0'-`nbcovariables')'
+ di
+ di in green "Type 3 Sum of Squares "
+ di "{hline 85}"
+ di in green _col(44) "Degrees" _col(56) "Variance of the" _col(77) "Explained"
+ di in green _col(4) "Covariates" _col(25) "SS" _col(35) "Diff" _col(41) "of freedom"_col(59) "latent trait" _col(78) "Variance"
+ di "{hline 85}"
+ di _col(10) in green "None" _col(15) in ye %12.3f `ss30' _col(47) %4.0f `df0' _col(63) %8.3f `var0'
+ di _col(6) in green "Complete" _col(15) in ye %12.3f `ss3ref' _col(25) %12.3f `=`ss30'-`ss3ref'' _col(47) %4.0f `=`df0'-`nbcovariables'' _col(63) %8.3f `sig'^2 _col(81) %5.3f 1-`sig'^2*(`df0'+`nbcovariables')/`ss30'
+ di in green "{dup 85:-}"
+ forvalues i=1/`nbcovariables' {
+ local covariablesss3
+ forvalues j=1/`nbcovariables' {
+ if `i'!=`j' {
+ local covariablesss3 `covariablesss3' `covariable`j''
+ }
+ }
+ qui raschtestv7 `varlist' ,id(`id') meth(`method') covariates(`covariablesss3') test(none) `ld' `difficulties2'
+ *ereturn list
+ local sigmas`i'=r(sigma)
+ local vars`i'=`sigmas`i''^2
+ local nbobs=e(N)
+ local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)
+ *di "local dfs`i'=`nbobs'-(`nbitems'+1)-1-(`nbcovariables'-1)"
+ local ss3s`i'=`vars`i''*`dfs`i''
+ local vara`i'=`sig'^2
+ local dfa`i'=`nbobs'-(`nbitems'+1)-1-`nbcovariables'
+ local ss3a`i'=`vara`i''*`dfa`i''
+ *di "cov : `covariablesss3' var=`vars`i'' df=`dfs`i''"
+ di _col(2) %12s in green abbrev("`covariable`i''",12) _col(15) in ye %12.3f `ss3s`i'' _col(25) %12.3f in ye `=`ss3s`i''-`ss3a`i''' _col(47) %4.0f `=`df0'-`nbcovariables'+1' _col(63) %8.3f `vars`i'' _col(80) %6.3f (`=`ss3s`i''-`ss3a`i''')/`ss30'
+ }
+ di in green "{hline 85}"
+ qui use `ss3save'
+ }
+}
+
+
+
+/*Tabular of the estimated values of the latent trait*/
+
+if "`covariables'"=="" {
+ if "`html'" == "" {
+ di
+ di
+ noi di in green _col(33) "Ability" _col(60) "Expected"
+ noi di in green _col(17) "Group" _col(23) "Score" _col(30) "parameters" _col(42) "std Err." _col(54) "Freq." _col(63) "Score"_c
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ noi di in green _col(75) "ll"
+ }
+ else {
+ noi di ""
+ }
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ local line=62
+ }
+ else {
+ local line=51
+ }
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di ""
+ di ""
+ di "Group | Score | Ability parameters | std Err. | Freq. | Expected Score | "
+ if "`method'"=="cml"&"`test'"!="NONE" {
+ di "ll | "
+ }
+ di "
"
+ }
+
+ local nonul=0
+ forvalues g=0/`nbgroups' {
+ if `g'!=0 {
+ if "`html'" == "" {
+ di in green _col(17) "{dup `line':-}"
+ }
+ }
+ forvalues s=`liminf`g''/`limsup`g'' {
+ if `s'==`liminf`g'' {
+ local tmp `ll`g''
+ local gr `g'
+ }
+ else {
+ local tmp
+ local gr
+ }
+ local expscore`nonul'=0
+ forvalues i=1/`nbitems' {
+ local expscore`nonul'=`expscore`nonul''+1/(1+exp(-`theta`nonul''+`beta`i''))
+ }
+ if "`method'"=="cml" {
+ local format1 %8.3f
+ }
+ else {
+ local format1 %8.5f
+ }
+ if "`html'" == "" {
+ noi di in yellow _col(17) %5s "`gr'"_col(23) %5s "`s'" _col(32) `format1' `theta`nonul'' _col(42) `format1' `sdtheta`nonul'' _col(55) %4.0f `nbrealscore`s'' _col(64) % 4.2f `expscore`nonul'' _col(68) %11.4f `tmp'
+ }
+ else {
+ di "" %5s "`gr'" " | " %5s "`s'" " | " `format1' `theta`nonul'' " | " `format1' `sdtheta`nonul'' " | " %4.0f `nbrealscore`s'' " | " % 4.2f `expscore`nonul'' " | " %11.4f `tmp' " | "
+ }
+ local nonul=`nonul'+1
+ }
+ }
+ if "`html'" == "" {
+ di in green _col(17) "{hline `line'}"
+ }
+ else {
+ di "
"
+ }
+}
+
+if "`method'"=="mml"|"`method'"=="gee" {
+ if "`html'" == "" {
+ di
+ *di in green "Variance of the estimated latent trait" _col(45) in ye %10.4f `vartheta'
+ di in green "Mean variance of the error" _col(45) in ye %10.4f `meanse2'
+ local sig2=`sig'^2
+ di in green "Estimated variance of the latent trait" _col(45) in ye %10.4f `sig2'
+ local psi2=1-`meanse2'/`sig2'
+ di in green "Personal Separation Index (PSI)" _col(45) in ye %10.4f `psi2'
+ di in green "Adjusted PSI on covariates (PSIadj)" _col(45) in ye %10.4f `psi'
+ }
+ else {
+ di ""
+ di ""
+ di ""
+ di "Mean variance of the error | " %10.4f `meanse2' " |
"
+ local sig2=`sig'^2
+ di "Estimated variance of the latent trait | " %10.4f `sig2' " |
"
+ local psi2=1-`meanse2'/`sig2'
+ di "Personal Separation Index (PSI) | " %10.4f `psi2' " |
"
+ di "Adjusted PSI on covariates (PSIadj) | " %10.4f `psi' " |
"
+ di "
"
+ }
+}
+
+
+/***********************************************************************************************************
+DETAILS OPTION
+************************************************************************************************************/
+
+if "`details'"!="" {
+ if "`html'"=="" {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di
+ di in green "{hline 44}"
+ di in green "Group: " in ye "`g'" in green " from " in ye "`liminf`g''" in green " to " in ye "`limsup`g''" in green " (n=" in ye "`nbscore`g''" in green")"
+ di
+ di _col(3) "Item" _col(10) "Observed" _col(23) "Expected" _col(37) "Scaled"
+ di in green "{dup 44:-}"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di _col(3) in ye "``j''" _col(14) %4.0f `Obs2'[`j',`g'] _col(25) %6.2f `Th2'[`j',`g'] _col(36) %7.4f `tmp'
+ }
+ di in green "{dup 44:-}"
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `test`g''[1,1]
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di in ye _col(14) %4.0f `nbrealscore`h'' _col(25) %6.2f `ci`h'' _col(36) %7.4f `tmp'
+ di in green "{dup 44:-}"
+ local tmp=`tmp'^2
+ di in green "Contribution to the `namewp' statistics: " %8.4f in ye `tmp'
+ }
+ }
+ }
+ else {
+ forvalues g=0/`nbgroups' {
+ if (`g'!=0&`g'!=`nbgroups')|"`method'"!="cml" {
+ di in gr ""
+ di in gr "Group: `g' from `liminf`g'' to `limsup`g'' (n=`nbscore`g'')"
+ di in gr "Item | Observed | Expected | Scaled |
"
+ }
+ if `g'!=0&`g'!=`nbgroups' {
+ forvalues j=1/`nbitems' {
+ local tmp=`d2`g''[`j',1]/sqrt(`W2`g''[`j',`j'])
+ di "``j'' | " %4.0f `Obs2'[`j',`g'] " | " %6.2f `Th2'[`j',`g'] " | " %7.4f `tmp' " |
"
+ }
+ di "Contribution to the `namewp' statistics: | " %8.4f `test`g''[1,1] " |
"
+ }
+ else if "`method'"!="cml" {
+ if `g'==0 {
+ local h=0
+ }
+ else {
+ local h=`nbitems'
+ }
+ local tmp=abs(`nbrealscore`h''-`ci`h'')/sqrt(`ci`h'')
+ di " | " %4.0f `nbrealscore`h'' " | " %6.2f `ci`h'' " | " %7.4f `tmp' " |
"
+ local tmp=`tmp'^2
+ di "Contribution to the `namewp' statistics: | " %8.4f `tmp' " |
"
+ }
+ di "
"
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION ICC
+************************************************************************************************************/
+*set trace on
+if "`icc'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Items Characteristic Curves"
+ }
+ tempvar proba propemp propth propthb
+ qui replace `tl'=. if `realscore'==0|`realscore'==`nbitems'|`realscore'==.
+ qui gen `propemp'=.
+ qui gen `propth'=.
+ qui gen `propthb'=.
+ label variable `propth' "Expected ICC"
+ label variable `propemp' "Observed ICC"
+ label variable `propthb' "Expected ICC"
+ label variable `tl' "Latent trait"
+ global iccs
+ forvalues i=1/`nbitems' {
+ forvalues s=1/`=`nbitems'-1' {
+ qui replace `propthb'=exp(`theta`s''-`beta`i'')/(1+exp(`theta`s''-`beta`i'')) if `item'==`i'&`realscore'==`s'
+ }
+ qui replace `propemp'=.
+ qui replace `propth'=.
+ tempvar propemp`i' propth`i'
+ qui bysort `realscore' `item' : egen `propth`i''=mean(`propthb') if `item'==`i'
+ qui bysort `realscore' `item' : egen `propemp`i''=mean(`rep') if `item'==`i'
+ qui replace `propth'=`propth`i'' if `item'==`i'
+ qui replace `propemp'=`propemp`i'' if `item'==`i'
+ local mintl=floor(`theta1')
+ local maxtl=floor(`theta`=`nbitems'-1'')+1
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\icc``i''"
+ }
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_icc_``i''"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ graph twoway (line `propemp' `propth' `tl') if `item'==`i' , `htmlregion' name(icc``i'',replace) ytitle("") ylabel(0(.25)1) title("Observed and Expected ICC for the item ``i''") xlabel(`mintl'(1)`maxtl') xsize(12) ysize(9) `draw'
+ if "html"=="" {
+ pause
+ }
+ else {
+ qui graph save icc``i'' "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_icc_``i''.eps, replace
+ di ""
+
+ }
+ if "`filessave'"!="" {
+ qui graph save icc``i'' "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui graph `propemp' `propth' `tl' if `item'==`i' , twoway `saving' c(ll) ylabel(0(.25)1) xlabel(`mintl'(1)`maxtl') title("Observed and Expected ICC for the item ``i''")
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION INFORMATION
+************************************************************************************************************/
+
+if "`information'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Information graph"
+ }
+
+ tempfile saveinfo
+ qui save "`saveinfo'",replace
+ tempvar info latent
+ drop _all
+ qui set obs 2001
+ gen `latent'=((_n-1)/1001-1)*3
+ label variable `latent' "latent trait"
+ gen `info'=0
+ forvalues i=1/`nbitems' {
+ qui replace `info'=`info'+exp(`latent'-`beta`i'')/(1+exp(`latent'-`beta`i''))^2
+ }
+ local saving "`dirsave'\\information"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_information"
+ }
+ if "`v8'"!=""|"`html'"!="" {
+ *set trace on
+ graph twoway (line `info' `latent') , `htmlregion' name(information,replace) ytitle("Information") xlabel(-3(1)3) title("Information graph of the scale") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ graph save information "`saving'" , `replace'
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save information "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_information.eps, replace
+ di ""
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ if "`filessave'"=="" {
+ local saving
+ }
+ qui graph `info' `latent' , twoway `saving' c(l) xlabel(-3(1)3) title("Information graph of the scale")
+ pause
+ }
+ qui use "`saveinfo'",replace
+}
+
+/***********************************************************************************************************
+OPTION FITGRAPH
+************************************************************************************************************/
+
+if "`fitgraph'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graphical validation of the fit"
+ }
+ *set trace on
+ tempname outfit meanz2 meanv2 sumd infit Voutfit outfitstd Vinfit infitstd
+ qui egen `outfit'=mean(`y2'),by(`id')
+ qui egen `Voutfit'=sum(`r'),by(`id')
+ qui replace `Voutfit'=`Voutfit'/(`nbitems')^2-1/`nbitems'
+ qui gen `outfitstd'=(`outfit'^(1/3)-1)*(3/sqrt(`Voutfit'))-sqrt(`Voutfit')/3
+ qui egen `meanz2'=sum(`z2'),by(`id')
+ qui egen `meanv2'=sum(`v2'),by(`id')
+ qui gen `infit'=`meanz2'/`meanv2'
+ qui egen `Vinfit'=sum(`e'),by(`id')
+ qui replace `Vinfit'=`Vinfit'/(`meanv2')^2
+ qui gen `infitstd'=(`infit'^(1/3)-1)*(3/sqrt(`Vinfit'))-sqrt(`Vinfit')/3
+
+ qui su `outfitstd'
+ local mino=floor(2*min(`r(min)',-2))/2
+ local maxo=ceil(2*max(`r(max)',2))/2
+ qui su `infitstd'
+ local mini=floor(2*min(`r(min)',-2))/2
+ local maxi=ceil(2*max(`r(max)',2))/2
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfitind"
+ local savingi "`dirsave'\\infitind"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstd' `id'), `htmlregion' name(outfit,replace) yline(-2 2) title("Outfit indexes") xtitle("Individual indexes") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstd' `id'), `htmlregion' name(infit,replace) yline(-2 2) title("Infit indexes") xtitle("Individual indexes") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html'"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfit "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfit.eps, replace
+ }
+ qui graph save infit "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infit.eps, replace
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstd' `id', `savingo' twoway sy(.) c(.) yline(-2 2) title("Outfit indexes") b2title("Individual indexes") l1("") l2title("Outfit") ylabel(`mino'(.5)`maxo')
+ pause
+ graph `infitstd' `id', `savingi' twoway sy(.) c(.) yline(-2 2) title("Infit indexes") b2title("Individual indexes") l1("") l2title("Infit") ylabel(`mini'(.5)`maxi')
+ pause
+ }
+ drop _all
+ qui set obs `nbitems'
+ tempvar name betap outfitstdj infitstdj
+ qui gen str9 `name'=""
+ qui gen `betap'=.
+ qui gen `outfitstdj'=.
+ qui gen `infitstdj'=.
+ local mino=-2
+ local maxo=2
+ local mini=-2
+ local maxi=2
+ forvalues j=1/`nbitems' {
+ qui replace `name'="``j''" in `j'
+ qui replace `betap'=`beta`j'' in `j'
+ qui replace `outfitstdj'=`outfitstd`j'' in `j'
+ qui replace `infitstdj'=`infitstd`j'' in `j'
+ local mino=floor(min(`mino',`outfitstd`j'')*2)/2
+ local mini=floor(min(`mini',`infitstd`j'')*2)/2
+ local maxo=ceil(max(`maxo',`outfitstd`j'')*2)/2
+ local maxi=ceil(max(`maxi',`infitstd`j'')*2)/2
+ }
+ if "`filessave'"!=""{
+ local savingo "`dirsave'\\outfititems"
+ local savingi "`dirsave'\\infititems"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `outfitstdj' `betap',`htmlregion' name(outfititem,replace) mlabel(`name')), yline(-2 2) title("Outfit indexes") xtitle("Difficulty") ytitle("Outfit") ylabel(`mino'(.5)`maxo') `draw'
+ if "`html"=="" {
+ pause
+ }
+ graph twoway (scatter `infitstdj' `betap',`htmlregion' name(infititem,replace) mlabel(`name')), yline(-2 2) title("Infit indexes") xtitle("Difficulty") ytitle("Infit") ylabel(`mini'(.5)`maxi') `draw'
+ if "`html"=="" {
+ pause
+ }
+ if "`filessave'"!=""|"`html'"!="" {
+ qui graph save outfititem "`savingo'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_outfititem.eps, replace
+ }
+ qui graph save infititem "`savingi'" , `replace'
+ if "`html'"!="" {
+ qui graph export `c(tmpdir)'/`html'_infititem.eps, replace
+ }
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local savingo "saving(`savingo'"
+ local savingi "saving(`savingi'"
+ if "`replace'"=="" {
+ local savingo "`savingo')"
+ local savingi "`savingi')"
+ }
+ else {
+ local savingo "`savingo',replace)"
+ local savingi "`savingi',replace)"
+ }
+ }
+ graph `outfitstdj' `betap', `savingo' twoway c(.) yline(-2 2) title("Outfit indexes") b2title("Difficulty") l1title("") l2title("Outfit") ylabel(`mino'(.5)`maxo') sy([`name'])
+ pause
+ graph `infitstdj' `betap', `savingi' twoway c(.) yline(-2 2) title("Infit indexes") b2title("Difficulty") l1title("") l2title("Infit") ylabel(`mini'(.5)`maxi') sy([`name'])
+ pause
+ }
+}
+
+
+/***********************************************************************************************************
+OPTION SPLITTESTS
+************************************************************************************************************/
+
+if "`splittests'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Splitting tests"
+ }
+ forvalues j=1/`nbitems' {
+ tempname estneg`j' estpos`j'
+ local listitems
+ forvalues k=1/`nbitems' {
+ if `j'!=`k' {
+ local listitems `listitems' ``k''
+ }
+ }
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ qui raschtestv7 `listitems' if ``j''==0,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estneg`j''=r(beta)
+ local llneg=r(cll)
+ qui raschtestv7 `listitems' if ``j''==1,test(NONE) meth(cml) `ld' id(`id')
+ matrix `estpos`j''=r(beta)
+ local llpos=r(cll)
+ qui raschtestv7 `listitems',test(NONE) meth(cml) `ld' id(`id')
+ local llnegpos=r(cll)
+ local nbcol=colsof(`estneg`j'')
+ local meanneg=0
+ local meanpos=0
+ forvalues k=1/`nbcol' {
+ local meanneg=`meanneg'+`estneg`j''[1,`k']
+ local meanpos=`meanpos'+`estpos`j''[1,`k']
+ }
+ local meanneg=`meanneg'/`nbitems'
+ local meanpos=`meanpos'/`nbitems'
+ forvalues k=1/`nbcol' {
+ matrix `estneg`j''[1,`k']=`estneg`j''[1,`k']-`meanneg'
+ matrix `estpos`j''[1,`k']=`estpos`j''[1,`k']-`meanpos'
+ if "`method'"=="cml" {
+ matrix `estneg`j''=`estneg`j'',-`meanneg'
+ matrix `estpos`j''=`estpos`j'',-`meanpos'
+ }
+ }
+ drop _all
+ qui set obs `=`nbitems'+1'
+ tempvar neg pos name diag
+ qui gen `neg'=.
+ qui gen `pos'=.
+ qui gen str9 `name'=""
+ local min=`estneg`j''[1,1]
+ local max=`estneg`j''[1,1]
+ forvalues k=1/`=`nbitems'-1' {
+ qui replace `neg'=`estneg`j''[1,`k'] in `k'
+ qui replace `pos'=`estpos`j''[1,`k'] in `k'
+ local min=min(`min',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local max=max(`max',`estneg`j''[1,`k'],`estpos`j''[1,`k'])
+ local tmp:word `k' of `listitems'
+ qui replace `name'="`tmp'" in `k'
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui gen `diag'=.
+ qui replace `diag'=`min' in `nbitems'
+ qui replace `diag'=`max' in `=`nbitems'+1'
+ local Zgr=round(2*(`llneg'+`llpos'-`llnegpos'),0.001)
+ local Zgr=substr("`Zgr'",1,6)
+ local pgr=round(1-chi2(`=`nbitems'-1',`Zgr'),0.0001)
+ local pgr=substr("`pgr'",1,5)
+ local note="Z=`Zgr', df=`=`nbitems'-1' , p=`pgr'"
+ if "`filessave'"!=""{
+ local saving "`dirsave'\\split``j''"
+ }
+ if "`v8'"!="" {
+ graph twoway (scatter `pos' `neg' ,mlabel(`name')) (line `diag' `diag'), ytitle("Positive answer") xtitle("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title(Splitting on ``j'') `draw' legend(off) note("Andersen Z test: `note'") name(split,replace) `draw'
+ pause
+ if "`filessave'"!="" {
+ graph save split "`saving'" , `replace'
+ }
+ }
+ else {
+ if "`filessave'"!="" {
+ local saving "saving(`saving'"
+ if "`replace'"=="" {
+ local saving "`saving')"
+ }
+ else {
+ local saving "`saving',replace)"
+ }
+ }
+ qui replace `diag'=`neg' if `diag'==.
+ graph `pos' `diag' `diag', `saving' c(.l) sy([`name']i) l1title("") l2title("Positive answer") b2title("Negative answer") xlabel(`min'(1)`max') ylabel(`min'(1)`max') title("Splitting on ``j'' (`note')") `draw'
+ pause
+ }
+ }
+}
+
+/***********************************************************************************************************
+OPTION GRAPH
+************************************************************************************************************/
+
+if "`graph'"!=""&"`v8'"!="" {
+ if "`trace'"!="" {
+ di in green "*** Graph option"
+ }
+ tempvar latent2 tl2 delta2 tlth2 labdelta2 labtl2
+ drop _all
+ qui set obs 1001
+ gen `latent2'=(_n-501)/100
+ label variable `latent2' "latent trait"
+ qui gen `tl2'=.
+ qui gen `labtl2'=""
+ forvalues i=0/`nbitems' {
+ *if (`i'!=0&`i'!=`nbitems')|"`method'"!="cml" {
+ qui replace `tl2'=`nbrealscore`i''/`N' if round(`latent2',0.01)==round(`theta`i'',0.01)
+ qui replace `labtl2'="`i'" if round(`latent2',0.01)==round(`theta`i'',0.01)
+ *}
+ }
+ qui gen `delta2'=.
+ qui gen `labdelta2'=""
+ forvalues i=1/`nbitems' {
+ qui replace `delta2'=-.05 if round(`latent2',0.01)==round(`beta`i'',0.01)
+ qui replace `labdelta2'="``i''" if round(`latent2',0.01)==round(`beta`i'',0.01)
+ }
+ if "`method'"=="mml"|"`method'"=="gee" {
+ qui gen `tlth2'=1/(2*_pi*`sig')*exp(-.5*(`latent2'/`sig')^2)
+ label variable `tlth2' "Theorical distribution"
+ local graphmml line `tlth2' `latent2'
+ }
+ label variable `tl2' "Score"
+ label variable `delta2' "Items"
+ local saving "`dirsave'\\graph"
+ if "`html'"!="" {
+ local saving "`c(tmpdir)'/`html'_map"
+ }
+ local min=-2
+ local max=2
+ forvalues j=1/`nbitems' {
+ if `beta`j''<`min' {
+ local min=`beta`j''-.5
+ }
+ if `beta`j''>`max'&`beta`j''!=. {
+ local max=`beta`j''+.5
+ }
+ }
+ if "`method'"=="cml" {
+ if `theta0'<`min' {
+ local min=`theta0'-.5
+ }
+ if `theta`=`nbitems'-1''>`max' {
+ local max=`theta`=`nbitems'-1''+.5
+ }
+ }
+ else if "`method'"!="cml" {
+ if `theta0'<`min'&`theta0'!=. {
+ local min=`theta0'-.5
+ }
+ if `theta`nbitems''>`max'&`theta`nbitems''!=. {
+ local max=`theta`nbitems''+.5
+ }
+ }
+ local min=floor(`min')
+ local max=floor(`max')+1
+ qui su `tl2'
+ local max2=r(max)
+ if "`method'"!="cml" {
+ qui su `tlth2'
+ local max2=max(`max2',`r(max)')
+ }
+ qui replace `latent2'=. if `latent2'<`min'|`latent2'>`max'
+ if "`v8'"!="" {
+ graph twoway (bar `tl2' `latent2',/*mlabel(`labtl2')*/ barwidth(.3) ) (dropline `delta2' `latent2',mlabel(`labdelta2') mlabposition(6)) (`graphmml'), `htmlregion' name(graph,replace) ytitle("") xlabel(`min'(1)`max') ylabel(-.1 0(0.05)`max2') title("Individuals/items representations") xsize(12) ysize(9) `draw'
+ if "`filessave'"!="" {
+ graph save graph "`saving'" , `replace'
+ }
+ if "`html'"=="" {
+ pause
+ }
+ else {
+ qui graph save graph "`saving'" , `replace'
+ qui graph export `c(tmpdir)'/`html'_map.eps, replace
+ di ""
+ }
+ }
+}
+else if "`graph'"!=""&"`v8'"=="" {
+ di in ye "The graph option is not available with Stata 7"
+}
+
+/***********************************************************************************************************
+COMPARISON OF TWO POPULATION
+************************************************************************************************************/
+
+if "`comp'"!=""&"`method'"!="cml" {
+ di
+ di _col(4) "{hline 30}"
+ di _col(4) in green "Comparison of two populations"
+ di _col(4) "{hline 30}"
+ di
+ di _col(4) in green "`comp'==`mincomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmin' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmin' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmin'
+ di _col(4) in green "`comp'==`maxcomp':" _col(20) "N=" _col(22) in yellow %7.0f `Nmax' _col(30) in green "mean= " _col(35) in yellow %8.4f `meanmax' _col(45) in green "variance=" _col(55) in yellow %8.4f `varmax'
+ di _col(33) in green "Z= " _col(35) in yellow %8.4f `Zcomp' _col(47) in green "pvalue= " _col(57) in yellow %6.4f `pvalue'
+}
+
+/***********************************************************************************************************
+TEST DIF
+************************************************************************************************************/
+
+if "`method'"=="cml"&"`dif'"!=""&"`test'"!="NONE" {
+ if "`trace'"!="" {
+ di in green "*** Tests of DIF"
+ }
+ local ssll=0
+ tempname DIFfile
+ qui save "`DIFfile'", replace
+ qui use "`saveraschtest'",replace
+ qui keep if `touse'==1
+ unab list:`dif'
+ local nbdif:word count `list'
+ tempname DIF
+ matrix define `DIF'=J(`nbdif',4,0)
+ local count=1
+ di
+ di _col(4) in green "{hline 45}"
+ di _col(4) in green "Test of Differential Item Functioning (DIF)"
+ di _col(4) in green "{hline 45}"
+ foreach j in `list' {
+ qui inspect `j'
+ local nbdif=r(N_unique)
+ qui su `j'
+ local maxdif=r(max)
+ if `nbdif'>10&`maxdif'<=10 {
+ di in ye "The {hi:dif} option is available with variables containing 10 or less modalities (coded from 0 or 1 to k<10)."
+ di in ye "The variable `j' (`nbdif' modalities) is omitted."
+ }
+ else {
+ local ssll=0
+ forvalues i=0/10 {
+ qui count if `j'==`i'
+ local effdif=r(N)
+ if `effdif'>0 {
+ qui raschtestv7 `varlist' if `j'==`i', test(NONE) id(`id')
+ local ll`i'=r(cll)
+ local ssll=`ssll'+(`ll`i'')
+ }
+ }
+ local Z=2*`ssll'-2*`ll'
+ local ddl=(`nbdif'-1)*(`nbitems'-1)
+ matrix define `DIF'[`count',1]=(`count',`Z',`ddl',1-chi2(`ddl',`Z'))
+ di
+ di _col(4) in green "Variable:" in ye " `j' " in green " Number of groups: " in ye "`nbdif'"
+ di _col(4) in green "LR Test Z=" in ye %8.3f `Z' in gr " ddl=" in ye %4.0f `ddl' in gr " p-value=" in ye %6.4f `=1-chi2(`ddl',`Z')'
+ di
+ }
+ local ++count
+ }
+ use "`DIFfile'",replace
+}
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+if "`trace'"!="" {
+ di in green "*** Returns"
+}
+local colnametheta
+
+forvalues i=0/`nbgroups' {
+ local colnametheta `colnametheta' score_`i'
+}
+
+
+return clear
+
+if `nbitems'>=3&"`test'"!="NONE" {
+ matrix colnames `globalfit'=`namewp' df p
+ matrix rownames `globalfit'=`method'
+ matrix rownames `itemfit'=`varlist'
+ matrix roweq `itemfit'=`method'
+
+ if "`method'"=="cml" {
+ matrix colnames `itemfit'=`namewp' df p outfit infit U
+ matrix rownames `AndersenZ'=`method'
+ matrix colnames `AndersenZ'=Z df p
+ return matrix AndersenZ=`AndersenZ'
+ if "`dif'"!="" {
+ matrix rownames `DIF'=`list'
+ matrix colnames `DIF'=num Z df p
+ return matrix DIF=`DIF'
+ }
+ }
+ else {
+ matrix colnames `itemfit'=`namewp' df p outfit infit
+ }
+ return matrix itemFit=`itemfit'
+ return matrix globalFit=`globalfit'
+}
+
+matrix colnames `theta'=`colnametheta'
+matrix rownames `theta'=theta
+return matrix theta `theta'
+matrix colnames `sdtheta'=`colnametheta'
+matrix rownames `sdtheta'=`colnametheta'
+return matrix Vartheta `sdtheta'
+local varlist2
+matrix coleq `beta'=`method'
+matrix coleq `Vbeta'=`method'
+matrix roweq `Vbeta'=`method'
+if "`method'"=="cml" {
+ forvalues i=1/`=`nbitems'-1' {
+ local varlist2 `varlist2' ``i''
+ }
+ return scalar cll=`ll'
+ return scalar ll=`globalll'
+ local AIC=-2*`globalll'+2*(`nbitems'-1)
+}
+else {
+ return scalar ll=`ll'
+ local varlist2 `varlist'
+ return scalar sigma=`sig'
+ return scalar sesigma=`sesig'
+ local AIC=-2*`ll'+2*(`nbitems'+1)
+}
+
+if "`comp'"!="" {
+ return scalar Zcomp=`Zcomp'
+ return scalar pZcomp=`pvalue'
+}
+
+matrix colnames `beta'=`varlist2'
+matrix rownames `beta'=beta
+return matrix beta `beta'
+
+matrix colnames `Vbeta'=`varlist2'
+matrix rownames `Vbeta'=`varlist2'
+return matrix Varbeta `Vbeta'
+
+return scalar AIC=`AIC'
+return scalar N=`nbind'
+return scalar N_obs=`nbobserv'
+
+if "`method'"=="mml" {
+ return scalar PSI=`psi2'
+ return scalar PSIadj=`psi'
+}
+if "`covariables'"!="" {
+ local tmp
+ local tmp2
+ forvalues i=1/`nbcovariables' {
+ local tmp `tmp' `covariable`i''
+ local tmp2 "`tmp2' :`covariable`i''"
+ }
+ matrix colnames `betacov'=`tmp2'
+ matrix rownames `Vbetacov'=`tmp2'
+ matrix colnames `Vbetacov'=`tmp2'
+ matrix colnames `zcovariates'=`tmp'
+ matrix colnames `pcovariates'=`tmp'
+ return matrix betacovariates=`betacov'
+ return matrix Vbetacovariates=`Vbetacov'
+ return matrix zcovariates=`zcovariates'
+ return matrix pcovariates=`pcovariates'
+}
+if "`pause'"!="" {
+ pause off
+}
+
+drop _all
+
+restore,not
+use "`saveraschtest'"
+
+/***********************************************************************************************************
+CREATE EVENTUAL NEW VARIABLES
+************************************************************************************************************/
+
+*set trace on
+if "`genres'"!="" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge se`genlt'
+ forvalues i=1/`nbitems' {
+ gen `genres'`i'=exp(``i''*(`genlt'-`beta`i''))/(1+exp(`genlt'-`beta`i''))/sqrt(exp(`genlt'-`beta`i'')/(1+exp(`genlt'-`beta`i''))^2)
+ }
+ corr `genres'*
+ pca `genres'*
+ drop `u'm1
+}
+if "`genfit'"!=""|"`genlt'"!=""|"`genscore'"!="" {
+ tempname genlt2 genscore2 outfit2 infit2
+ qui gen `score'=0 `if'
+ forvalues i=1/`nbitems' {
+ qui replace `score'=`score'+``i'' `if'
+ }
+ if "`genscore'"!="" {
+ qui gen `genscore'=`score' `if'
+ }
+ if "`genlt'"!="" {
+ if "`replacegenlt'"=="replace" {
+ capture drop `genlt'
+ capture drop se`genlt'
+ }
+ if "`method'"=="mml" {
+ qui sort `id'
+ qui merge `id' using `ltsave'
+ qui rename `u'm1 `genlt'
+ qui rename `u's1 se`genlt'
+ qui drop _merge
+ }
+ else if "`method'"!="mml" {
+ qui gen `genlt2'=. `if'
+ forvalues i=0/`nbitems' {
+ qui replace `genlt2'=`theta`i'' `if'&`score'==`i'
+ }
+ qui gen `genlt'=`genlt2' `if'
+ }
+ }
+ if "`genfit'"!="" {
+ local outfit:word 1 of `genfit'
+ local infit:word 2 of `genfit'
+ qui gen `outfit'=0 `if'
+ qui gen `infit'=0 `if'
+ tempname infit1 infit2
+ qui gen `infit1'=0 `if'
+ qui gen `infit2'=0 `if'
+ forvalues j=1/`nbitems' {
+ tempname pi`j'
+ qui gen `pi`j''=exp(`genlt2'-`beta`j'')/(1+exp(`genlt2'-`beta`j'')) `if'
+ qui replace `pi`j''=0 `if'
+ forvalues s=1/`nbitems' {
+ qui replace `pi`j''=`Pi'[`j',`s'] `if'&`score'==`s'
+ }
+ qui gen `outfit'``j''=(``j''-`pi`j'')^2/(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `infit1'=`infit1'+(``j''-`pi`j'')^2 `if'
+ qui replace `infit2'=`infit2'+(`pi`j''*(1-`pi`j'')) `if'
+ qui replace `outfit'=`outfit'+`outfit'``j''/`nbitems' `if'
+ }
+ qui replace `infit'=`infit1'/`infit2' `if'
+ }
+}
+
+if "`trace'"!=""|"`time'"!="" {
+ capture qui elapse `st'
+ di in green "** Time : " in yellow "$S_elap " in green "seconds"
+}
+
+end
diff --git a/Modules/ado/personal/r/raschtestv8.10.ado b/Modules/ado/personal/r/raschtestv8.10.ado
new file mode 100644
index 0000000..cc6b694
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv8.10.ado
@@ -0,0 +1,206 @@
+*! version 8.10 5july2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+* Version 8.3 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option*/
+* Version 8.6 (2012-11-19) : Jean-Benoit Hardouin /*HTML option*/
+* Version 8.9 (2019-06-05) : Jean-Benoit Hardouin /*PNG option*/
+* Version 8.10 (2019-06-05) : Jean-Benoit Hardouin /*EXTENSION option*/
+*
+* Required modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - University of Nantes - France
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2003-2012, 2019 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) GENRes(string) EXTension(string) graphclose docx(string)]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genres'"!="" {
+ local gensresv8 "genres(`genres')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+
+raschtestv7 `varlist' `if' `in' , id(`id') html(`html') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genresv8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8' `png' extension(`extension') `graphclose' docx(`docx')
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/raschtestv86.ado b/Modules/ado/personal/r/raschtestv86.ado
new file mode 100644
index 0000000..d70abde
--- /dev/null
+++ b/Modules/ado/personal/r/raschtestv86.ado
@@ -0,0 +1,205 @@
+*! version 8.6 19november2012
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Raschtest: Rasch model, fit tests and graphical validation
+*
+* Historic:
+* Version 1 (2003-06-30): Jean-Benoit Hardouin
+* Version 2 (2003-07-07): Jean-Benoit Hardouin
+* Version 3 (2004-01-02): Jean-Benoit Hardouin
+* Version 4 (2004-01-21): Jean-Benoit Hardouin
+* Version 5 (2004-01-24): Jean-Benoit Hardouin
+* Version 6 (2004-02-05): Jean-Benoit Hardouin
+* Version 6.1 (2004-03-29): Jean-Benoit Hardouin
+* Version 6.2 (2004-04-06): Jean-Benoit Hardouin
+* Version 6.3 (2004-07-08) : Jean-Benoit Hardouin
+* Version 7 (2005-04-02) : Jean-Benoit Hardouin
+* Version 7.2 (2005-05-20) : Jean-Benoit Hardouin
+* Version 7.3 (2005-07-02) : Jean-Benoit Hardouin
+* Version 7.4 (2006-01-15) : Jean-Benoit Hardouin
+* Version 7.5 (2006-04-20) : Jean-Benoit Hardouin
+* Version 7.6 (2008-06-20) : Jean-Benoit Hardouin /*nold option*/
+* Version 8 (2009-06-20) : Jean-Benoit Hardouin /*DIFFICULTIES and COVARIATES options*/
+* Version 8.3 (2010-06-15) : Jean-Benoit Hardouin /*GENRES option*/
+* Version 8.6 (2012-11-19) : Jean-Benoit Hardouin /*HTML option*/
+*
+* Needed modules :
+* raschtestv7 version 8.1 (http://freeirt.free.fr)
+* gammasym version 2.2 (http://www.freeirt.org)
+* gausshermite version 1 (http://www.freeirt.org)
+* geekel2d version 4.3 (http://www.freeirt.org)
+* genscore version 1.4 (http://www.freeirt.org)
+* ghquadm (findit ghquadm)
+* gllamm version 2.3.14 (ssc describe gllamm)
+* gllapred version 2.3.7 (ssc describe gllapred)
+* elapse (ssc describe elapse)
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2003-2012 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define raschtest,eclass
+syntax varlist(min=1 numeric) [if] [in] , ID(varname) [HTML(string) MEANdiff DIRsave(string) FILESsave nodraw PAUse REPlace ICC INFormation SPLITtests FITgraph Method(string) group(numlist >0 ascen) AUTOGroup Test(string) q2 GENLT(string) GENSCOre(string) GENFIT(string) GRAph COMp(varname) dif(varlist) time TRace Details nold iterate(int 200) DIFFiculties(string) COVariates(string) GENRes(string)]
+
+local nbitems:word count `varlist'
+if "`method'"=="" {
+ local method "cml"
+}
+else {
+ local method=lower("`method'")
+}
+if "`test'"=="" {
+ local test "R"
+}
+else {
+ local test=upper("`test'")
+}
+if "`dirsave'"!="" {
+ local dirsavev8 "dirsave(`dirsave')"
+}
+if "`method'"!="" {
+ local methodv8 "method(`method')"
+}
+if "`test'"!="" {
+ local testv8 "test(`test')"
+}
+if "`group'"!="" {
+ local groupv8 "group(`group')"
+}
+if "`genlt'"!="" {
+ local genltv8 "genlt(`genlt')"
+}
+if "`genscore'"!="" {
+ local genscorev8 "genscore(`genscore')"
+}
+if "`genres'"!="" {
+ local gensresv8 "genres(`genres')"
+}
+if "`genfit'"!="" {
+ local genfitv8 "genfit(`genfit')"
+}
+if "`comp'"!="" {
+ local compv8 "comp(`comp')"
+}
+if "`dif'"!="" {
+ local difv8 "dif(`dif')"
+}
+if "`iterate'"!="" {
+ local iteratev8 "iterate(`iterate')"
+}
+if "`difficulties'"!="" {
+ local difficultiesv8 "difficulties(`difficulties')"
+}
+if "`covariates'"!="" {
+ local covariatesv8 "covariates(`covariates')"
+}
+
+raschtestv7 `varlist' `if' `in' , id(`id') html(`html') `meandiff' `dirsavev8' `filessave' `nodraw' `pause' `replace' `icc' `information' `splittests' `fitgraph' `methodv8' `groupv8' `autogroup' `testv8' `q2' `genltv8' `genscorev8' `genresv8' `genfitv8' `graph' v8 `compv8' `difv8' `time' `trace' `details' `ld' `iteratev8' `difficultiesv8' `covariatesv8'
+
+/***********************************************************************************************************
+RETURN
+************************************************************************************************************/
+
+ereturn clear
+if `nbitems'>=3 {
+ if "`method'"=="cml" {
+ if "`test'"!="none" {
+ tempname AndersenZv8
+ matrix `AndersenZv8'=r(AndersenZ)
+ ereturn matrix AndersenZ=`AndersenZv8'
+ }
+ if "`dif'"!="" {
+ tempname DIFv8
+ matrix `DIFv8'=r(DIF)
+ ereturn matrix DIF=`DIFv8'
+ }
+ tempname cllv8
+ scalar `cllv8'=r(cll)
+ ereturn scalar cll=`cllv8'
+
+ }
+ if "`test'"!="NONE" {
+ tempname itemFitv8 globalFitv8
+ matrix `itemFitv8'=r(itemFit)
+ matrix `globalFitv8'=r(globalFit)
+ ereturn matrix itemFit=`itemFitv8'
+ ereturn matrix globalFit=`globalFitv8'
+ }
+}
+
+if "`method'"!="cml" {
+ tempname sigmav8 sesigmav8
+ local `sigmav8'=`r(sigma)'
+ local `sesigmav8'=`r(sesigma)'
+ ereturn scalar sigma=``sigmav8''
+ ereturn scalar sesigma=``sesigmav8''
+}
+
+tempname betav8 Varbetav8 thetav8 Varthetav8 llv8 AICv8
+matrix `betav8'=r(beta)
+matrix `Varbetav8'=r(Varbeta)
+ereturn matrix beta=`betav8'
+ereturn matrix Varbeta=`Varbetav8'
+matrix `thetav8'=r(theta)
+matrix `Varthetav8'=r(Vartheta)
+ereturn matrix theta=`thetav8'
+ereturn matrix Vartheta=`Varthetav8'
+scalar `llv8'=`r(ll)'
+scalar `AICv8'=`r(AIC)'
+ereturn scalar ll=`llv8'
+ereturn scalar AIC=`AICv8'
+ereturn scalar Zcomp=r(Zcomp)
+ereturn scalar pZcomp=r(pZcomp)
+
+
+if "`method'"=="mml" {
+ local psi=r(PSI)
+ local psiadj=r(PSIadj)
+ ereturn scalar PSI=`psi'
+ ereturn scalar PSIadj=`psiadj'
+}
+if "`covariates'"!="" {
+ tempname betacovariates Vbetacovariates zcovariates pcovariates
+ matrix `betacovariates'=r(betacovariates)
+ matrix `Vbetacovariates'=r(Vbetacovariates)
+ matrix `zcovariates'=r(zcovariates)
+ matrix `pcovariates'=r(pcovariates)
+
+ ereturn matrix betacovariates=`betacovariates'
+ ereturn matrix Vbetacovariates=`Vbetacovariates'
+ ereturn matrix zcovariates=`zcovariates'
+ ereturn matrix pcovariates=`pcovariates'
+}
+
+
+
+
+return clear
+
+end
diff --git a/Modules/ado/personal/r/rel.ado b/Modules/ado/personal/r/rel.ado
new file mode 100644
index 0000000..77dd72b
--- /dev/null
+++ b/Modules/ado/personal/r/rel.ado
@@ -0,0 +1,203 @@
+capture program drop rel
+program rel,rclass
+syntax varlist, PARTition(numlist integer >0) [SCOrename(string) Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3)]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+di as result "{hline}"
+di "{bf:Reliability}"
+di as result "{hline}"
+di
+
+local y = 1
+local nbitems = 0
+matrix aa = J(`P',4,.)
+
+foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+matrix d = J(`nbitems',2,.)
+
+local i = 1
+foreach x in `partition' {
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ *qui count if !=.
+
+ capture qui alpha `liste', asi item std
+ local al`i' = r(alpha)
+ local n`i' = e(N)
+
+ capture qui loevh `liste', pairwise
+ local h`i' = r(loevH)
+ mat a = r(Obs)
+ *local n`i' = a[1,1]
+ matrix c = r(loevHj)
+ matrix ct = c'
+
+
+ local lister = ""
+ forvalues w = `y'/`s' {
+ tempvar z
+ qui gen `z' = round(`var`w'')
+ local lister `lister' `z'
+ }
+
+ capture qui delta `lister'
+ local delt`i' = r(delta)
+
+
+ // on remplit d avec les valeurs de ct
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',1] = ct[`k',1]
+ matrix d[`j',2] = `i'
+ }
+
+ matrix aa [`i',1] = `al`i''
+ matrix aa [`i',2] = `delt`i''
+ matrix aa [`i',3] = `h`i''
+
+ local `i++'
+ local y = `s'+1
+}
+
+matrix rownames d = `varlist'
+local i = 1
+local y = 1
+
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ matrix C = d[`y'..`s',1.]
+ local min`i' = C[1,1]
+ local n : rownames C
+ tokenize `n'
+ local t`i' = "`1'"
+ forvalues j = 1/`x' {
+ local t = "``j''"
+ if C[`j',1] <= `min`i'' {
+ local min`i' = C[`j',1]
+ local t`i' = "``j''"
+ local itmin`i' = "``j''"
+ }
+ }
+ *di "`t`i''"
+ matrix aa [`i',4] = `min`i''
+ local `i++'
+ local y = `s'+1
+}
+
+matrix colnames aa = "alpha" "delta" "H" "Hj_min"
+
+if "`scorename'"=="" {
+ local i = 1
+ local y = 1
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local maxlen = 0
+foreach sco in `scorename' {
+ local w = length("`sco'")
+ if `w' > `maxlen' local maxlen = `w'
+}
+
+local i = 1
+local j = 1
+local y = 1
+local col = `maxlen'+8
+di _col(`col') "{bf:n}" _c
+local col = `col'+5
+di _col(`col') "{bf:alpha}" _c
+local col = `col'+8
+di _col(`col') "{bf:delta}" _c
+local col = `col'+11
+di _col(`col') "{bf:H}" _c
+local col = `col'+5
+di _col(`col') "{bf:Hj_min}"
+*di "{hline 41}"
+
+
+foreach s in `scorename' {
+ di in blue "{bf:`s'}" _c
+ local col = `maxlen'+3
+ local n : di %6.0f `n`i''
+ di in blue _col(`col') "{text:`n'}" _c
+ local col = `col'+10
+
+ local a : di %5.2f `al`i''
+ if `a' < `alpha' {
+ di _col(`col') "{error:`a'} " _c
+ }
+ else di _col(`col') "{text:`a'}" _c
+
+ local col = `col'+8
+ local d : di %5.2f `delt`i''
+ if `d' < `delta' {
+ di _col(`col') "{error:`d'} " _c
+ }
+ else di _col(`col') "{text:`d'}" _c
+
+ local col = `col'+8
+ local h : di %4.2f `h`i''
+ if `h' < `h' {
+ di _col(`col') "{error:`h'} " _c
+ }
+ else di _col(`col') "{text:`h'}" _c
+
+ local col = `col'+8
+ local m : di %6.2f `min`i''
+ if `m' < `hjmin' {
+ di _col(`col') "{error:`m'} " _c
+ di "{text:(item `itmin`i'')}" _c
+ }
+ else di _col(`col') "{text:`m'}" _c
+
+ di
+ local `++i'
+}
+
+end
+
+*rel ioc1-ioc37, partition(4 4 7 3 3 4 7 5) scorename(HA PSE W BCC AC AE LI MOC) a(0.7) d(0.9) h(0.3) hjmin(0.3)
+*rel x1-x40, partition(5 5 5 5 5 5 5 5) scorename(HA PSE W BCC AC AE LI MOC) a(0.7) d(0.9) h(0.3) hjmin(0.3)
diff --git a/Modules/ado/personal/r/repet.ado b/Modules/ado/personal/r/repet.ado
new file mode 100644
index 0000000..26cd4d2
--- /dev/null
+++ b/Modules/ado/personal/r/repet.ado
@@ -0,0 +1,275 @@
+capture program drop repet
+program repet,rclass
+syntax varlist [in], t2(varlist) PARTition(numlist integer >0) calcmethod(string) [SCOrename(string) KAPpa ICKAPpa(integer 0)]
+preserve
+
+local nbvars : word count `varlist'
+
+if "`in'"!="" {
+ qui keep `in'
+}
+
+if `ickappa' <= 0 {
+ local ickappa = ""
+}
+
+/*
+if "`ickappa'" != "" & "`kappa'" == "" {
+ di "{it:The ickappa option is ignored}"
+}
+*/
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+/*
+qui tab `id', nofreq
+local u = r(r)
+if `u' != _N {
+ di in red "The variable `ident' has not unique values"
+ exit
+}
+*/
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+else {
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local a:word count `varlist'
+local b:word count `t2'
+if `a' != `b' di in red "The number of items is not the same in t1 and t2"
+
+/* coupure noms des scores */
+/*
+local i = 1
+foreach s in `scorename' {
+ local len = length("`s'")
+ if `len' > 10 {
+ local c = substr("`s'",1,9)
+ local d = substr("`s'",-1,1)
+ local s`i' "`c'" "~" "`d'"
+ }
+ else local s`i' = "`s'"
+ local sc `sc' `s`i''
+ local `++i'
+}
+*/
+
+local i = 1
+foreach s in `scorename' {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+/* coupure noms des items */
+/*
+local i = 1
+foreach s in `varlist' {
+ local len = length("`s'")
+ if `len' > 10 {
+ local c = substr("`s'",1,9)
+ local var`i' "`c'"
+ }
+ else local var`i' = "`s'"
+ local `++i'
+}
+*/
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+local maxit = 1
+forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `maxit' local maxit = `len'
+}
+
+local decit = `maxit' + 4
+local colit = `decit'
+
+
+
+di as result "{hline}"
+di as result "{bf:Reproducibility}"
+di as result "{hline}"
+di
+
+foreach sco in `scorename' {
+ *local t = "`sco'bis"
+ tempname s
+ local scorename2 `scorename2' `s'
+}
+
+qui calcscore `t2', scorename(`scorename2') partition(`partition') calcmethod(`calcmethod')
+
+local i = 1
+foreach var in `varlist' {
+ tokenize `t2'
+ qui kap `var' ``i''
+ local k`i' = r(kappa)
+ if "`ickappa'" != "" {
+ qui kapci `var' ``i'', reps(`ickappa')
+ local lbk`i' = r(lb_bc)
+ local ubk`i' = r(ub_bc)
+ }
+ local `++i'
+}
+
+local i = 1
+foreach s in `scorename' {
+ tokenize `scorename2'
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ *qui drop `score' `temps' `id'
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+}
+
+tokenize `sc'
+local max = length("dimension")
+
+forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+}
+
+local dec = `max' + 5
+
+local i = 1
+local j = 1
+local y = 1
+di "{bf:Dimension}" _c
+di _col(`=`dec'+2') "{bf:n}" _c
+local col = `dec'+6
+di _col(`col') "{bf:Item}" _c
+local col = `col'+`decit'
+
+if "`kappa'" != "" {
+ di _col(`col') "{bf:Kappa}" _c
+ local col = `col'+10
+ if "`ickappa'" != "" {
+ di _col(`col') "{bf:95% CI for Kappa}" _c
+ local col = `col'+20
+ }
+
+}
+
+di _col(`=`col'+2') "{bf:ICC}" _c
+local col = `col'+9
+di _col(`col') "{bf:95% CI for ICC}"
+
+local zz = 0
+foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ local z : word count `levels'
+ if `z' > 2 local zz = 1
+}
+
+if "`kappa'" != "" & "`ickappa'" != "" & `zz' == 1 {
+ local col = `dec'+`decit'+16
+ di _col(`col') "{bf:(bootstrapped)}"
+}
+
+
+if "`ickappa'" != "" local h = `dec'+6+`decit'+10+8+21+12+1
+else if "`kappa'" != "" local h = `dec'+6+`decit'+10+8+21+12-20
+else local h = `dec'+6+`decit'+10+8+21+12-30
+di "{hline `h'}"
+
+local i = 1
+foreach p in `partition' {
+ tokenize `sc'
+ di "{bf:``i''}" _c
+ di _col(`dec') "{text:`n`i''}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+6
+ di _col(`col') "{text:`var`y''}" _c
+
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`y''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`i''
+ local ubk : di %5.2f `ubk`i''
+ local col = `col'+11
+ di _col(`col') "{text:[`lbk' ; `ubk']}" _c
+ local col = `decit'+50
+ }
+
+ else local col = `decit'+30
+ }
+ else local col = `decit'+20
+
+ *local col = `decit'+30
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+8
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ forvalues z = `w'/`s' {
+ local col = `dec'+6
+ di _col(`col') "{text:`var`z''}" _c
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`z''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`z''
+ local ubk : di %5.2f `ubk`z''
+ local col = `col'+11
+ di _col(`col')"{text:[`lbk' ; `ubk']}"
+ }
+ else di
+
+ }
+ else di
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+}
+end
+
+*repet ioc1-ioc37, t2(ptgi1-peur16) partition(4 4 7 3 3 4 7 5) scorename(HA PSE W BCC AC AE LI MOC) kappa ickappa(20)
+*repet sf36_3q_intenses sf36_3q_moderees sf36_3q_soulever sf36_3q_etages sf36_3q_etage sf36_3q_pencher sf36_3q_15km sf36_3q_500m sf36_3q_100m sf36_3q_douche sf36_4q_limite_temps_travail sf36_4q_moins_choses sf36_4q_type_travail sf36_4q_effort , t2(sf36_3q_intenses_v5 sf36_3q_moderees_v5 sf36_3q_soulever_v5 sf36_3q_etages_v5 sf36_3q_etage_v5 sf36_3q_pencher_v5 sf36_3q_15km_v5 sf36_3q_500m_v5 sf36_3q_100m_v5 sf36_3q_douche_v5 sf36_4q_limite_temps_travail_v5 sf36_4q_moins_choses_v5 sf36_4q_type_travail_v5 sf36_4q_effort_v5 ) partition(10 4)
diff --git a/Modules/ado/personal/r/rosali.ado b/Modules/ado/personal/r/rosali.ado
new file mode 100644
index 0000000..1276ba1
--- /dev/null
+++ b/Modules/ado/personal/r/rosali.ado
@@ -0,0 +1,3137 @@
+*! version 2.4 june2020
+*! Myriam Blanchin - Priscilla Brisson
+************************************************************************************************************
+* ROSALI: RespOnse-Shift ALgorithm at Item-level
+* Response-shift detection based on Rasch models family
+*
+* Version 1 : December 21, 2016 (Myriam Blanchin) /*rspcm122016*/
+* Version 1.1 : October 13, 2017 (Myriam Blanchin) /*option: MODA, automatic recoding of unused response categories*/
+* Version 2 : April, 2018 (Myriam Blanchin - Priscilla Brisson) /*option: GROUP, dichotomous group variable*/
+* Version 2.1 : October, 2018 (Myriam Blanchin - Priscilla Brisson) /* Version 1.1 + Version 2 */
+* Version 2.2 : February, 2019 (Priscilla Brisson) /* option nodif, optimization */
+* Version 2.3 : December, 2019 (Priscilla Brisson) /* option detail, + petites corrections */
+* Version 2.4 : June, 2020 (Myriam Blanchin) /* debug option detail + step C, modifs sorties et help */
+*
+* Myriam Blanchin, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* myriam.blanchin@univ-nantes.fr
+*
+* Priscilla Brisson, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* priscilla.brisson@univ-nantes.fr
+*
+* 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 rosali, rclass
+
+timer clear 1
+timer on 1
+
+syntax varlist(min=2 numeric) [if] [,GROUP(varlist) NODIF PRO DETail]
+
+preserve
+version 15
+tempfile saverspcm
+capture qui save `saverspcm',replace
+local save1=_rc
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`pro'" != "" {
+ di "START"
+}
+
+/**************************************************************************/
+set more off
+set matsize 5000
+constraint drop _all
+
+local gp "`group'"
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+
+ /* VĂ©rif nb d'items pair */
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di as error "You must enter an even number of items : the first half of the items represents the items at time 1 and the second half the items at time 2"
+ error 198
+ exit
+}
+
+local nbitems=`nbitems'/2
+
+
+if "`group'"=="" & "`nodif'"!="" {
+ di as error "nodif can only be used with the group option ({hi:nodif} option). Please correct this option."
+ error 198
+ exit
+}
+
+local nbc: word count `group'
+if `nbc' >= 2 {
+ di as error "Only one variable can be used for group option ({hi:group} option). Please correct this option."
+ error 198
+ exit
+}
+
+ /* VĂ©rif qu'il y a 2 groupes si l'option groupe est choisie */
+if "`group'"!="" {
+ qui tab `group'
+ local nbgrp = r(r)
+ if `nbgrp' != 2 {
+ di as error "Only 2 groups are possible for the group option ({hi:group} option). Please correct this option."
+ error 420
+ exit
+ }
+}
+/* recoder la variable de groupe en 0, 1*/
+
+if "`group'"!="" {
+ qui tab `gp', matrow(rep)
+ qui matrix list rep
+ if rep[1,1]+rep[2,1] != 1 & rep[1,1]*rep[2,1] != 0 {
+ forvalues i=1/`=rowsof(rep)'{
+ qui replace `gp'=`i'-1 if `gp'==rep[`i',1]
+ di "WARNING : `gp' `=rep[`i',1]' is now `gp' `=`i'-1' "
+ }
+ }
+ forvalues g = 0/1 {
+ qui tab `gp' if `gp' == `g'
+ local nbp_gp`g' = r(N)
+ }
+}
+
+
+
+/*item rename*/
+/*
+Items au temps 1 : 1 Ă nbitems ``j''
+Items au temps 2 : nbitems Ă 2*nbitems ``=`j'+`nbitems'''
+
+Si t varie, puis num item : ``=(`t'-1)*`nbitems'+`j'''
+*/
+
+
+local com_z = 0 // Indicatrice de recodage
+ /*verif modalités répondues*/
+if "`gp'" == "" { // Si pas d'option groupe
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'', matrow(rect1_`j') // Récupération des infos moda du temps 1
+ local minm`j'_t1 = rect1_`j'[1,1]
+ local maxm`j'_t1 = rect1_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''', matrow(rect2_`j') // Récupération des infos moda du temps 2
+ local minm`j'_t2 = rect2_`j'[1,1]
+ local maxm`j'_t2 = rect2_`j'[r(r),1]
+
+ local minm_`j' = min(`minm`j'_t1',`minm`j'_t2') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1',`maxm`j'_t2')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j'''
+
+ if `minm_`j'' != 0 & `com_z' == 0 {
+ local com_z = 1
+ }
+
+
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`nbm_`j'' {
+ qui count if ``j'' == `m'
+ local nb_rn1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m'
+ local nb_rn2 = r(N)
+ local nb_rn = min(`nb_rn1',`nb_rn2')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' <= `minm`j'_t1' | `m' <= `minm`j'_t2' { // La moda 0 ou les moda min ne sont pas utilisées
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged "
+ local stop = 0
+ }
+ }
+ }
+ else if `m' >= `maxm`j'_t1' | `m' >= `maxm`j'_t2' | `m' == `maxm_`j'' { // La (ou les) moda max ne sont pas utilisée(s)
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems''' =`=`m'-`k'' if ``=`j'+`nbitems''' ==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+else { // Cas oĂč l'option groupe est utilisĂ©e
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'' if `gp' == 0, matrow(rect1_g0_`j') matcell(nbrt1_g0_`j') // Récupération des infos moda du temps 1pour chaque groupe
+ local minm`j'_t1_g0 = rect1_g0_`j'[1,1]
+ local maxm`j'_t1_g0 = rect1_g0_`j'[r(r),1]
+
+ qui tab ``j'' if `gp' == 1, matrow(rect1_g1_`j') matcell(nbrt1_g1_`j')
+ local minm`j'_t1_g1 = rect1_g1_`j'[1,1]
+ local maxm`j'_t1_g1 = rect1_g1_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 0, matrow(rect2_g0_`j') matcell(nbrt2_g0_`j') // Récupération des infos moda du temps 2 pour chaque groupe
+ local minm`j'_t2_g0 = rect2_g0_`j'[1,1]
+ local maxm`j'_t2_g0 = rect2_g0_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 1 , matrow(rect2_g1_`j') matcell(nbrt2_g1_`j')
+ local minm`j'_t2_g1 = rect2_g0_`j'[1,1]
+ local maxm`j'_t2_g1 = rect2_g0_`j'[r(r),1]
+
+ local minm_`j' = min(`minm`j'_t1_g0',`minm`j'_t2_g0',`minm`j'_t1_g1',`minm`j'_t2_g1') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1_g0',`maxm`j'_t2_g0',`maxm`j'_t1_g1',`maxm`j'_t2_g1')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j''+1'
+
+ if `minm_`j'' != 0 & `com_z' == 0 {
+ local com_z = 1
+ }
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`=`nbm_`j''-1' {
+ qui count if ``j'' == `m' & `gp' == 0
+ local nb_rn1_g0 = r(N)
+ qui count if ``j'' == `m' & `gp' == 1
+ local nb_rn1_g1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 0
+ local nb_rn2_g0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 1
+ local nb_rn2_g1 = r(N)
+ local nb_rn = min(`nb_rn1_g0',`nb_rn2_g0',`nb_rn1_g1',`nb_rn2_g1')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' < `minm`j'_t1_g0' | `m' < `minm`j'_t2_g0' | `m' < `minm`j'_t1_g1' | `m' < `minm`j'_t2_g1' { // La moda 0 n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else if `m' == `=`nbm_`j''-1' | `m' >= `maxm`j'_t2_g0' | `m' >= `maxm`j'_t1_g1' | `m' >= `maxm`j'_t2_g1' { // La moda max n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`m'' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0 ) & `stop' != 0 {
+ qui replace ``j''= `=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else { // Moda central non utilisée
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'-`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0{
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if `com_z' == 1 {
+ di
+ di "WARNING : Automatic recoding, the first response category is 0. see {help rosali:help rosali}."
+ di
+}
+
+forvalues j =1/`nbitems' {
+ qui tab ``j'', matrow(rec) // Récupération des infos moda du temps 1
+ local nbm`j'_t1 = r(r)
+
+ qui tab ``=`j'+`nbitems''' // Récupération des infos moda du temps 2
+ local nbm`j'_t2 = r(r)
+
+ local nbm_`j' = max(`nbm`j'_t1', `nbm`j'_t2')
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`nbm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=rec[`=`r'+1',1]'
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=rec[`=`r'+1',1]'
+ }
+}
+
+/* Calcul de nbmoda & nbdif */
+forvalues j = 1/`nbitems' {
+ qui tab ``j''
+ local nbmoda_`j' = r(r)
+ local nbdif_`j' = r(r) - 1
+}
+
+local maxdif = 0
+local nbmoda_sum = 0
+forvalues j = 1/`nbitems' {
+ if `maxdif' < `nbdif_`j'' {
+ local maxdif = `nbdif_`j''
+ }
+ local nbmoda_sum = `nbmoda_sum' + `nbdif_`j''
+}
+
+/* Au moins 2 moda par item */
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' == 1 {
+ di as error "``j'' have only one response category, the analysis can be performed only if each item has at least 2 response categories"
+ error 198
+ exit
+ }
+}
+
+local coln ""
+forvalues j =1 /`nbitems' {
+ local coln "`coln' ``j''"
+}
+
+matrix nbmod = J(2,`nbitems',.)
+
+matrix colnames nbmod = `coln'
+matrix rownames nbmod = NbModa Recoding
+
+forvalues j = 1/`nbitems' {
+ matrix nbmod[1,`j'] = `nbmoda_`j''
+ matrix nbmod[2,`j'] = `recoda_`j''
+}
+
+*Erreur si plus de 200 difficultés
+local nb_test = 0
+forvalues j=1/`nbitems' {
+ local nb_test = `nb_test'+`nbmoda_`j'' -1
+}
+
+if `nb_test' >= 200 {
+ di as error "The total number of items difficulties to be estimated must be less than 200 ({hi:moda} option option)."
+ error 198
+ exit
+}
+
+local nbitp = 0
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ local nbitp = `nbitp' + 1
+ }
+}
+
+qui count
+local nbpat = r(N)
+
+
+/*********************************
+* AFFICHAGE INITIAL
+*********************************/
+di
+di _col(5) "{hline 78}"
+di _col(15) "Time 1" _col(42) "Time 2" _col(65) "Nb of Answer Cat."
+di _col(5) "{hline 78}"
+forvalues j=1/`nbitems' {
+ di as text _col(15) abbrev("``j''",20) _col(42) abbrev("``=`j'+`nbitems'''",20) _col(65) `nbmoda_`j''
+}
+di _col(5) "{hline 78}"
+if "`group'" != "" {
+ di _col(10) "Nb of patients: " abbrev("`gp'",20) " 0 = `nbp_gp0' ;", abbrev("`gp'",20) " 1 = `nbp_gp1'"
+ di _col(5) "{hline 78}"
+}
+else {
+ di _col(10) "Nb. of patients: `nbpat'"
+ di _col(5) "{hline 78}"
+}
+di
+if `nbitems' == 1 {
+ di as error "The analysis can only be performed with at least 2 items."
+ error 198
+ exit
+}
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' == 2 {
+ di "WARNING: ``j'' has only 2 response categories, no distinction can be made between uniform or non-uniform recalibration."
+ }
+ if `nbmoda_`j'' == 1 {
+ di as error "Only `nbmoda_`j'' response categories of item ``j'' were used by the sample, the analysis cannot be performed."
+ error 198
+ exit
+ }
+ if `nbmoda_`j'' == 0 {
+ di as error "No response categories of item ``j'' were used by the sample, the analysis cannot be performed."
+ error 198
+ exit
+ }
+}
+di
+if "`group'" != "" {
+ di _col(2) as text "For all models : - mean of the latent trait in `gp' 0 at time 1 is constrained at 0"
+ di _col(19) "- equality of variances between groups"
+ di
+}
+else {
+ di _col(2) as text "For all models : mean of the latent trait at time 1 is constrained at 0"
+ di
+}
+
+
+
+/*********************************
+* DEFINITION DES CONTRAINTES
+*********************************/
+
+if "`group'"!="" { // Contraintes si option groupe
+ *EGALITE ENTRE GROUPES A T1 (1-200)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=0+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``j'']1.`gp'
+ }
+ }
+
+ *DIF UNIFORME A T1 (201-400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=200+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'-[`p'.``j'']0bn.`gp'=`p'*[1.``j'']1.`gp'-`p'*[1.``j'']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 0 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 1 (601-800)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=600+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'
+ }
+ }
+
+ * RC COMMUNE (801-1000)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=800+`maxdif'*(`j'-1)+`p'' [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 0 (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 1 (1201-1400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1200+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ *Sans interaction temps x groupe
+ constraint 1999 [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'=[/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+}
+else { //Contraintes si pas d'option groupe
+ *EGALITE ENTRE T1 et T2 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']:_cons = [`p'.``=`j'+`nbitems''']:_cons
+ }
+ }
+ *RC UNIFORME (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']:_cons - [1.``j'']:_cons)=[`p'.``=`j'+`nbitems''']:_cons -[`p'.``j'']:_cons
+ }
+ }
+}
+
+/*********************************
+* MATRICE DES RESULTATS
+*********************************/
+matrix dif_rc=J(`nbitems',8,.)
+matrix colnames dif_rc=DIFT1 DIFU RC RC_DIF RCG0 RCUG0 RCG1 RCUG1
+local rown ""
+
+forvalues j =1 /`nbitems' {
+ local rown "`rown' ``j''"
+}
+matrix rownames dif_rc = `rown'
+
+*Nb modalité max
+local nbdif_max = 0
+forvalues j=1/`nbitems' {
+ if `nbdif_max' < `nbdif_`j'' {
+ local nbdif_max = `nbdif_`j''
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 1 : DIF A T1 ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+
+if "`group'"!="" & "`nodif'"=="" { // PARTIE 1 = Slmt si option group & pas de "nodif"
+
+ di _dup(49) "_ "
+ di
+ di as input "PART 1: DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS AT TIME 1"
+
+ *********************************
+ ** MODEL B **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading cons) var(0: THETA@v) var(1:THETA@v) latent(THETA) nocapslatent
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifB
+ matrix val_mB = r(table)
+ matrix esti_B = e(b)
+
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mB=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+
+ matrix colnames delta_mB = `name_partOneC'
+ matrix rownames delta_mB = `name_partOneL'
+ matrix delta_mB_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mB_se = `name_partOneC_se'
+ matrix rownames delta_mB_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB=r(estimate)
+ local delta`j'_`p'g`g'mB_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB = r(estimate)
+ local delta`j'_`p'g`g'mB_se = r(se)
+ }
+ matrix delta_mB[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB'
+ matrix delta_mB_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB_se'
+ }
+ }
+ }
+
+ matrix var_mB = (val_mB[1,"/var(THETA)#0bn.`gp'"]\val_mB[2,"/var(THETA)#0bn.`gp'"])
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmB=r(estimate)
+ local segeffmB=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmBp=r(p)
+ local gcmBchi=r(chi2)
+ local gcmBdf=r(df)
+
+
+ *********************************
+ ** MODEL A **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading means) var(0: THETA@v) var(1:THETA@v) from(esti_B, skip) latent(THETA) nocapslatent
+
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifA
+ matrix val_mA = r(table)
+ matrix esti_A = e(b)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mA=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mA = `name_partOneC'
+ matrix rownames delta_mA = `name_partOneL'
+ matrix delta_mA_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mA_se = `name_partOneC_se'
+ matrix rownames delta_mA_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA=r(estimate)
+ local delta`j'_`p'g`g'mA_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA = r(estimate)
+ local delta`j'_`p'g`g'mA_se = r(se)
+ }
+ matrix delta_mA[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA'
+ matrix delta_mA_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA_se'
+ }
+ }
+ }
+ //Variance et se mA
+ matrix var_mA = (val_mA[1,"/var(THETA)#0bn.`gp'"]\val_mA[2,"/var(THETA)#0bn.`gp'"])
+
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+
+
+ //Affichage modĂšle A
+ di
+ di as input "PROCESSING STEP A"
+ di
+
+ if "`detail'" != "" {
+ /* Affichage des estimations des difficultés modÚle A */
+
+ di _col(5) as text "{ul:MODEL A:} Overall measurement non-invariance between groups"
+ di
+ di %~85s as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 65}"
+ di _col(31) as text abbrev("`gp'",20) "=0" _col(57) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 65}"
+ forvalues j=1/`nbitems' {
+ di as text _col(10) abbrev("``j''", 18)
+ forvalues p=1/`nbdif_`j'' {
+ di as text _col(10) "`p'" as result _col(30) %6.2f `delta`j'_`p'g0mA' %6.2f " (" %3.2f `delta`j'_`p'g0mA_se' ")" _col(56) %6.2f `delta`j'_`p'g1mA' " (" %3.2f `delta`j'_`p'g1mA_se' ")"
+ }
+ }
+ di as text _col(10) "{hline 65}"
+ /* Affichage des estimations sur le trait latent du modĂšle A */
+ di
+ di %~85s as text "Latent trait distribution"
+ di _col(10) "{hline 65}"
+ di _col(31) "Estimate" _col(57) "Standard error"
+ di _col(10) "{hline 65}"
+ di _col(10) "Variance" as result _col(31) %6.2f `=var_mA[1,1]' _col(55) %6.2f `=var_mA[2,1]'
+ di _col(10) as text "Group effect" as result _col(31) "0 (constrained)"
+ di _col(10) as text "{hline 65}"
+ di
+ di _col(10) as text "No group effect: equality of the latent trait means between groups"
+ di _col(10) as text "All item difficulties are freely estimated in both groups"
+ di
+ }
+ //*Affichage modĂšle B
+
+ di
+ di as input "PROCESSING STEP B"
+ di
+
+ /* Affichage des estimations des difficultés modÚle B */
+ if "`detail'" != "" {
+ di _col(5) as text "{ul:MODEL B:} Overall measurement invariance between groups"
+ di
+ di %~85s as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 65}"
+ di _col(31) abbrev("`gp'",20) "=0" _col(57) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 65}"
+
+ forvalues j=1/`nbitems' {
+ di _col(10) as text "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ di as text _col(10) "`p'" as result _col(30) %6.2f `delta`j'_`p'g0mB' " (" %3.2f `delta`j'_`p'g0mB_se' ")" _col(56) %6.2f `delta`j'_`p'g1mB' " (" %3.2f `delta`j'_`p'g1mB_se' ")"
+ }
+ }
+
+ di _col(10) as text "{hline 65}"
+ /* Affichage des estimations sur le trait latent du modĂšle B */
+ di
+ di %~85s as text "Latent trait distribution"
+ di _col(10) "{hline 65}"
+ di _col(28) "Estimate" _col(42) "Standard error" _col(62) "P-value"
+ di _col(10) "{hline 65}"
+ di _col(10) "Variance" as result _col(28) %6.2f `=var_mB[1,1]' _col(40) %6.2f `=var_mB[2,1]'
+ di _col(10) as text "Group effect" as result _col(28) %6.2f `geffmB' _col(40) %6.2f `segeffmB' _col(62) %6.4f `gcmBp'
+ di _col(10) as text "{hline 65}"
+ di
+ di _col(10) as text "Group effect estimated: mean of the latent trait of group 1 freely estimated"
+ di _col(10) "Equality of the item difficulties between groups"
+ di
+ }
+
+ *****************************************************
+ * ModĂšle A vs ModĂšle B *
+ *****************************************************
+
+ qui lrtest modeldifA modeldifB
+ local diftestp=r(p)
+ local diftestchi=r(chi2)
+ local diftestdf=r(df)
+ if "`detail'" != "" {
+ //affichage lrtest
+ di as input "LIKELIHOOD-RATIO TEST"
+ di
+ di %~60s "Model A vs Model B"
+ di _col(10) "{hline 40}"
+ di _col(10) as text "Chi-square" _col(28) "DF" _col(40) "P-value"
+ di _col(10) as result %6.2f `diftestchi' _col(28) %2.0f `diftestdf' _col(40) %6.4f `diftestp'
+ di _col(10) as text "{hline 40}"
+ di
+ }
+
+ if `diftestp'<0.05{
+ di as result "DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS LIKELY"
+ }
+ else{
+ di as result "NO DIFFERENCE BETWEEN GROUPS DETECTED"
+ }
+ *********************************
+ *************MODEL C*************
+ *********************************
+ // Etape itérative si lrtest significatif
+ local nb_stepC = 0
+ if `diftestp'<0.05{ /*If pvalue(LRtest)<0.05 then step C*/
+ di
+ di as input "PROCESSING STEP C"
+ di
+
+ /*test DIF pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ while `boucle'<=`=`nbitp'-1' & `stop'==0{ /*on s'arrĂȘte quand on a libĂ©rĂ© du DIF sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_stepC = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle''
+ /*réinitialisation de la matrice de test*/
+ matrix test_difu_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_difu_`boucle'=chi_DIFU df_DIFU pvalueDIFU
+ matrix test_dif_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_dif_`boucle'=chi_DIF df_DIF pvalueDIF
+ local nbsig=0
+ local minpval=1
+ local itemdif=0
+ if "`detail'" != ""{
+
+ di as text "Loop `boucle'"
+ di as text _col(5) "Adjusted alpha: " %6.4f `pajust'
+ di
+ di as text _col(10) "{hline 65}"
+ di as text _col(10) "Freed item" _col(31) "Chi-Square" _col(48) "DF" _col(57) "P-Value"
+ di as text _col(10) "{hline 65}"
+ }
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ //if `nbdif_`j'' > 2 {
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF déjà détecté sur l'item j*/
+ /*on libĂšre le DIF de l'item i: pas de contraintes*/
+ forvalues k=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if `k'!=`j' & `nbmoda_`j'' >= 2 {
+ if dif_rc[`k',1]==. | dif_rc[`k',1]==0 {/*pas de DIF sur item k: contraintes 1-200*/
+ forvalues p=1/`nbdif_`k''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!= 0 & `nbmoda_`k'' > 2 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`k''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B) latent(THETA) nocapslatent
+ estimates store modeldif3b`boucle'it`i'
+
+ *************************
+ *****test DIF item i*****
+ *************************
+ qui test [1.``j'']1.`gp'=[1.``j'']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``j'']0bn.`gp', acc
+ }
+ }
+ matrix test_dif_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+ /* Test DIF Uniforme */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``j'']1.`gp'-[1.``j'']0bn.`gp')=[2.``j'']1.`gp'-[2.``j'']0bn.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``j'']1.`gp'-[1.``j'']0bn.`gp')=[`p'.``j'']1.`gp'-[`p'.``j'']0bn.`gp', acc
+ }
+ matrix test_difu_`boucle'[`j',1]=(r(chi2), r(df), r(p))
+ }
+
+ if test_dif_`boucle'[`j',3]<`pajust'{/*si DIF sur item i*/
+ local ++nbsig
+ if test_dif_`boucle'[`j',3]<`minpval'{
+ local minpval=test_dif_`boucle'[`j',3]
+ local itemdif=`j'
+ }
+ }
+ if "`detail'" != "" {
+ di as text _col(10) abbrev("``j''",15) as result _col(31) %6.3f test_dif_`boucle'[`j',1] _col(48) test_dif_`boucle'[`j',2] _col(57) %6.4f test_dif_`boucle'[`j',3]
+ }
+ }
+ }
+ /*si nb de tests significatifs=0, on arrĂȘte*/
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ if "`detail'" != "" {
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "No significant test: no difference between groups detected, no DIF detected"
+ di
+ }
+ }
+ else {
+ if "`detail'" != ""{
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "No other significant tests"
+ di
+ }
+ }
+ }
+ else{/*si nb de tests significatifs>0, mise à jour de la matrice de résultats*/
+ matrix dif_rc[`itemdif',1]=`boucle'
+ if "`detail'" != ""{
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "Difference between groups on ``itemdif'' at time 1"
+ }
+ if `nbmoda_`itemdif'' > 2 {
+ if "`detail'" != "" {
+
+ di
+ di %~60s as text "Test of uniform difference"
+ di _col(10) "{hline 40}"
+ di _col(10) as text "Chi-square" _col(28) "DF" _col(40) "P-value"
+ di _col(10) as result %4.2f `=test_difu_`boucle'[`itemdif',1]' _col(28) `=test_difu_`boucle'[`itemdif',2]' _col(40) %4.2f `=test_difu_`boucle'[`itemdif',3]'
+ di _col(10) as text "{hline 40}"
+ }
+ if test_difu_`boucle'[`itemdif',3]<0.05{ /*DIF NU détectée*/
+ matrix dif_rc[`itemdif',2]=0
+ di
+ di as result "``itemdif'' : Non-uniform differences of item difficulties between groups at T1"
+ di
+ }
+ else{/*DIF U détectée*/
+ matrix dif_rc[`itemdif',2]=`boucle'
+ di
+ di as result "``itemdif'' : Uniform differences of item difficulties between groups at T1"
+ di
+ }
+ }
+ else {
+ // Différence entre groupes au temps 1 mais slmt 2 moda. donc pas de U ou NU
+ di _col(15) _dup(60) "-"
+ }
+ }
+ local ++boucle
+ }
+ }
+
+ /* MODELE FINAL DE LA PARTIE 1. Si DIFT1 détecté (=Au moins 2 boucles dans l'étape C)*/
+ if `nb_stepC' > 1 {
+ forvalues j=1/`nbitems'{
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B) latent(THETA) nocapslatent
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifCFin
+ matrix val_mC = r(table)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mCFin=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mCFin = `name_partOneC'
+ matrix rownames delta_mCFin = `name_partOneL'
+
+ matrix delta_mCFin_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+ matrix colnames delta_mCFin_se = `name_partOneC_se'
+ matrix rownames delta_mCFin_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin=r(estimate)
+ local delta`j'_`p'g`g'mCFin_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin = r(estimate)
+ local delta`j'_`p'g`g'mCFin_se = r(se)
+ }
+ matrix delta_mCFin[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin'
+ matrix delta_mCFin_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin_se'
+ }
+ }
+ }
+ if "`group'" != "" { //Variance et se mA
+ matrix var_mC = (val_mC[1,"/var(THETA)#0bn.`gp'"]\val_mC[2,"/var(THETA)#0bn.`gp'"])
+ }
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmCFin=r(estimate)
+ local segeffmCFin=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmCFinp=r(p)
+ local gcmCFinchi=r(chi2)
+ local gcmCFindf=r(df)
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 2 : RECALIBRATION ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+
+di
+di as text _dup(49) "_ "
+di
+if "`group'" != "" {
+ di as input "PART 2 : DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIME (RECALIBRATION)"
+}
+else {
+ di as input "DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIME (RECALIBRATION)"
+}
+
+ *********************************
+ ** MODEL 2 **
+ *********************************
+
+local listconst "" // liste des contraintes si option groupe
+local listconst_g "" //LIste des contraintes sans option groupe (Notation peu logique !!)
+
+forvalues j=1/`nbitems'{
+ if "`group'" == "" { // Contraintes pas de RC pour tous les items
+ forvalues p=1/`nbdif_`j''{
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF Ă T1 sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 200*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 0 (401-600)*/
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 1 (601-800)*/
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+}
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+*di "gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') latent(THETA1 THETA2) nocapslatent"
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') latent(THETA1 THETA2) nocapslatent
+}
+
+/*Stockage des données du modÚle 2 */
+estimates store model2
+matrix val_m2 = r(table)
+matrix esti_2 = e(b)
+
+if "`group'" != "" {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)#0bn.`gp'"],val_m2[1,"/var(THETA2)#0bn.`gp'"]\val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"]\val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)"]\val_m2[2,"/cov(THETA1,THETA2)"]\val_m2[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm2=r(estimate)
+ local segeffm2=r(se)
+ local ubgeffm2 = r(ub)
+ local lbgeffm2 = r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm2p=r(p)
+ local gpm2chi=r(chi2)
+ local gpm2df=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* [/]:mean(THETA1)*/
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2) = 0 /* [/]:mean(THETA1)*/
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ local interm2=r(estimate)
+ local seinterm2=r(se)
+ local ubinterm2 = r(ub)
+ local lbinterm2 = r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ local interm2p=r(p)
+ local interm2chi=r(chi2)
+ local interm2df=r(df)
+}
+
+if "`group'" != "" {
+ matrix mod2 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod2 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2= r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se= r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2=r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se=r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2= r(estimate)
+ local delta`t'_`j'_`p'g0m2_se= r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2=r(estimate)
+ local delta`t'_`j'_`p'g0m2_se=r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod2[1,`=4*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)#0bn.`gp'"], val_m2[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)#0bn.`gp'"],val_m2[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)#0bn.`gp'"],val_m2[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = `seinterm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2p'
+}
+else {
+ matrix mod2[1,`=2*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)"],val_m2[6,"/var(THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)"],val_m2[5,"/var(THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm2'
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm2'
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm2'
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm2'
+ matrix mod2[5,`=2*`nbmoda_sum'+2+1+1'] = `tm2chi'
+ matrix mod2[6,`=2*`nbmoda_sum'+2+1+1'] = `tm2df'
+ matrix mod2[7,`=2*`nbmoda_sum'+2+1+1'] = `tm2p'
+}
+
+ *********************************
+ ** MODEL 1 **
+ *********************************
+
+
+/*PCM longitudinal, no true change, group effect, interaction*/
+local listconst ""
+forvalues j=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if `nbdif_`j'' > 1 {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 201*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+}
+
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'"!="" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@0) means(1: THETA1@m1 THETA2@m1) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@0) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+
+/* Stockage des estimations du modĂšle 1 */
+estimates store model1
+matrix val_m1 = r(table)
+
+/* Calcul des difficultés d'item (delta_j) */
+matrix delta_m1 = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC ""
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' delta_t`t'_`p'_gp`g'"
+ }
+ }
+}
+
+local name_partTwoL ""
+forvalues j=1/`=`nbitems'*2' {
+ if `j' <= `nbitems' {
+ local name_partTwoL "`name_partTwoL' ``j''"
+ }
+ else {
+ local name_partTwoL "`name_partTwoL' ``=`nbitems'+`j'''"
+ }
+}
+
+matrix colnames delta_m1 = `name_partTwoC'
+matrix rownames delta_m1 = `name_partTwoL'
+
+matrix delta_m1_se = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC_se ""
+
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC_se "`name_partTwoC_se' delta_t`t'_`p'_gp`g'_se"
+ }
+ }
+}
+
+matrix colnames delta_m1_se = `name_partTwoC_se'
+matrix rownames delta_m1_se = `name_partTwoL'
+
+if "`group'"!="" {
+ forvalues t=1/2{
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1= r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1=r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ }
+ }
+ }
+ }
+}
+else {
+ forvalues t=1/2 {
+ forvalues j=1/`nbitems' {
+ forvalues p = 1/`nbdif_`j'' {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1= r(estimate)
+ local delta`t'_`j'_`p'g0m1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1=r(estimate)
+ local delta`t'_`j'_`p'g0m1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)#0bn.`gp'"],val_m1[1,"/var(THETA2)#0bn.`gp'"]\val_m1[2,"/var(THETA1)#0bn.`gp'"],val_m1[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)"],val_m1[1,"/var(THETA2)"]\val_m1[2,"/var(THETA1)"],val_m1[2,"/var(THETA2)"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)"]\val_m1[2,"/cov(THETA1,THETA2)"]\val_m1[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'"!="" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm1=r(estimate)
+ local segeffm1=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ local gpm1p=r(p)
+ local gpm1chi=r(chi2)
+ local gpm1df=r(df)
+}
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+ di
+ di as input "PROCESSING STEP 1"
+ di
+
+if "`detail'" != "" {
+ // Affichage du modĂšle 1
+
+ /* Affichage des estimations des difficultés */
+
+ if "`group'" != "" {
+ di _col(5) as text "{ul:MODEL 1:} Overall longitudinal measurement non-invariance across time (RS on all items)"
+ di
+ di %~105s as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(38) "Time 1" _col(76) "Time 2"
+ di as text _col(26) abbrev("`gp'",15) "=0" _col(44) abbrev("`gp'",15) "=1" _col(64) abbrev("`gp'",15) "=0" _col(82) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di _col(5) as text "{ul:MODEL 1:} Overall longitudinal measurement non-invariance across time (RS on all items)"
+ di
+ di %~70s as text as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(25) "Time 1" _col(42) "Time 2"
+ di _col(10) "{hline 50}"
+ }
+
+ forvalues j=1/`nbitems' {
+ di as text _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(43) %6.2f `delta1_`j'_`p'g1m1' " (" %4.2f `delta1_`j'_`p'g1m1_se' ")" ///
+ _col(63) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")" _col(81) %6.2f `delta2_`j'_`p'g1m1' " (" %4.2f `delta2_`j'_`p'g1m1_se' ")"
+ }
+ else {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")"
+ }
+ }
+ }
+ if "`group'" != "" {
+ di _col(10) as text "{hline 85}"
+ }
+ else {
+ di _col(10) as text "{hline 50}"
+ }
+ /* Affichage des estimations du trait latent du modĂšle 1 */
+
+ di
+ if "`group'" != "" {
+ di %~85s as text "Latent trait distribution"
+ di _col(10) "{hline 65}"
+ di _col(28) "Estimate" _col(46) "Standard error" _col(64) "P-value"
+ di _col(10) "{hline 65}"
+ }
+ else {
+ di %~70s as text "Latent trait distribution"
+ di _col(10) "{hline 50}"
+ di _col(28) as text "Estimate" _col(44) "Standard error" "
+ di _col(10) "{hline 50}"
+ }
+ di _col(10) as text "Variance Time 1" as result _col(28) %6.2f `=var_m1[1,1]' _col(44) %6.2f `=var_m1[2,1]'
+ di _col(10) as text "Variance Time 2" as result _col(28) %6.2f `=var_m1[1,2]' _col(44) %6.2f `=var_m1[2,2]'
+ di _col(10) as text "Covariance" as result _col(28) %6.2f `=covar_m1[1,1]' _col(44) %6.2f `=covar_m1[2,1]'
+ if "`group'" != "" {
+ di _col(10) as text "Group effect" as result _col(28) %6.2f `geffm1' _col(44) %6.2f `segeffm1' _col(64) %6.4f `gpm1p'
+ }
+ di _col(10) as text "Time effect" as result _col(28) "0 (constrained)"
+ if "`group'" != "" {
+ di _col(10) as text "TimexGroup inter" as result _col(28) "0 (constrained)"
+ }
+ if "`group'" != "" {
+ di _col(10) as text "{hline 65}"
+ }
+ else {
+ di _col(10) as text "{hline 50}"
+ }
+ di
+ if "`group'" != "" {
+ di _col(10) as text "Group effect estimated: mean of the latent trait of group 1 at time 1 freely estimated"
+ di _col(10) as text "No time effect: equality of means of the latent trait of group 0 across time"
+ di _col(10) as text "All item difficulties freely estimated across time"
+ }
+ else{
+ di _col(10) as text "No time effect: equality of means of the latent trait across time"
+ di _col(10) as text "All item difficulties freely estimated across time"
+ }
+}
+ //Affichage du modĂšle 2
+di
+di as input "PROCESSING STEP 2"
+di
+if "`detail'" != "" {
+ /* Affichage des estimations des difficultés */
+ di _col(5) as text "{ul:MODEL 2:} Overall longitudinal measurement invariance across time (no RS)"
+ di
+ if "`group'" != "" {
+ di %~105s as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(38) "Time 1" _col(76) "Time 2"
+ di as text _col(26) abbrev("`gp'",15) "=0" _col(44) abbrev("`gp'",15) "=1" _col(64) abbrev("`gp'",15) "=0" _col(82) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di %~70s as text as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(25) "Time 1" _col(42) "Time 2"
+ di _col(10) "{hline 50}"
+ }
+
+ forvalues j=1/`nbitems' {
+ di as text _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(43) %6.2f `delta1_`j'_`p'g1m2' " (" %4.2f `delta1_`j'_`p'g1m2_se' ")" ///
+ _col(63) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")" _col(81) %6.2f `delta2_`j'_`p'g1m2' " (" %4.2f `delta2_`j'_`p'g1m2_se' ")"
+ }
+ else {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")"
+ }
+ }
+ }
+ if "`group'" != "" {
+ di as text _col(10) "{hline 85}"
+ }
+ else {
+ di as text _col(10) "{hline 50}"
+ }
+ /* Affichage des estimations du trait latent du modĂšle 2 */
+ di
+ di %~85s as text "Latent trait distribution"
+ di _col(10) "{hline 65}"
+ di _col(28) as text "Estimate" _col(46) "Standard error" _col(64) "P-value"
+ di _col(10) "{hline 65}"
+
+ if "`group'" == "" {
+ local fact_k = 2
+ }
+ else {
+ local fact_k = 4
+ }
+
+ di _col(10) as text "Variance Time 1" as result _col(28) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+1']' _col(44) %6.2f =mod2[2,`=`fact_k'*`nbmoda_sum'+1']
+ di _col(10) as text "Variance Time 2" as result _col(28) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+2']' _col(44) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+2']'
+ di _col(10) as text "Covariance" as result _col(28) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+3']' _col(44) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+3']'
+ if "`group'" != "" {
+ di _col(10) as text "Group effect" as result _col(28) %6.2f `geffm2' _col(44) %6.2f `segeffm2' _col(64) %6.4f `gpm2p'
+ }
+ di _col(10) as text "Time effect" as result _col(28) %6.2f `teffm2' _col(44) %6.2f `seteffm2' _col(64) %6.4f `tm2p'
+ if "`group'" != "" {
+ di _col(10) as text "TimexGroup inter" as result _col(28) %6.2f `interm2' _col(44) %6.2f `seinterm2' _col(64) %6.4f `interm2p'
+ }
+ di as text _col(10) "{hline 65}"
+ di
+ if "`group'" != "" {
+ di _col(10) as text "Group effect estimated: mean of the latent trait of group 1 at time 1 freely estimated"
+ di _col(10) as text "Time effect estimated: mean of the latent trait of group 0 at time 2 freely estimated"
+ di _col(10) as text "Equality of all item difficulties across time"
+ }
+ else {
+ di _col(10) as text "Time effect estimated: mean of the latent trait at time 2 freely estimated"
+ di _col(10) as text "Equality of all item difficulties across time"
+ }
+ di
+}
+
+ *****************************************************
+ * ModĂšle 1 vs ModĂšle 2 *
+ *****************************************************
+qui lrtest model2 model1
+
+local rstestp=r(p)
+local rstestchi=r(chi2)
+local rstestdf=r(df)
+if "`detail'" != "" {
+
+ di as input "LIKELIHOOD-RATIO TEST
+ di
+ di %~60s "Model 1 vs Model 2"
+ di _col(10) "{hline 40}"
+ di _col(10) as text "Chi-square" _col(28) "DF" _col(40) "P-value"
+ di _col(10) as result %6.2f `rstestchi' _col(28) %2.0f `rstestdf' _col(40) %6.4f `rstestp'
+ di _col(10) as text "{hline 40}"
+ di
+}
+if `rstestp'<0.05{
+ di as result "DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIME LIKELY"
+}
+else{
+ di as result "NO DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIME DETECTED, NO RECALIBRATION DETECTED"
+}
+ *********************************
+ *************MODEL 3*************
+ *********************************
+// Etape itérative si lrtest significatif
+local nb_step3=0
+
+if `rstestp' < 0.05 { /* If pvalue(LRtest)<0.05 then step 3 */
+ di
+ di as input "PROCESSING STEP 3"
+ di
+
+ /*test RC pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ //matrix list dif_rc
+ while `boucle' <= `=`nbitp'-1' & `stop' == 0 { /*on s'arrĂȘte quand on a libĂ©rĂ© du RC sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_step3 = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle'' // local pajust=0.05/`=`nbitems'+1-`boucle'
+ if "`group'" != "" {
+ local pajust2 = 0.05/`nbgrp'
+ }
+ /*réinitialisation de la matrice de test*/
+ matrix test_rc_`boucle'=J(`nbitems',9,.)
+ matrix test_rcCOMM_`boucle'=J(`nbitems',3,.)
+ matrix test_rcU_`boucle'=J(`nbitems',6,.)
+ matrix colnames test_rc_`boucle'= chi_RC df_RC pvalue_RC chi_RCg0 df_RCg0 pvalue_RCg0 chi_RCg1 df_RCg1 pvalue_RCg1
+ matrix colnames test_rcCOMM_`boucle'= chi_RCCOMM df_RCCOMM pvalue_RCCOMM
+ matrix colnames test_rcU_`boucle'= chi_RCUg0 df_RCUg0 pvalue_RCUg0 chi_RCUg1 df_RCUg1 pvalue_RCUg1
+ local nbsig=0
+ local minpval=1
+ local itemrc=0
+ if "`detail'" != "" {
+ di as text "Loop `boucle'"
+ di _col(5) "Adjusted alpha : " %6.4f `pajust'
+ di
+ di as text _col(10) "{hline 65}"
+ di as text _col(10) "Freed item" _col(31) "Chi-Square" _col(48) "DF" _col(57) "P-Value"
+ di as text _col(10) "{hline 65}"
+ }
+
+
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ if `nbdif_`j'' >= 1 {
+ local model ""
+ local listconst ""
+ local listconst_g ""
+ if dif_rc[`j',3]==. { /*si pas de RC déjà détecté sur l'item j -> test item j*/
+ /*on libĂšre la RC de l'item j: pas de contraintes*/
+ forvalues k=1/`nbitems'{
+ if "`group'" == "" {
+ if `k'!=`j'{
+ if dif_rc[`k',3]==. | dif_rc[`k',3]==0 {/*pas de RC sur item k: contraintes 401-600*/
+ forvalues p=1/`nbdif_`k''{
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`k'-1)+`p'' "
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RC commune unif.
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst_g "`listconst_g' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ /* Contraintes de DIF */
+ if dif_rc[`k',1]==.|dif_rc[`k',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ if `k'!=`j'{ /*contraintes pour les autres items */
+ if dif_rc[`k',3]==. | dif_rc[`k',3]==0 {/*pas de RC sur item k: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item k
+ if dif_rc[`k',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`k''{ /***************************** j=1 ou 2 ?****/
+ local listconst "`listconst' `=800+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`k'-1)+`p''
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RC commune unif.
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`k',5]==. | dif_rc[`k',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`k',7]==. | dif_rc[`k',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',8]!=. & dif_rc[`k',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ if "`group'" == "" { // Sans l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /*****************/
+ /*tests RC item j*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']_cons =[1.``=`j'+`nbitems''']_cons
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']_cons =[`p'.``=`j'+`nbitems''']_cons, acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+
+ /* RCU ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[2.``=`j'+`nbitems''']_cons -[2.``j'']_cons
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[`p'.``=`j'+`nbitems''']_cons -[`p'.``j'']_cons , acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2), r(df),r(p))
+ }
+ }
+ else { // Avec l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /*****************/
+ /*tests RC item i*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp', acc
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC COMMUNE ? */
+ qui test [1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ }
+ matrix test_rcCOMM_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC groupe 0 ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[2.``=`j'+`nbitems''']0bn.`gp'-[2.``j'']0bn.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ }
+
+ /* RC groupe 1 ? */
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',7]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 1 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[2.``=`j'+`nbitems''']1.`gp'-[2.``j'']1.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+ }
+ }
+ /******* Matrice test complĂšte *********/
+ if "`detail'" != "" {
+ di as text _col(10) abbrev("``j''",22) as result _col(31) %6.3f test_rc_`boucle'[`j',1] _col(48) test_rc_`boucle'[`j',2] _col(57) %6.4f test_rc_`boucle'[`j',3]
+ }
+ }
+ }
+ }
+ //matrix list test_rc_`boucle'
+ forvalues j=1/`nbitems'{
+ if test_rc_`boucle'[`j',3]<`pajust'{/*si RC sur item i*/
+ if test_rc_`boucle'[`j',3]<`minpval'{
+ local minpval=test_rc_`boucle'[`j',3]
+ local itemrc=`j'
+ }
+ }
+ }
+ if `itemrc' != 0 { // itemrc = numéro de l'item avec le test le + sig.
+ if "`group'" == "" { // Recalibration si pas d'option groupe
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ if "`detail'" != "" {
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "Recalibration on ``itemrc''"
+ di
+ di as text _col(10) "{hline 65}"
+ di as text _col(10) "Test" _col(31) "Chi-Square" _col(48) "DF" _col(57) "P-Value"
+ di as text _col(10) "{hline 65}"
+ di as text _col(10) "Uniform RC? " as result _col(31) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(48) `=test_rcU_`boucle'[`itemrc',2]' _col(57) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ di as text _col(10) "{hline 65}"
+ }
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { //RC Uniforme sur itemRC
+ matrix dif_rc[`itemrc',6]=`boucle'
+ di
+ di as result "``itemrc'' : Uniform RC"
+ di
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ di
+ di as result "``itemrc'' : Non-uniform RC"
+ di
+ }
+ }
+ else {
+ di
+ di as result "``itemrc'' : Recalibration "
+ di
+ }
+ }
+ else { // Option groupe
+ if "`detail'" != "" {
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "Recalibration on ``itemrc''"
+ di
+ di as text _col(10) "{hline 65}"
+ di as text _col(10) "Test" _col(31) "Chi-Square" _col(48) "DF" _col(57) "P-Value"
+ di as text _col(10) "{hline 65}"
+ di _col(10) as text "Common RC? " as result _col(31) %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' _col(48) `=test_rcCOMM_`boucle'[`itemrc',2]' _col(57) %6.4f `=test_rcCOMM_`boucle'[`itemrc',3]'
+ }
+ if test_rcCOMM_`boucle'[`itemrc',3] < 0.05 { //RC différentielle
+ if "`detail'" != "" {
+ di _col(10) as text "RC group 0? " as result _col(31) %4.2f `=test_rc_`boucle'[`itemrc',4]' _col(48) `=test_rc_`boucle'[`itemrc',5]' _col(57) %6.4f `=test_rc_`boucle'[`itemrc',6]' "{it: - with adjusted alpha = `pajust2' }"
+ }
+ if test_rc_`boucle'[`itemrc',6] < `pajust2' { //RC gp 0
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ di _col(10) as text "Uniform RC group 0? " as result _col(31) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(48) `=test_rcU_`boucle'[`itemrc',2]' _col(57) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { // RCU gp 0
+ matrix dif_rc[`itemrc',6]=`boucle'
+ local phrase_diff = "``itemrc'' : Uniform differential RC in group 0."
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ local phrase_diff = "``itemrc'' : Non-uniform differential RC in group 0."
+ }
+ }
+ else {
+ local phrase_diff = "``itemrc'' : Differential RC in group 0."
+ }
+ }
+ if "`detail'" != "" {
+ di _col(10) as text "RC group 1?" as result _col(31) %4.2f `=test_rc_`boucle'[`itemrc',7]' _col(48) `=test_rc_`boucle'[`itemrc',8]' _col(57) %6.4f `=test_rc_`boucle'[`itemrc',9]' "{it: - with adjusted alpha = `pajust2' }"
+ }
+ if test_rc_`boucle'[`itemrc',9] < `pajust2' { //RC gp 1
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ if "`detail'" != "" {
+ di _col(10) as text "Uniform RC group 1? " as result _col(31) %4.2f `=test_rcU_`boucle'[`itemrc',4]' _col(48) `=test_rcU_`boucle'[`itemrc',5]' _col(57) %6.4f `=test_rcU_`boucle'[`itemrc',6]'
+ }
+ if test_rcU_`boucle'[`itemrc',6] >= 0.05 { // RCU gp 1
+ matrix dif_rc[`itemrc',8]=`boucle'
+ if dif_rc[`itemrc',5] != `boucle' { //RC slmt sur g1
+ local phrase_diff = "``itemrc'' : Differential RC, uniform RC in group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = "``itemrc'' : Differential RC, non-uniform RC in group 0 and uniform RC in group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = "``itemrc'' : Differential RC, uniform RC in group 0 and uniform RC in group 1."
+ }
+ }
+ }
+ else { //RCNU gp 1
+ matrix dif_rc[`itemrc',8]=0
+ if "`detail'" != "" {
+ di
+ }
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = "``itemrc'' : Differential RC, non-uniform RC in group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = "``itemrc'' : Differential RC, non-uniform RC in group 0 and non-uniform RC in group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = "``itemrc'' : Differential RC, uniform RC in group 0 and non-uniform RC in group 1."
+ }
+ }
+ }
+ }
+ else {
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = "``itemrc'' : Differential RC in group 1."
+ }
+ else {
+ local phrase_diff = "``itemrc'' : Differential RC in group 0 and differential RC in group 1."
+ }
+ }
+ }
+ if "`detail'" != "" {
+ di as text _col(10) "{hline 65}"
+ }
+ di
+ di as result "`phrase_diff'"
+ di
+ }
+ else { // RC commune -> MAJ modĂšle 3
+ /*******************************************************************************************************************/
+ if `nbmoda_`itemrc'' == 2 {
+ if "`detail'" != "" {
+ di
+ di as result "{ul:``itemrc''}: recalibration"
+ di _col(20) in ye "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ }
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ local ++nbsig
+ }
+ else {
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ //matrix list dif_rc
+ local model ""
+ local listconst ""
+ forvalues j=1/`nbitems'{
+ /* Contraintes de DIF */
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ if `j' != `itemrc'{ /*contraintes pour les autres items */
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 {/*pas de RC sur item p: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item p
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else if dif_rc[`j',4] != 0 & dif_rc[`j',4]!=0. { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ else { // Contrainte de RC commune pour l'itemrc
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`itemrc'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`itemrc'-1)+`p''
+ }
+ }
+ }
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /************************/
+ /*tests RC item `itemrc'*/
+ /************************/
+ matrix commU_`boucle'=J(`nbitems',3,.) //Matrice des tests de RCU slmt si RC commune
+ matrix colnames commU_`boucle'= chi_RCU df_RCU p_RCU
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`itemrc'' > 2 {
+ qui test 2*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[2.``=`itemrc'+`nbitems''']0bn.`gp'-[2.``itemrc'']0bn.`gp'
+ forvalues j=3/`nbdif_`itemrc''{
+ qui test `j'*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[`j'.``=`itemrc'+`nbitems''']0bn.`gp'-[`j'.``itemrc'']0bn.`gp', acc
+ }
+ matrix commU_`boucle'[`itemrc',1]=(r(chi2),r(df),r(p))
+ if "`detail'" != "" {
+ di _col(10) as text "Uniform RC?" as result _col(31) %4.2f `=commU_`boucle'[`itemrc',1]' _col(48) `=commU_`boucle'[`itemrc',2]' _col(57) %6.4f `=commU_`boucle'[`itemrc',3]'
+ di as text _col(10) "{hline 65}"
+ }
+ if commU_`boucle'[`itemrc',3] >= 0.05 { // RCU
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=`boucle'
+ matrix dif_rc[`itemrc',8]=`boucle'
+ di
+ //di as result "{ul:``itemrc''}: recalibration"
+ //di _col(20) "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ di as result "``itemrc'' : Uniform common RC"
+ di
+ }
+ else {
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=0
+ matrix dif_rc[`itemrc',8]=0
+ di
+ di as result "``itemrc'' : Non-uniform common RC"
+ di
+ }
+ }
+ }
+ } // fin de RC commune
+ }
+ }
+ else {
+ local stop = 1
+ }
+ /*******************************************************************************************************************/
+ // Fin de RC sur item i
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "No significant tests, no recalibration detected"
+ di
+ }
+ else {
+ if "`detail'" != "" {
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "No other significant tests"
+ di
+ }
+ }
+ }
+ local ++boucle
+ }
+}
+
+
+
+ *********************************
+ *** BILAN ***
+ *********************************
+
+ if "`group'" != "" & "`nodif'" == "" {
+ di
+ di %~84s as result "SUMMARY"
+ di as result _col(2) "{hline 80}"
+ di as result _col(18) "Difference in"
+ di as result _col(2) "Item" _col(18) "groups at T1" _col(36) "Recalibration" _col(54) "RC " abbrev("`gp'",10) " 0" _col(72) "RC " abbrev("`gp'",10) " 1"
+ di as result _col(2) "{hline 80}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ local difft1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ if (dif_rc[`j',1] != . ) {
+ if (dif_rc[`j',2]!=0) {
+ local difft1 "Uniform"
+ }
+ else {
+ local difft1 "Non-uniform"
+ }
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ if dif_rc[`j',1] != . {
+ local difft1 " X "
+ }
+ }
+ di as result _col(2) abbrev("``j''",15) as text _col(18) "`difft1'" _col(36) "`RC'" _col(54) "`RCg0'" _col(72) "`RCg1'"
+ }
+ di as result _col(2) "{hline 80}"
+ di
+}
+else if "`group'" != "" & "`nodif'" != "" {
+ di
+ di %~90s as result "SUMMARY"
+ di as result _col(10) "{hline 70}"
+ di as result _col(10) "Item" _col(26) "Recalibration" _col(46) "RC `gp' 0" _col(62) "RC `gp' 1"
+ di _col(10) "{hline 70}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ }
+ di as result _col(10) "``j''" as text _col(26) "`RC'" _col(44) "`RCg0'" _col(62) "`RCg1'"
+ }
+ di as result _col(10) "{hline 70}"
+}
+else if "`group'" == "" {
+ di
+ di %~60s as result "SUMMARY"
+ di as result _col(10) "{hline 40}"
+ di _col(10) "Item" _col(36) "Recalibration"
+ di _col(10) "{hline 40}"
+ forvalues j=1/`nbitems' {
+ local RC
+ if dif_rc[`j',3] != . {
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RC "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RC "Non-uniform"
+ }
+ }
+ else {
+ local RC " X "
+ }
+ }
+ di as result _col(10) "``j''" as text _col(38) "`RC'"
+ }
+ di as result _col(10) "{hline 40}"
+ di
+}
+
+
+ *********************************
+ ** MODEL 4 **
+ *********************************
+if "`detail'" != "" {
+ di
+ di as input "PROCESSING STEP 4"
+ di
+}
+ //matrix list dif_rc, title ("Constraints")
+
+local model ""
+local listconst ""
+local listconst_g ""
+forvalues j=1/`nbitems'{
+ if "`group'" != "" {
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200 */
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 { /*pas de RC : contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ if "`group'" == "" {
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ else {
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ else { //RC détectée sur l'item j
+ if "`group'" == "" {
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst_g "`listconst_g' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else {
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+local model ""
+
+forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means( THETA1@0 THETA2@m2) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+ /* Stockage des estimations du modĂšle */
+matrix val_m4 = r(table)
+matrix esti_4 = e(b)
+
+if "`group'" != "" {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)#0bn.`gp'"],val_m4[1,"/var(THETA2)#0bn.`gp'"]\val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"]\val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)"]\val_m4[2,"/cov(THETA1,THETA2)"]\val_m4[4,"/cov(THETA1,THETA2)"])
+}
+
+/* Matrice des tests effet grp, tps et inter */
+matrix effet = J(5,3,.)
+matrix colnames effet= Groupe Temps Interaction
+matrix rownames effet = Esti Std_Err Pvalue Chi DF
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,1] =r(estimate)
+ matrix effet[2,1]=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,1]=r(p)
+ matrix effet[4,1]=r(chi2)
+ matrix effet[5,1]=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,2]=r(estimate)
+ matrix effet[2,2]=r(se)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,2]=r(p)
+ matrix effet[4,2]=r(chi2)
+ matrix effet[5,2]=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* -[/]:mean(THETA1)*/
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local ubteffm4 = r(ub)
+ local lbteffm4 = r(lb)
+ qui test [/]:mean(THETA2) /* -[/]:mean(THETA1) */ = 0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,3]=r(estimate)
+ matrix effet[2,3]=r(se)
+ local ubinterm4=r(ub)
+ local lbinterm4=r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,3]=r(p)
+ matrix effet[4,3]=r(chi2)
+ matrix effet[5,3]=r(df)
+}
+
+if "`group'" != "" {
+ local effet_tps = 0
+ local effet_grp = 0
+
+ if effet[3,3] >= 0.05 { // Si option group, on s'interesse Ă l'interaction temps x group, et MAJ modĂšle >>> modĂšle final = modĂšle 4 + contrainte 1999 (Interaction = 0)
+ /* Affichage des estimations sur le trait latent du modĂšle 4 */
+ if "`detail'" != "" {
+ di
+ di %~85s as text "Latent trait distribution"
+ di _col(10) "{hline 65}"
+ di _col(28) as text "Estimate" _col(46) "Standard error" _col(62) "P-value"
+ di _col(10) "{hline 65}"
+ di _col(10) as text "Variance Time 1" as result _col(28) %6.2f `=var_m4[1,1]' _col(44) %6.2f `=var_m4[2,1]'
+ di _col(10) as text "Variance Time 2" as result _col(28) %6.2f `=var_m4[1,2]' _col(44) %6.2f `=var_m4[2,2]'
+ di _col(10) as text "Covariance" as result _col(28) %6.2f `=covar_m4[1,1]' _col(44) %6.2f `=covar_m4[2,1]'
+ if "`group'" != "" {
+ di _col(10) as text "Group effect" as result _col(28) %6.2f effet[1,1] _col(44) %6.2f effet[2,1] _col(62) %6.4f effet[3,1]
+ }
+ di _col(10) as text "Time effect" as result _col(28) %6.2f effet[1,2] _col(44) %6.2f effet[2,2] _col(62) %6.4f effet[3,2]
+
+ if "`group'" != "" {
+ di _col(10) as text "TimexGroup inter" as result _col(28) %6.2f effet[1,3] _col(44) %6.2f effet[2,3] _col(62) %6.4f effet[3,3]
+ }
+ di as text _col(10) "{hline 65}"
+ di
+ di as result "Time x group interaction : test not significant
+ di "Reestimation of model 4 with time x group interaction constrained at 0 "
+ di
+ }
+ local yn_inter = 0
+ local listconst "`listconst' 1999"
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_4, skip) latent(THETA1 THETA2) nocapslatent
+
+ matrix val_m4 = r(table)
+ }
+ else {
+ local yn_inter = 1
+ }
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm4=r(estimate)
+ local segeffm4=r(se)
+ local ubgeffm4=r(ub)
+ local lbgeffm4=r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm4p=r(p)
+ local gpm4chi=r(chi2)
+ local gpm4df=r(df)
+
+ /*time effect*/
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local lbteffm4=r(lb)
+ local ubteffm4=r(ub)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+ /* Calcul des difficultés (delta_j) */
+if "`group'" != "" {
+ matrix mod4 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod4 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4= r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se= r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4=r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se=r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4= r(estimate)
+ local delta`t'_`j'_`p'g0m4_se= r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4=r(estimate)
+ local delta`t'_`j'_`p'g0m4_se=r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod4[1,`=4*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)#0bn.`gp'"], val_m4[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)#0bn.`gp'"],val_m4[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)#0bn.`gp'"],val_m4[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm4p'
+
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4p'
+
+ if `yn_inter' == 1 { //Slmt si model avec interaction
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[1,3]
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[2,3]
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[4,3]
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[5,3]
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[3,3]
+ }
+
+}
+else {
+ matrix mod4[1,`=2*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)"],val_m4[6,"/var(THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)"],val_m4[5,"/var(THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm4'
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm4'
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm4'
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm4'
+ matrix mod4[5,`=2*`nbmoda_sum'+2+1+1'] = `tm4chi'
+ matrix mod4[6,`=2*`nbmoda_sum'+2+1+1'] = `tm4df'
+ matrix mod4[7,`=2*`nbmoda_sum'+2+1+1'] = `tm4p'
+}
+
+
+ /* Affichage des estimations des difficultés */
+di _col(5) as text "{ul:MODEL 4} = Final model"
+di
+if "`group'" != "" {
+ di %~105s as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(38) "Time 1" _col(76) "Time 2"
+ di as text _col(25) abbrev("`gp'",15) "=0" _col(43) abbrev("`gp'",15) "=1" _col(64) abbrev("`gp'",15) "=0" _col(82) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+}
+else {
+ di %~70s as text as text "Item difficulties: estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(25) "Time 1" _col(43) "Time 2"
+ di _col(10) "{hline 50}"
+}
+
+forvalues j=1/`nbitems' {
+ di as text _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(43) %6.2f `delta1_`j'_`p'g1m4' " (" %4.2f `delta1_`j'_`p'g1m4_se' ")" ///
+ _col(63) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")" _col(81) %6.2f `delta2_`j'_`p'g1m4' " (" %4.2f `delta2_`j'_`p'g1m4_se' ")"
+ }
+ else {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(43) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")"
+ }
+ }
+}
+
+if "`group'" != "" {
+ di as text _col(10) "{hline 85}"
+}
+else {
+ di as text _col(10) "{hline 50}"
+}
+
+ /* Affichage des estimations sur le trait latent du modĂšle final */
+di
+di %~85s as text "Latent trait distribution"
+di _col(10) "{hline 65}"
+di _col(28) as text "Estimate" _col(44) "Standard error" _col(62) "P-value"
+di _col(10) "{hline 65}"
+
+if "`group'" == "" {
+ local fact_k = 2
+}
+else {
+ local fact_k = 4
+}
+
+di _col(10) as text "Variance Time 1" as result _col(28) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+1']' _col(44) %6.2f =mod4[2,`=`fact_k'*`nbmoda_sum'+1']
+di _col(10) as text "Variance Time 2" as result _col(28) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+2']' _col(44) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+2']'
+di _col(10) as text "Covariance" as result _col(28) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+3']' _col(44) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+3']'
+
+if "`group'" != "" {
+
+ di _col(10) as text "Group effect" as result _col(28) %6.2f `geffm4' _col(44) %6.2f `segeffm4' _col(62) %6.4f `gpm4p'
+}
+di _col(10) as text "Time effect" as result _col(28) %6.2f `teffm4' _col(44) %6.2f `seteffm4' _col(62) %6.4f `tm4p'
+
+if "`group'" != "" {
+ if effet[3,3] < 0.05 {
+ di _col(10) as text "TimexGroup inter" as result _col(28) %6.2f effet[1,3] _col(44) %6.2f effet[2,3] _col(62) %6.4f effet[3,3]
+ }
+ else {
+ di _col(10) as text "TimexGroup inter" as result _col(28) "0 (constrained)"
+ }
+}
+
+di as text _col(10) "{hline 65}"
+
+/***************************************/
+/* Calcul des valeurs de DIF et de RC */
+/*************************************/
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ matrix valeur_difrc_`j' = J(`nbdif_`j'',8,.)
+ matrix colnames valeur_difrc_`j' = DIFT1 DIFT1_SE RC_GP0 RC_GP0_SE RC_GP1 RC_GP1_SE
+ }
+}
+
+forvalues j=1/`nbitems'{
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" {
+ *DIF
+ if "`nodif'"=="" {
+ if (dif_rc[`j',1] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ if `p' == 1 {
+ qui lincom -[1.``j'']:1.`gp'+[1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``j'']:1.`gp' - [`p'.``j'']:1.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ *RC GROUP 0
+ if (dif_rc[`j',3] != . & dif_rc[`j',5] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:0.`gp' + [1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:0.`gp' - [`p'.``=`j'+`nbitems''']:0.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ *RC GROUP 1
+ if (dif_rc[`j',3] != . & dif_rc[`j',7] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:1.`gp' + [1.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:1.`gp' - [`p'.``=`j'+`nbitems''']:1.`gp' -[`=`p'-1'.``j'']:1.`gp' + [`p'.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ else {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']_cons + [1.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']_cons - [`p'.``=`j'+`nbitems''']_cons -[`=`p'-1'.``j'']_cons + [`p'.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+}
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ forvalues p = 1/`nbdif_`j'' {
+ forvalues k = 1/8 {
+ if valeur_difrc_`j'[`p',`k'] == . {
+ matrix valeur_difrc_`j'[`p',`k'] = 0
+ }
+ }
+ }
+ }
+}
+
+ /* Affichage des estimations des valeurs de DIF et de RC */
+if "`group'" != "" {
+ di
+ di %~85s as text "Estimates of differences between groups and recalibration"
+}
+else {
+ di
+ di %~50s as text "Estimates of recalibration"
+}
+if "`group'" != "" & "`nodif'"==""{
+ di _col(10) "{hline 65}"
+ di _col(27) "Difference of" _col(52) "RECALIBRATION"
+ di _col(27) "groups at T1" _col(47) abbrev("`gp'",15) "=0" _col(62) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 65}"
+}
+else if "`group'" != "" & "`nodif'"!="" {
+ di _col(10) "{hline 50}"
+ di _col(32) "RECALIBRATION"
+ di in ye _col(27) "`gp'=`=rep[1,1]'" _col(47) "`gp'=`=rep[2,1]'"
+ di _col(10) "{hline 50}"
+}
+else {
+ di _col(10) "{hline 30}"
+ di _col(25) "RECALIBRATION"
+ di _col(10) "{hline 30}"
+}
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" & "`nodif'" == "" {
+ di as text _col(10) "``j''"
+ }
+ else {
+ di as text _col(10) "``j''"
+ }
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" & "`nodif'"=="" {
+ di as text _col(10) "`p'" as result _col(27) %6.2f `=valeur_difrc_`j'[`p',1]' " (" %4.2f `=valeur_difrc_`j'[`p',2]' ")" ///
+ _col(47) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(62) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else if "`group'" != "" & "`nodif'"!="" {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(45) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else {
+ di as text _col(10) "`p'" as result _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")"
+ }
+ }
+ }
+}
+
+if "`group'" != "" & "`nodif'"=="" {
+ di as text _col(10) "{hline 65}"
+}
+else if "`group'" != "" & "`nodif'"!=""{
+ di as text _col(10) "{hline 50}"
+}
+else {
+ di as text _col(10) "{hline 30}"
+}
+di
+
+
+*******************************************************************************
+* New outputs
+
+if "`group'" == "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else if "`nodif'" != "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else {
+ matrix testlrm = J(2,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = mA_vs_mB m1_vs_m2
+ matrix testlrm[1,1] = (`diftestchi',`diftestdf',`diftestp')
+ matrix testlrm[2,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+
+return matrix model_4 = mod4
+return matrix model_2 = mod2
+
+capture qui use `saverspcm', clear
+
+end
+
diff --git a/Modules/ado/personal/r/rosali.sthlp b/Modules/ado/personal/r/rosali.sthlp
new file mode 100644
index 0000000..cb3f7e8
--- /dev/null
+++ b/Modules/ado/personal/r/rosali.sthlp
@@ -0,0 +1,64 @@
+{smcl}
+{* june2020}{...}
+{hline}
+help for {hi:rosali}{right:Myriam Blanchin - Priscilla Brisson}
+{hline}
+
+{title:Detection of response shift at item-level between 2 times of measurement}
+
+{p 4}{cmd:rosali} {it:varlist} [{it:if}] [{it:in}] [, {cmdab:group}({it:string}) {cmdab:nodif} {cmdab:detail}]
+
+{p 4 4 4 140}{it:varlist} contains the list of items: the first part of the list is composed of the items at time 1 and the second part of the items at time 2, in the same order.
+
+{title:Description}
+
+{p 4 12 2 140}{cmd:rosali} performs the {bf:R}esp{bf:O}nse {bf:S}hift {bf:AL}gorithm at {bf:I}tem-level (ROSALI) based on partial credit models
+between two times of measurement, time 1 and time 2. Only uniform or non-uniform {bf:r}e{bf:c}alibration can be detected. Response shift detection is performed at item-level assuming all individuals of the sample are affected the same way by default. A dichotomous group variable can be specified with the {cmd:group} option to assess its impact on latent variable, item functioning and response shift. {bf:D}ifferential {bf:I}tem {bf:F}unctionning (DIF) refers to a constant difference of item difficulties between groups over time.
+
+{title:Options}
+
+{p 4 12 2 140}{cmd:group}({it:string}) specifies a binary group variable that can affect item functioning, the estimation of the latent variable means (group effect)
+and response shift. Response shift can be common to both groups or differential (occuring in only one group or affecting both groups differentially). By default, response shift detection is performed assuming all individuals are affected in the same way.
+
+{phang}{cmd:nodif} assumes no DIF occurs in the sample and skips DIF detection. Only response shift detection is performed. {it:Use only with group option.}
+
+{phang}{cmd:detail} displays results of each step of ROSALI.
+
+{title:Remarks}
+
+{p 4} {it:Data} must be in wide format, one row per individual.
+
+{p 4} At least two items per time of measurement are required.
+
+{p 4 12 2 140} {cmd:automatic recoding for response categories}
+{break} Response categories are automatically recoded to start from 0.
+{break} If a response category is not used at one time of measurement, this category is automatically recoded at both times of measurement (for each group if group option).
+{break} Rules for automatic recoding:
+{break} - 0 response category: merged with response category 1.
+{break} - most difficult response category: merged with the previous one.
+{break} - other response categories: randomly merged with the next or previous adjacent one.
+
+{title:Outputs}
+
+{p 4 12 2 140}{bf:Matrix:}
+
+{phang}{cmd:r(test_model)}: Result of LRT between models A/B and models 1/2: chi-square statistic, DF and p-value.
+
+{phang}{cmd:r(model_#)}: Item difficulties and latent trait distribution parameters of models #2 or #4 : Estimates, standard errors, 95% confidence interval, chi-square statistics, DF and p-values.
+
+{title:Examples}
+
+{phang}{cmd: . rosali m0gh1 m0gh2 m0gh3 m0gh4 m0gh5 m6gh1 m6gh2 m6gh3 m6gh4 m6gh5, detail }
+
+{phang}{cmd: . rosali it1_t1-it9_t2 , group(cancer_site) }
+
+{title:Reference}
+
+{p} Blanchin, M., Guilleux, A., Hardouin, J.-B., & SĂ©bille, V. (2020). Comparison of structural equation modelling, item response theory and Rasch measurement theory-based methods for response shift detection at item level: A simulation study: Statistical Methods in Medical Research, 19(4), 1015â1029. https://doi.org/10.1177/0962280219884574
+
+{title:Authors}
+
+{p}Myriam Blanchin, Research engineer, PhD, SPHERE - UMR INSERM U1246, "methodS in Patient-centered outcomes and HEalth ResEarch", University of Nantes, France {browse "mailto:myriam.blanchin@univ-nantes.fr":myriam.blanchin@univ-nantes.fr}
+{break}Priscilla Brisson, SPHERE - UMR INSERM U1246, "methodS in Patient-centered outcomes and HEalth ResEarch", University of Nantes, France
+
+
diff --git a/Modules/ado/personal/r/rosali22.ado b/Modules/ado/personal/r/rosali22.ado
new file mode 100644
index 0000000..c072c35
--- /dev/null
+++ b/Modules/ado/personal/r/rosali22.ado
@@ -0,0 +1,3266 @@
+*! version 2.2 february2019
+*! Myriam Blanchin - Priscilla Brisson
+*! construction
+************************************************************************************************************
+* ROSALI: RespOnse-Shift ALgorithm at Item-level
+* Response-shift detection based on Rasch models family
+*
+* Version 1 : December 21, 2016 (Myriam Blanchin) /*rspcm122016*/
+* Version 1.1 : October 13, 2017 (Myriam Blanchin) /*option: MODA, automatic recoding of unused response categories*/
+* Version 2 : April, 2018 (Myriam Blanchin - Priscilla Brisson) /*option: GROUP, dichotomous group variable*/
+* Version 2.1 : October, 2018 (Myriam Blanchin - Priscilla Brisson) /* Version 1.1 + Version 2 */
+* Version 2.2 : February, 2019 (Priscilla Brisson) /* option nodif, keep name of variables, optimization */
+*
+* Myriam Blanchin, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* myriam.blanchin@univ-nantes.fr
+*
+* Priscilla Brisson, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* priscilla.brisson@univ-nantes.fr
+*
+* 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 rosali22, rclass
+
+timer clear 1
+timer on 1
+
+syntax varlist(min=2 numeric) [if] [in] [,ID(string) MODA(string) GROUP(string) NODIF]
+version 15
+tempfile saverspcm
+qui save `saverspcm',replace
+local save1=_rc
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+/**************************************************************************/
+set more off
+set matsize 5000
+
+local id "`id'"
+local gp "`group'"
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+
+ /* VĂ©rif nb d'items pair */
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items at time 1 and the second half the items at time 2"
+ error 198
+ exit
+}
+
+local nbitems=`nbitems'/2
+
+
+* VĂ©rification du format wide
+if "`id'" == "" {
+ di in red "You must enter an identifiant ({hi:id} option). Please correct this option."
+ error 198
+ exit
+}
+qui tab `id'
+local nbpat = r(r)
+local nbline = _N
+if `nbpat' != `nbline' {
+ di in red "Data must be in wide format : one line for one patient. Please correct this."
+ error 198
+ exit
+}
+
+if "`group'"=="" & "`nodif'"!="" {
+ di in red "nodif can only be used with the group option ({hi:nodif} option). Please correct this option."
+ error 198
+ exit
+}
+
+if "`moda'"!="" {
+ local listmoda:word count `moda'
+ if `listmoda'!=`nbitems' {
+ di in red "You have indicated a number of categories ({hi:moda} option) different of the number of items. Please correct this option."
+ if `listmoda' < `nbitems' {
+ error 122
+ exit
+ }
+ if `listmoda' > `nbitems' {
+ error 123
+ exit
+ }
+ }
+}
+
+
+local nbc: word count `group'
+if `nbc' >= 2 {
+ di in red "Only one variable can be used for group option ({hi:group} option). Please correct this option."
+ error 198
+ exit
+}
+
+ /* VĂ©rif qu'il y a 2 groupes si l'option groupe est choisie */
+if "`group'"!="" {
+ qui tab `group'
+ local nbgrp = r(r)
+ if `nbgrp' != 2 {
+ di in red "The option group must be used with only 2 groups ({hi:group} option). Please correct this option."
+ error 420
+ exit
+ }
+}
+/* recoder la variable de groupe en 0, 1*/
+
+if "`group'"!="" {
+ qui tab `gp', matrow(rep)
+ qui matrix list rep
+ if rep[1,1]+rep[2,1] != 1 & rep[1,1]*rep[2,1] != 0 {
+ forvalues i=1/`=rowsof(rep)'{
+ qui replace `gp'=`i'-1 if `gp'==rep[`i',1]
+ di "WARNING : `gp' `=rep[`i',1]' is now `gp' `=`i'-1' "
+ }
+ }
+ forvalues g = 0/1 {
+ qui tab `gp' if `gp' == `g'
+ local nbp_gp`g' = r(N)
+ }
+}
+
+
+
+/*item rename*/
+/*
+Items au temps 1 : 1 Ă nbitems ``j''
+Items au temps 2 : nbitems Ă 2*nbitems ``=`j'+`nbitems'''
+
+Si t varie, puis num item : ``=(`t'-1)*`nbitems'+`j'''
+*/
+
+di
+di "WARNING : Automatic recoding, so that the first response category is 0. see {help rosali22:help rosali22}."
+di
+
+ /*verif modalités répondues*/
+if "`gp'" == "" { // Si pas d'option groupe
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'' // Récupération des infos moda du temps 1
+ local nbm`j'_t1 = r(r)
+ qui su ``j''
+ local minm`j'_t1 = r(min)
+ local maxm`j'_t1 = r(max)
+
+ qui tab ``=`j'+`nbitems''' // Récupération des infos moda du temps 2
+ local nbm`j'_t2 = r(r)
+ qui su ``=`j'+`nbitems'''
+ local minm`j'_t2 = r(min)
+ local maxm`j'_t2 = r(max)
+
+ local minm_`j' = min(`minm`j'_t1',`minm`j'_t2') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1',`maxm`j'_t2')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j'''
+
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`nbm_`j'' {
+ qui count if ``j'' == `m'
+ local nb_rn1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m'
+ local nb_rn2 = r(N)
+ local nb_rn = min(`nb_rn1',`nb_rn2')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' <= `minm`j'_t1' | `m' <= `minm`j'_t2' { // La moda 0 ou les moda min ne sont pas utilisées
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'+`k'' merged "
+ local stop = 0
+ }
+ }
+ }
+ else if `m' >= `maxm`j'_t1' | `m' >= `maxm`j'_t2' | `m' == `maxm_`j'' { // La (ou les) moda max ne sont pas utilisée(s)
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local hour=real(substr("$S_TIME",1,2))
+ local min=real(substr("$S_TIME",4,2))
+ local sec=real(substr("$S_TIME",7,2))
+ local jour=real(substr("$S_DATE",1,2))
+ global seed=784556+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+ set seed $seed
+
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems''' =`=`m'-`k'' if ``=`j'+`nbitems''' ==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item answers ``j'': `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+else { // Cas oĂč l'option groupe est utilisĂ©e
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'' if `gp' == 0 // Récupération des infos moda du temps 1pour chaque groupe
+ local nbm`j'_t1_g0 = r(r)
+ qui su ``j'' if `gp' == 0
+ local minm`j'_t1_g0 = r(min)
+ local maxm`j'_t1_g0 = r(max)
+
+ qui tab ``j'' if `gp' == 1
+ local nbm`j'_t1_g1 = r(r)
+ qui su ``j'' if `gp' == 1
+ local minm`j'_t1_g1 = r(min)
+ local maxm`j'_t1_g1 = r(max)
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 0 // Récupération des infos moda du temps 2 pour chaque groupe
+ local nbm`j'_t2_g0 = r(r)
+ qui su ``=`j'+`nbitems''' if `gp' == 0
+ local minm`j'_t2_g0 = r(min)
+ local maxm`j'_t2_g0 = r(max)
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 1
+ local nbm`j'_t2_g1 = r(r)
+ qui su ``=`j'+`nbitems''' if `gp' == 1
+ local minm`j'_t2_g1 = r(min)
+ local maxm`j'_t2_g1 = r(max)
+
+ local minm_`j' = min(`minm`j'_t1_g0',`minm`j'_t2_g0',`minm`j'_t1_g1',`minm`j'_t2_g1') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1_g0',`maxm`j'_t2_g0',`maxm`j'_t1_g1',`maxm`j'_t2_g1')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j''+1'
+
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`=`nbm_`j''-1' {
+ qui count if ``j'' == `m' & `gp' == 0
+ local nb_rn1_g0 = r(N)
+ qui count if ``j'' == `m' & `gp' == 1
+ local nb_rn1_g1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 0
+ local nb_rn2_g0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 1
+ local nb_rn2_g1 = r(N)
+ local nb_rn = min(`nb_rn1_g0',`nb_rn2_g0',`nb_rn1_g1',`nb_rn2_g1')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' < `minm`j'_t1_g0' | `m' < `minm`j'_t2_g0' | `m' < `minm`j'_t1_g1' | `m' < `minm`j'_t2_g1' { // La moda 0 n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else if `m' == `=`nbm_`j''-1' | `m' >= `maxm`j'_t2_g0' | `m' >= `maxm`j'_t1_g1' | `m' >= `maxm`j'_t2_g1' { // La moda max n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`m'' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0 ) & `stop' != 0 {
+ qui replace ``j''= `=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else { // Moda central non utilisée
+ local hour=real(substr("$S_TIME",1,2))
+ local min=real(substr("$S_TIME",4,2))
+ local sec=real(substr("$S_TIME",7,2))
+ local jour=real(substr("$S_DATE",1,2))
+ global seed=784556+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+ set seed $seed
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'-`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0{
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: item ``j'': answers `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+forvalues j =1/`nbitems' {
+ qui tab ``j'', matrow(rec) // Récupération des infos moda du temps 1
+ local nbm`j'_t1 = r(r)
+
+ qui tab ``=`j'+`nbitems''' // Récupération des infos moda du temps 2
+ local nbm`j'_t2 = r(r)
+
+ local nbm_`j' = max(`nbm`j'_t1', `nbm`j'_t2')
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`nbm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=rec[`=`r'+1',1]'
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=rec[`=`r'+1',1]'
+ }
+}
+
+
+forvalues j = 1/`nbitems' {
+ if `recoda_`j'' == 1 {
+ if "`gp'" != "" {
+ di
+ di "``j'' & ``=`j'+`nbitems''' after automatic recoding :"
+ di
+ tab ``j'' `gp'
+ tab ``=`j'+`nbitems''' `gp'
+ }
+ else {
+ di
+ di "``j'' & ``=`j'+`nbitems''' after automatic recoding :"
+ di
+ tab ``j''
+ tab ``=`j'+`nbitems'''
+
+ }
+ di
+ di
+ }
+}
+
+
+/* Calcul de nbmoda & nbdif */
+forvalues j = 1/`nbitems' {
+ qui tab ``j''
+ local nbmoda_`j' = r(r)
+ local nbdif_`j' = r(r) - 1
+}
+
+local maxdif = 0
+local nbmoda_sum = 0
+forvalues j = 1/`nbitems' {
+ if `maxdif' < `nbdif_`j'' {
+ local maxdif = `nbdif_`j''
+ }
+ local nbmoda_sum = `nbmoda_sum' + `nbdif_`j''
+}
+
+/* Au moins 2 mmoda par item */
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' == 1 {
+ di in red "``j'' have only one response category, each item need at least 2 response categories"
+ error 198
+ exit
+ }
+}
+
+/* Vérification moda théorique VS moda réelles -> CONSTAT */
+if "`moda'" != "" {
+ forvalues j=1/`nbitems' {
+ local nbmoda`j':word `j' of `moda'
+
+ if `nbmoda`j'' != `nbmoda_`j'' { //nbmodaj = nb moda annoncé par l'uti. (théorique) VS nbmoda_j = nb moda utilisée (réel)
+ di " WARNING : `nbmoda`j'' response categories exist for item ``j'' but only `nbmoda_`j'' seem to be used"
+ local recoda_`j' = 1
+ }
+ }
+}
+
+local coln ""
+forvalues j =1 /`nbitems' {
+ local coln "`coln' ``j''"
+}
+
+matrix nbmod = J(2,`nbitems',.)
+
+matrix colnames nbmod = `coln'
+matrix rownames nbmod = NbModa Recoding
+
+forvalues j = 1/`nbitems' {
+ matrix nbmod[1,`j'] = `nbmoda_`j''
+ matrix nbmod[2,`j'] = `recoda_`j''
+}
+
+*Erreur si plus de 200 difficultés
+local nb_test = 0
+forvalues j=1/`nbitems' {
+ local nb_test = `nb_test'+`nbmoda_`j'' -1
+}
+
+if `nb_test' >= 200 {
+ di in red "The number of items difficulties must be less than 200 ({hi:moda} option option). Please correct this option."
+ error 198
+ exit
+}
+
+local nbitp = 0
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ local nbitp = `nbitp' + 1
+ }
+}
+
+
+/*********************************
+* AFFICHAGE INITIAL
+*********************************/
+di _col(5) "{hline 78}"
+di _col(5) in ye %~30s "Time 1" _col(30) %~30s "Time 2" _col(55) "Nb of Responses Cat."
+di _col(5) "{hline 78}"
+forvalues j=1/`nbitems' {
+ di in gr _col(5) %~30s abbrev("``j''",20) _col(30) %~30s abbrev("``=`j'+`nbitems'''",20) _col(75) `nbmoda_`j''
+}
+di _col(5) "{hline 78}"
+if "`group'" != "" {
+ di _col(10) "Nb. of patients : " abbrev("`gp'",20) " 0 = `nbp_gp0' ;", abbrev("`gp'",20) " 1 = `nbp_gp1'"
+ di _col(5) "{hline 78}"
+}
+else {
+ di _col(20) "Nb. of patients : `nbpat'"
+ di _col(5) "{hline 78}"
+}
+di
+if `nbitems' == 1 {
+ di in red "2 items at least is necessary to detect DIF and/or RC at item level."
+ error 198
+ exit
+}
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' == 2 {
+ di "WARNING: ``j'' have only 2 response categories, the type uniform or non-uniform can't be detected."
+ }
+ if `nbmoda_`j'' == 1 {
+ di in red "``j'' uses only `nbmoda_`j'' response category, each item need at least 2 response categories used."
+ error 198
+ exit
+ }
+ if `nbmoda_`j'' == 0 {
+ di in red "``j'' uses no response category, each item needs at least 2 response categories used."
+ error 198
+ exit
+ }
+}
+di
+if "`group'" != "" {
+ di _col(2) in ye "For all models : - mean of latent trait of `gp' 0 at time 1 is constrained at 0"
+ di _col(19) "- Equality of variances between groups"
+ di
+}
+else {
+ di _col(2) in ye "For all models : mean of latent trait at time 1 is constrained at 0"
+ di
+}
+
+/*********************************
+* DEFINITION DES CONTRAINTES
+*********************************/
+
+if "`group'"!="" { // Contraintes si option groupe
+ *EGALITE ENTRE GROUPES A T1 (1-200)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=0+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``j'']1.`gp'
+ }
+ }
+
+ *DIF UNIFORME A T1 (201-400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=200+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'-[`p'.``j'']0bn.`gp'=`p'*[1.``j'']1.`gp'-`p'*[1.``j'']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 0 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 1 (601-800)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=600+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'
+ }
+ }
+
+ * RC COMMUNE (801-1000)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=800+`maxdif'*(`j'-1)+`p'' [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 0 (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 1 (1201-1400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1200+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ *Sans interaction temps x groupe
+ constraint 1999 [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'=[/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+}
+else { //Contraintes si pas d'option groupe
+ *EGALITE ENTRE T1 et T2 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']:_cons = [`p'.``=`j'+`nbitems''']:_cons
+ }
+ }
+ *RC UNIFORME (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']:_cons - [1.``j'']:_cons)=[`p'.``=`j'+`nbitems''']:_cons -[`p'.``j'']:_cons
+ }
+ }
+}
+
+/*********************************
+* MATRICE DES RESULTATS
+*********************************/
+matrix dif_rc=J(`nbitems',8,.)
+matrix colnames dif_rc=DIFT1 DIFU RC RC_DIF RCG0 RCUG0 RCG1 RCUG1
+local rown ""
+
+forvalues j =1 /`nbitems' {
+ local rown "`rown' ``j''"
+}
+matrix rownames dif_rc = `rown'
+
+*Nb modalité max
+local nbdif_max = 0
+forvalues j=1/`nbitems' {
+ if `nbdif_max' < `nbdif_`j'' {
+ local nbdif_max = `nbdif_`j''
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 1 : DIF A T1 ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+
+if "`group'"!="" & "`nodif'"=="" { // PARTIE 1 = Slmt si option group & pas de "nodif"
+ di _dup(59) "_ "
+ di
+ di _col(5) in ye "PART 1: DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS AT FIRST TIME OF MEASUREMENT"
+
+ *********************************
+ ** MODEL B **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading cons) var(0: THETA@v) var(1:THETA@v)
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifB
+ matrix val_mB = r(table)
+ matrix esti_B = e(b)
+
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mB=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+
+ matrix colnames delta_mB = `name_partOneC'
+ matrix rownames delta_mB = `name_partOneL'
+ matrix delta_mB_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mB_se = `name_partOneC_se'
+ matrix rownames delta_mB_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB=r(estimate)
+ local delta`j'_`p'g`g'mB_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB = r(estimate)
+ local delta`j'_`p'g`g'mB_se = r(se)
+ }
+ matrix delta_mB[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB'
+ matrix delta_mB_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB_se'
+ }
+ }
+ }
+
+ matrix var_mB = (val_mB[1,"/var(THETA)#0bn.`gp'"]\val_mB[2,"/var(THETA)#0bn.`gp'"])
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmB=r(estimate)
+ local segeffmB=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmBp=r(p)
+ local gcmBchi=r(chi2)
+ local gcmBdf=r(df)
+
+
+ *********************************
+ ** MODEL A **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading means) var(0: THETA@v) var(1:THETA@v) from(esti_B, skip)
+
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifA
+ matrix val_mA = r(table)
+ matrix esti_A = e(b)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mA=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mA = `name_partOneC'
+ matrix rownames delta_mA = `name_partOneL'
+ matrix delta_mA_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mA_se = `name_partOneC_se'
+ matrix rownames delta_mA_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA=r(estimate)
+ local delta`j'_`p'g`g'mA_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA = r(estimate)
+ local delta`j'_`p'g`g'mA_se = r(se)
+ }
+ matrix delta_mA[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA'
+ matrix delta_mA_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA_se'
+ }
+ }
+ }
+ //Variance et se mA
+ matrix var_mA = (val_mA[1,"/var(THETA)#0bn.`gp'"]\val_mA[2,"/var(THETA)#0bn.`gp'"])
+
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+
+ //Affichage modĂšle A
+ di
+ di in ye "PROCESSING STEP A"
+ di
+
+
+ /* Affichage des estimations des difficultés modÚle A */
+
+ di _col(5) in ye "{ul:MODEL A:} No group effect: mean of latent trait of group 1 = mean of latent trait of group 0,"
+ di _col(7) in ye "all item difficulties are freely estimated in both groups"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 70}"
+ di _col(30) in ye abbrev("`gp'",20) "=0" _col(60) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 70}"
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ di in gr _col(10) "`p'" _col(30) %6.2f `delta`j'_`p'g0mA' %6.2f " (" %3.2f `delta`j'_`p'g0mA_se' ")" _col(60) %6.2f `delta`j'_`p'g1mA' " (" %3.2f `delta`j'_`p'g1mA_se' ")"
+ }
+ }
+ di _col(10) "{hline 70}"
+ /* Affichage des estimations sur le trait latent du modĂšle A */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ di _col(10) "{hline 65}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error"
+ di _col(10) "{hline 65}"
+ di _col(10) in ye "Variance" in gr _col(45) %6.2f `=var_mA[1,1]' _col(62) %6.2f `=var_mA[2,1]'
+ di _col(10) in ye "Group effect (mean gp 1)" in gr _col(44) %6.2f "0 (constrained)"
+ di _col(10) "{hline 65}"
+
+ //*Affichage modĂšle B
+
+ di
+ di in ye "PROCESSING STEP B"
+ di
+
+ /* Affichage des estimations des difficultés modÚle B */
+
+ di _col(5) in ye "{ul:MODEL B:} Group effect estimated: mean of latent trait of group 1 free estimated,"
+ di _col(7) in ye "Same item difficulties estimated between groups"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 70}"
+ di _col(30) in ye abbrev("`gp'",20) "=0" _col(60) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 70}"
+
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ di in gr _col(10) "`p'" _col(30) %6.2f `delta`j'_`p'g0mB' " (" %3.2f `delta`j'_`p'g0mB_se' ")" _col(60) %6.2f `delta`j'_`p'g1mB' " (" %3.2f `delta`j'_`p'g1mB_se' ")"
+ }
+ }
+
+ di _col(10) "{hline 70}"
+ /* Affichage des estimations sur le trait latent du modĂšle B */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+ di _col(10) in ye "Variance" in gr _col(44) %6.2f `=var_mB[1,1]' _col(62) %6.2f `=var_mB[2,1]'
+ di _col(10) in ye "Group effect (mean gp 1)" in gr _col(44) %6.2f `geffmB' _col(62) %6.2f `segeffmB' _col(77) %6.4f `gcmBp'
+ di _col(10) "{hline 80}"
+ di
+
+ *****************************************************
+ * ModĂšle A vs ModĂšle B *
+ *****************************************************
+
+ qui lrtest modeldifA modeldifB
+ local diftestp=r(p)
+ local diftestchi=r(chi2)
+ local diftestdf=r(df)
+
+ //affichage lrtest
+ di _col(10) in ye "LIKELIHOOD-RATIO TEST MODEL A VS MODEL B : "
+ di _col(10) "{hline 50}"
+ di _col(10) in ye "Chi-square" _col(30) "DF" _col(50) "P-value"
+ di _col(10) in gr %6.2f `diftestchi' _col(30) %2.0f `diftestdf' _col(50) %6.4f `diftestp'
+ di _col(10) "{hline 50}"
+ if `diftestp'<0.05{
+ di _col(10) in ye "DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS LIKELY"
+ }
+ else{
+ di _col(10) in ye "NO DIFFERENCE BETWEEN GROUPS DETECTED"
+ }
+
+ *********************************
+ *************MODEL C*************
+ *********************************
+ // Etape itérative si lrtest significatif
+ local nb_stepC = 0
+
+ if `diftestp'<0.05{ /*If pvalue(LRtest)<0.05 then step C*/
+ di
+ di in ye "PROCESSING STEP C"
+ di
+ /*test DIF pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ while `boucle'<=`=`nbitp'-1' & `stop'==0{ /*on s'arrĂȘte quand on a libĂ©rĂ© du DIF sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_stepC = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle''
+ /*réinitialisation de la matrice de test*/
+ matrix test_difu_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_difu_`boucle'=chi_DIFU df_DIFU pvalueDIFU
+ matrix test_dif_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_dif_`boucle'=chi_DIF df_DIF pvalueDIF
+ local nbsig=0
+ local minpval=1
+ local itemdif=0
+ di _col(10) "{hline 70}"
+ di _col(10) in ye "Loop `boucle'" _col(50) "Adjusted alpha: " %6.4f `pajust'
+ di
+ di in ye _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-Value"
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ //if `nbdif_`j'' > 2 {
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF déjà détecté sur l'item j*/
+ /*on libĂšre le DIF de l'item i: pas de contraintes*/
+ forvalues k=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if `k'!=`j' & `nbmoda_`j'' >= 2 {
+ if dif_rc[`k',1]==. | dif_rc[`k',1]==0 {/*pas de DIF sur item k: contraintes 1-200*/
+ forvalues p=1/`nbdif_`k''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!= 0 & `nbmoda_`k'' > 2 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`k''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B)
+ estimates store modeldif3b`boucle'it`i'
+
+ *************************
+ *****test DIF item i*****
+ *************************
+ qui test [1.``j'']0bn.`gp'=[1.``j'']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``j'']1.`gp', acc
+ }
+ }
+ matrix test_dif_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+ /* Test DIF Uniforme */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``j'']0bn.`gp'-[1.``j'']1.`gp')=[2.``j'']0bn.`gp'-[2.``j'']1.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``j'']0bn.`gp'-[1.``j'']1.`gp')=[`p'.``j'']0bn.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ matrix test_difu_`boucle'[`j',1]=(r(chi2), r(df), r(p))
+ }
+
+ if test_dif_`boucle'[`j',3]<`pajust'{/*si DIF sur item i*/
+ local ++nbsig
+ if test_dif_`boucle'[`j',3]<`minpval'{
+ local minpval=test_dif_`boucle'[`j',2]
+ local itemdif=`j'
+ }
+ }
+ di in ye _col(12) %-30s abbrev("``j'' :",22) in gr _col(40) %6.3f test_dif_`boucle'[`j',1] _col(55) test_dif_`boucle'[`j',2] _col(60) %6.4f test_dif_`boucle'[`j',3]
+ }
+ }
+ /*si nb de tests significatifs=0, on arrĂȘte*/
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ di
+ di _col(20) in ye ">>> No significant test: no difference between groups detected, no DIF detected"
+ di _col(10) "{hline 70}"
+ }
+ else {
+ di
+ di _col(20) in ye ">>> No other significant tests"
+ di _col(10) "{hline 70}"
+ }
+ }
+ else{/*si nb de tests significatifs>0, mise à jour de la matrice de résultats*/
+ matrix dif_rc[`itemdif',1]=`boucle'
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Difference between groups on ``itemdif'' at time 1"
+ if `nbmoda_`itemdif'' > 2 {
+ di
+ di _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Uniform ? " in gr _col(40) %4.2f `=test_difu_`boucle'[`itemdif',1]' _col(55) `=test_difu_`boucle'[`itemdif',2]' _col(60) %4.2f `=test_difu_`boucle'[`itemdif',3]'
+ if test_difu_`boucle'[`itemdif',3]<0.05{ /*DIF NU détectée*/
+ matrix dif_rc[`itemdif',2]=0
+ di
+ di _col(17) in ye " >>> ``itemdif'' : Non-uniform differences of item difficulties between groups at T1"
+ di _col(15) _dup(60) "-"
+
+ }
+ else{/*DIF U détectée*/
+ matrix dif_rc[`itemdif',2]=`boucle'
+ di
+ di _col(17) in ye ">>> ``itemdif'' : Uniform differences of item difficulties between groups at T1"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else {
+ // Différence entre groupes au temps 1 mais slmt 2 moda. donc pas de U ou NU
+ di _col(15) _dup(60) "-"
+ }
+ }
+ local ++boucle
+ }
+ }
+
+ /* MODELE FINAL DE LA PARTIE 1. Si DIFT1 détecté (=Au moins 2 boucles dans l'étape C)*/
+ if `nb_stepC' > 1 {
+ forvalues j=1/`nbitems'{
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B)
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifCFin
+ matrix val_mC = r(table)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mCFin=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mCFin = `name_partOneC'
+ matrix rownames delta_mCFin = `name_partOneL'
+
+ matrix delta_mCFin_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+ matrix colnames delta_mCFin_se = `name_partOneC_se'
+ matrix rownames delta_mCFin_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin=r(estimate)
+ local delta`j'_`p'g`g'mCFin_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin = r(estimate)
+ local delta`j'_`p'g`g'mCFin_se = r(se)
+ }
+ matrix delta_mCFin[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin'
+ matrix delta_mCFin_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin_se'
+ }
+ }
+ }
+ if "`group'" != "" { //Variance et se mA
+ matrix var_mC = (val_mC[1,"/var(THETA)#0bn.`gp'"]\val_mC[2,"/var(THETA)#0bn.`gp'"])
+ }
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmCFin=r(estimate)
+ local segeffmCFin=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmCFinp=r(p)
+ local gcmCFinchi=r(chi2)
+ local gcmCFindf=r(df)
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 2 : RECALIBRATION ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+di
+di _dup(59) "_ "
+di
+if "`group'" != "" {
+ di in ye "PART 2 : DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES (RECALIBRATION)"
+}
+else {
+ di in ye "DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES (RECALIBRATION)"
+}
+
+ *********************************
+ ** MODEL 2 **
+ *********************************
+
+
+local listconst ""
+
+forvalues j=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes)*/
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF Ă T1 sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 200*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 0 (401-600)*/
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 1 (601-800)*/
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+}
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst')
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst')
+}
+
+/*Stockage des données du modÚle 2 */
+estimates store model2
+matrix val_m2 = r(table)
+matrix esti_2 = e(b)
+
+if "`group'" != "" {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)#0bn.`gp'"],val_m2[1,"/var(THETA2)#0bn.`gp'"]\val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"]\val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)"]\val_m2[2,"/cov(THETA1,THETA2)"]\val_m2[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm2=r(estimate)
+ local segeffm2=r(se)
+ local ubgeffm2 = r(ub)
+ local lbgeffm2 = r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm2p=r(p)
+ local gpm2chi=r(chi2)
+ local gpm2df=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* [/]:mean(THETA1)*/
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2) = 0 /* [/]:mean(THETA1)*/
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ local interm2=r(estimate)
+ local seinterm2=r(se)
+ local ubinterm2 = r(ub)
+ local lbinterm2 = r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ local interm2p=r(p)
+ local interm2chi=r(chi2)
+ local interm2df=r(df)
+}
+
+if "`group'" != "" {
+ matrix mod2 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod2 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2= r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se= r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2=r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se=r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2= r(estimate)
+ local delta`t'_`j'_`p'g0m2_se= r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2=r(estimate)
+ local delta`t'_`j'_`p'g0m2_se=r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod2[1,`=4*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)#0bn.`gp'"], val_m2[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)#0bn.`gp'"],val_m2[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)#0bn.`gp'"],val_m2[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = `seinterm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2p'
+}
+else {
+ matrix mod2[1,`=2*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)"],val_m2[6,"/var(THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)"],val_m2[5,"/var(THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm2'
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm2'
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm2'
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm2'
+ matrix mod2[5,`=2*`nbmoda_sum'+2+1+1'] = `tm2chi'
+ matrix mod2[6,`=2*`nbmoda_sum'+2+1+1'] = `tm2df'
+ matrix mod2[7,`=2*`nbmoda_sum'+2+1+1'] = `tm2p'
+}
+
+
+ *********************************
+ ** MODEL 1 **
+ *********************************
+
+
+/*PCM longitudinal, no true change, group effect, interaction*/
+local listconst ""
+forvalues j=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if `nbdif_`j'' > 1 {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 201*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+}
+
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'"!="" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@0) means(1: THETA1@m1 THETA2@m1) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@0) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) from(esti_2, skip)
+}
+
+/* Stockage des estimations du modĂšle 1 */
+estimates store model1
+matrix val_m1 = r(table)
+
+/* Calcul des difficultés d'item (delta_j) */
+matrix delta_m1 = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC ""
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' delta_t`t'_`p'_gp`g'"
+ }
+ }
+}
+
+local name_partTwoL ""
+forvalues j=1/`=`nbitems'*2' {
+ if `j' <= `nbitems' {
+ local name_partTwoL "`name_partTwoL' ``j''"
+ }
+ else {
+ local name_partTwoL "`name_partTwoL' ``=`nbitems'+`j'''"
+ }
+}
+
+matrix colnames delta_m1 = `name_partTwoC'
+matrix rownames delta_m1 = `name_partTwoL'
+
+matrix delta_m1_se = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC_se ""
+
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC_se "`name_partTwoC_se' delta_t`t'_`p'_gp`g'_se"
+ }
+ }
+}
+
+matrix colnames delta_m1_se = `name_partTwoC_se'
+matrix rownames delta_m1_se = `name_partTwoL'
+
+if "`group'"!="" {
+ forvalues t=1/2{
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1= r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1=r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ }
+ }
+ }
+ }
+}
+else {
+ forvalues t=1/2 {
+ forvalues j=1/`nbitems' {
+ forvalues p = 1/`nbdif_`j'' {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1= r(estimate)
+ local delta`t'_`j'_`p'g0m1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1=r(estimate)
+ local delta`t'_`j'_`p'g0m1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)#0bn.`gp'"],val_m1[1,"/var(THETA2)#0bn.`gp'"]\val_m1[2,"/var(THETA1)#0bn.`gp'"],val_m1[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)"],val_m1[1,"/var(THETA2)"]\val_m1[2,"/var(THETA1)"],val_m1[2,"/var(THETA2)"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)"]\val_m1[2,"/cov(THETA1,THETA2)"]\val_m1[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'"!="" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm1=r(estimate)
+ local segeffm1=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ local gpm1p=r(p)
+ local gpm1chi=r(chi2)
+ local gpm1df=r(df)
+}
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+
+// Affichage du modĂšle 1
+di
+di in ye "PROCESSING STEP 1"
+di
+ /* Affichage des estimations des difficultés */
+
+if "`group'" != "" {
+ di _col(5) in ye "{ul:MODEL 1:} Group effect estimated, no time effect (mean of latent trait of group 0 at T2) equal to mean of group 0 at T1),"
+ di _col(7) in ye "all item difficulties are freely estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(5) in ye "{ul:MODEL 1}: no time effect,"
+ di _col(7) in ye "all item difficulties are freely estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+}
+
+forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m1' " (" %4.2f `delta1_`j'_`p'g1m1_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m1' " (" %4.2f `delta2_`j'_`p'g1m1_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")"
+ }
+ }
+}
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+}
+ /* Affichage des estimations du trait latent du modĂšle 1 */
+di
+di _col(10) in ye "Latent trait distribution estimates"
+if "`group'" != "" {
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+}
+else {
+ di _col(10) "{hline 70}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" "
+ di _col(10) "{hline 70}"
+}
+di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=var_m1[1,1]' _col(62) %6.2f `=var_m1[2,1]'
+di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=var_m1[1,2]' _col(62) %6.2f `=var_m1[2,2]'
+di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=covar_m1[1,1]' _col(62) %6.2f `=covar_m1[2,1]'
+if "`group'" != "" {
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm1' _col(62) %6.2f `segeffm1' _col(77) %6.4f `gpm1p'
+}
+di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) "0 (constrained)"
+if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) "0 (constrained)"
+}
+if "`group'" != "" {
+ di _col(10) "{hline 80}"
+}
+else {
+ di _col(10) "{hline 70}"
+}
+//Affichage du modĂšle 2
+di
+di in ye "PROCESSING STEP 2"
+di
+ /* Affichage des estimations des difficultés */
+
+if "`group'" != "" {
+ di _col(5) in ye "{ul:MODEL 2:} Group effect, time effect (mean of latent trait of group 0 at T2) free estimated, time x group interaction estimated,"
+ di _col(7) in ye "Same item difficulties estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(5) in ye "{ul:MODEL 2}: time effect estimated (mean of latent trait group 0 at T2) free estimated,"
+ di _col(7) in ye "Same item difficulties estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+}
+
+forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m2' " (" %4.2f `delta1_`j'_`p'g1m2_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m2' " (" %4.2f `delta2_`j'_`p'g1m2_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")"
+ }
+ }
+}
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+}
+ /* Affichage des estimations du trait latent du modĂšle 2 */
+di
+di _col(10) in ye "Latent trait distribution estimates"
+di _col(10) "{hline 80}"
+di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+di _col(10) "{hline 80}"
+
+if "`group'" == "" {
+ local fact_k = 2
+}
+else {
+ local fact_k = 4
+}
+
+di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+1']' _col(62) %6.2f =mod2[2,`=`fact_k'*`nbmoda_sum'+1']
+di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+2']' _col(62) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+2']'
+di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+3']' _col(62) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+3']'
+
+if "`group'" != "" {
+
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm2' _col(62) %6.2f `segeffm2' _col(77) %6.4f `gpm2p'
+}
+di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f `teffm2' _col(62) %6.2f `seteffm2' _col(77) %6.4f `tm2p'
+
+if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f `interm2' _col(62) %6.2f `seinterm2' _col(77) %6.4f `interm2p'
+}
+di _col(10) "{hline 80}"
+di
+ *****************************************************
+ * ModĂšle 1 vs ModĂšle 2 *
+ *****************************************************
+qui lrtest model2 model1
+
+local rstestp=r(p)
+local rstestchi=r(chi2)
+local rstestdf=r(df)
+di _col(10) in ye "LIKELIHOOD-RATIO TEST MODEL 1 VS MODEL 2"
+di _col(10) "{hline 50}"
+di _col(10) in ye "Chi-square" _col(30) "DF" _col(50) "P-value"
+di _col(10) in gr %6.2f `rstestchi' _col(30) %2.0f `rstestdf' _col(50) %6.4f `rstestp'
+di _col(10) "{hline 50}"
+if `rstestp'<0.05{
+di _col(10) in ye "DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES LIKELY"
+}
+else{
+di _col(10) in ye "NO DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES DETECTED, NO RECALIBRATION DETECTED"
+}
+
+ *********************************
+ *************MODEL 3*************
+ *********************************
+// Etape itérative si lrtest significatif
+local nb_step3=0
+
+if `rstestp' < 0.05 { /* If pvalue(LRtest)<0.05 then step 3 */
+ di
+ di in ye "PROCESSING STEP 3"
+ di
+ /*test RC pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ //matrix list dif_rc
+ while `boucle' <= `=`nbitp'-1' & `stop' == 0 { /*on s'arrĂȘte quand on a libĂ©rĂ© du RC sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_step3 = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle'' // local pajust=0.05/`=`nbitems'+1-`boucle'
+ if "`group'" != "" {
+ local pajust2 = 0.05/`nbgrp'
+ }
+ /*réinitialisation de la matrice de test*/
+ matrix test_rc_`boucle'=J(`nbitems',9,.)
+ matrix test_rcCOMM_`boucle'=J(`nbitems',3,.)
+ matrix test_rcU_`boucle'=J(`nbitems',6,.)
+ matrix colnames test_rc_`boucle'= chi_RC df_RC pvalue_RC chi_RCg0 df_RCg0 pvalue_RCg0 chi_RCg1 df_RCg1 pvalue_RCg1
+ matrix colnames test_rcCOMM_`boucle'= chi_RCCOMM df_RCCOMM pvalue_RCCOMM
+ matrix colnames test_rcU_`boucle'= chi_RCUg0 df_RCUg0 pvalue_RCUg0 chi_RCUg1 df_RCUg1 pvalue_RCUg1
+ local nbsig=0
+ local minpval=1
+ local itemrc=0
+ di _col(10) "{hline 70}"
+ di _col(10) in ye "Loop `boucle'" _col(50) "Adjusted alpha : " %6.4f `pajust'
+ di
+ di in ye _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-Value"
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ if `nbdif_`j'' >= 1 {
+ local model ""
+ local listconst ""
+ if dif_rc[`j',3]==. { /*si pas de RC déjà détecté sur l'item j -> test item j*/
+ /*on libĂšre la RC de l'item j: pas de contraintes*/
+ forvalues k=1/`nbitems'{
+ /* Contraintes de DIF */
+ if dif_rc[`k',1]==.|dif_rc[`k',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ if `k'!=`j'{ /*contraintes pour les autres items */
+ if dif_rc[`k',3]==. | dif_rc[`k',3]==0 {/*pas de RC sur item k: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item k
+ if dif_rc[`k',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`k''{ /***************************** j=1 ou 2 ?****/
+ local listconst "`listconst' `=800+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`k'-1)+`p''
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RC commune unif.
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`k',5]==. | dif_rc[`k',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`k',7]==. | dif_rc[`k',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',8]!=. & dif_rc[`k',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ if "`group'" == "" { // Sans l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+
+ /*****************/
+ /*tests RC item i*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']_cons =[1.``=`j'+`nbitems''']_cons
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']_cons =[`p'.``=`j'+`nbitems''']_cons, acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+ /* RCU ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[2.``=`j'+`nbitems''']_cons -[2.``j'']_cons
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[`p'.``=`j'+`nbitems''']_cons -[`p'.``j'']_cons , acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2), r(df),r(p))
+ }
+ }
+ else { // Avec l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+
+ /*****************/
+ /*tests RC item i*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp', acc
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC COMMUNE ? */
+ qui test [1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ }
+ matrix test_rcCOMM_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC groupe 0 ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[2.``=`j'+`nbitems''']0bn.`gp'-[2.``j'']0bn.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ }
+
+ /* RC groupe 1 ? */
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',7]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 1 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[2.``=`j'+`nbitems''']1.`gp'-[2.``j'']1.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+ }
+ }
+ /******* Matrice test complĂšte *********/
+ di in ye _col(10) %-30s abbrev("``j'' :",22) in gr _col(40) %6.3f test_rc_`boucle'[`j',1] _col(55) test_rc_`boucle'[`j',2] _col(60) %6.4f test_rc_`boucle'[`j',3]
+ }
+ }
+ }
+ //matrix list test_rc_`boucle'
+ forvalues j=1/`nbitems'{
+ if test_rc_`boucle'[`j',3]<`pajust'{/*si RC sur item i*/
+ if test_rc_`boucle'[`j',3]<`minpval'{
+ local minpval=test_rc_`boucle'[`j',3]
+ local itemrc=`j'
+ }
+ }
+ }
+ if `itemrc' != 0 { // itemrc = numéro de l'item avec le test le + sig.
+ if "`group'" == "" { // Recalibration si pas d'option groupe
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Recalibration on ``itemrc''"
+ di _col(40) "Chi-square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Uniform RC ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(55) `=test_rcU_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { //RC Uniforme sur itemRC
+ matrix dif_rc[`itemrc',6]=`boucle'
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Uniform RC"
+ di _col(15) _dup(60) "-"
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Non-uniform RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else {
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Recalibration "
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else { // Option groupe
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Recalibration on ``itemrc''"
+ di
+ di _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Common RC ? " in gr _col(40) %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' _col(55) `=test_rcCOMM_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcCOMM_`boucle'[`itemrc',3]'
+ if test_rcCOMM_`boucle'[`itemrc',3] < 0.05 { //RC différentielle
+ di
+ di _col(15) in ye "RC group 0 ? " in gr _col(40) %4.2f `=test_rc_`boucle'[`itemrc',4]' _col(55) `=test_rc_`boucle'[`itemrc',5]' _col(60) %6.4f `=test_rc_`boucle'[`itemrc',6]' "{it: - with adjusted alpha = `pajust2' }"
+ if test_rc_`boucle'[`itemrc',6] < `pajust2' { //RC gp 0
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ di _col(15) in ye "Uniform RC on gp 0 ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(55) `=test_rcU_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { // RCU gp 0
+ matrix dif_rc[`itemrc',6]=`boucle'
+ local phrase_diff = ">>> ``itemrc'' : Uniform differential RC on group 0."
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ local phrase_diff = ">>> ``itemrc'' : Non-uniform differential RC on group 0."
+ }
+ }
+ else {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 0."
+ }
+ }
+ di
+ di _col(15) in ye "RC group 1 ? " in gr _col(40) %4.2f `=test_rc_`boucle'[`itemrc',7]' _col(55) `=test_rc_`boucle'[`itemrc',8]' _col(60) %6.4f `=test_rc_`boucle'[`itemrc',9]' "{it: - with adjusted alpha = `pajust2' }"
+ if test_rc_`boucle'[`itemrc',9] < `pajust2' { //RC gp 1
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ di _col(15) in ye "Uniform RC on gp 1 ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',4]' _col(55) `=test_rcU_`boucle'[`itemrc',5]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',6]'
+ if test_rcU_`boucle'[`itemrc',6] >= 0.05 { // RCU gp 1
+ matrix dif_rc[`itemrc',8]=`boucle'
+ di
+ if dif_rc[`itemrc',5] != `boucle' { //RC slmt sur g1
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 0 and uniform RC on group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 0 and uniform RC on group 1."
+ }
+ }
+ }
+ else { //RCNU gp 1
+ matrix dif_rc[`itemrc',8]=0
+ di
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 0 and non-uniform RC on group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 0 and non-uniform RC on group 1."
+ }
+ }
+ }
+ }
+ else {
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 1."
+ }
+ else {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 0 and differential RC on group 1."
+ }
+ }
+ }
+ di
+ di _col(17) in ye "`phrase_diff'"
+ di _col(15) _dup(60) "-"
+ }
+ else { // RC commune -> MAJ modĂšle 3
+ /*******************************************************************************************************************/
+ if `nbmoda_`itemrc'' == 2 {
+ di
+ di _col(14) in ye ">>> {ul:``itemrc''}: recalibration"
+ di _col(20) in ye "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ local ++nbsig
+ }
+ else {
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ //matrix list dif_rc
+ local model ""
+ local listconst ""
+ forvalues j=1/`nbitems'{
+ /* Contraintes de DIF */
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ if `j' != `itemrc'{ /*contraintes pour les autres items */
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 {/*pas de RC sur item p: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item p
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else if dif_rc[`j',4] != 0 & dif_rc[`j',4]!=0. { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ else { // Contrainte de RC commune pour l'itemrc
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`itemrc'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`itemrc'-1)+`p''
+ }
+ }
+ }
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+
+ /************************/
+ /*tests RC item `itemrc'*/
+ /************************/
+ matrix commU_`boucle'=J(`nbitems',3,.) //Matrice des tests de RCU slmt si RC commune
+ matrix colnames commU_`boucle'= chi_RCU df_RCU p_RCU
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`itemrc'' > 2 {
+ qui test 2*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[2.``=`itemrc'+`nbitems''']0bn.`gp'-[2.``itemrc'']0bn.`gp'
+ forvalues j=3/`nbdif_`itemrc''{
+ qui test `j'*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[`j'.``=`itemrc'+`nbitems''']0bn.`gp'-[`j'.``itemrc'']0bn.`gp', acc
+ }
+ matrix commU_`boucle'[`itemrc',1]=(r(chi2),r(df),r(p))
+ di _col(15) in ye "Uniform RC ?" in gr _col(40) %4.2f `=commU_`boucle'[`itemrc',1]' _col(55) `=commU_`boucle'[`itemrc',2]' _col(60) %6.4f `=commU_`boucle'[`itemrc',3]'
+ if commU_`boucle'[`itemrc',3] >= 0.05 { // RCU
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=`boucle'
+ matrix dif_rc[`itemrc',8]=`boucle'
+ di
+ //di _col(14) in ye ">>> {ul:``itemrc''}: recalibration"
+ //di _col(20) in ye "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ di _col(17) in ye ">>> ``itemrc'' : Uniform common RC"
+ di _col(15) _dup(60) "-"
+ }
+ else {
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=0
+ matrix dif_rc[`itemrc',8]=0
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Non-uniform common RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ }
+ } // fin de RC commune
+ }
+ }
+ else {
+ local stop = 1
+ }
+ /*******************************************************************************************************************/
+ // Fin de RC sur item i
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ di
+ di _col(20) in ye "No significant tests, no recalibration detected"
+ di _col(10) "{hline 70}"
+ di
+ }
+ else {
+ di
+ di _col(20) in ye ">>> No other significant tests"
+ di _col(10) "{hline 70}"
+ di
+ }
+ }
+ local ++boucle
+ }
+}
+
+
+
+ *********************************
+ *** BILAN ***
+ *********************************
+
+
+
+if "`group'" != "" & "`nodif'" == "" {
+ di
+ di _col(2) "{hline 80}"
+ di in ye _col(18) "Difference in"
+ di in ye _col(2) "Item" _col(18) "groups at T1" _col(36) "Recalibration" _col(54) "RC " abbrev("`gp'",10) " 0" _col(72) "RC " abbrev("`gp'",10) " 1"
+ di _col(2) "{hline 80}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ local difft1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ if (dif_rc[`j',1] != . ) {
+ if (dif_rc[`j',2]!=0) {
+ local difft1 "Uniform"
+ }
+ else {
+ local difft1 "Non-uniform"
+ }
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ if dif_rc[`j',1] != . {
+ local difft1 " X "
+ }
+ }
+ di in ye _col(2) abbrev("``j''",15) in gr _col(18) "`difft1'" _col(36) "`RC'" _col(54) "`RCg0'" _col(72) "`RCg1'"
+ }
+ di _col(2) "{hline 80}"
+}
+else if "`group'" != "" & "`nodif'" != "" {
+ di
+ di _col(10) "{hline 70}"
+ di in ye _col(10) "Item" _col(26) "Recalibration" _col(46) "RC `gp' 0" _col(62) "RC `gp' 1"
+ di _col(10) "{hline 70}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ }
+ di in ye _col(10) "``j''" in gr _col(26) "`RC'" _col(44) "`RCg0'" _col(62) "`RCg1'"
+ }
+ di _col(10) "{hline 70}"
+}
+else if "`group'" == "" {
+ di
+ di _col(10) "{hline 40}"
+ di in ye _col(10) "Item" _col(36) "Recalibration"
+ di _col(10) "{hline 40}"
+ forvalues j=1/`nbitems' {
+ local RC
+ if dif_rc[`j',3] != . {
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RC "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RC "Non-uniform"
+ }
+ }
+ else {
+ local RC " X "
+ }
+ }
+ di in ye _col(10) "``j''" in gr _col(38) "`RC'"
+ }
+ di _col(10) "{hline 40}"
+}
+
+
+ *********************************
+ ** MODEL 4 **
+ *********************************
+di
+di in ye "PROCESSING STEP 4"
+di
+//matrix list dif_rc, title ("Constraints")
+
+local model ""
+local listconst ""
+forvalues j=1/`nbitems'{
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200 */
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 {/*pas de RC : contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item j
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+}
+
+qui di "`listconst'"
+local model ""
+
+forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means( THETA1@0 THETA2@m2) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip)
+}
+ /* Stockage des estimations du modĂšle */
+matrix val_m4 = r(table)
+matrix esti_4 = e(b)
+
+if "`group'" != "" {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)#0bn.`gp'"],val_m4[1,"/var(THETA2)#0bn.`gp'"]\val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"]\val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)"]\val_m4[2,"/cov(THETA1,THETA2)"]\val_m4[4,"/cov(THETA1,THETA2)"])
+}
+
+/* Matrice des tests effet grp, tps et inter */
+matrix effet = J(5,3,.)
+matrix colnames effet= Groupe Temps Interaction
+matrix rownames effet = Esti Std_Err Pvalue Chi DF
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,1] =r(estimate)
+ matrix effet[2,1]=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,1]=r(p)
+ matrix effet[4,1]=r(chi2)
+ matrix effet[5,1]=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,2]=r(estimate)
+ matrix effet[2,2]=r(se)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,2]=r(p)
+ matrix effet[4,2]=r(chi2)
+ matrix effet[5,2]=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* -[/]:mean(THETA1)*/
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local ubteffm4 = r(ub)
+ local lbteffm4 = r(lb)
+ qui test [/]:mean(THETA2) /* -[/]:mean(THETA1) */ = 0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,3]=r(estimate)
+ matrix effet[2,3]=r(se)
+ local ubinterm4=r(ub)
+ local lbinterm4=r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,3]=r(p)
+ matrix effet[4,3]=r(chi2)
+ matrix effet[5,3]=r(df)
+}
+
+if "`group'" != "" {
+ local effet_tps = 0
+ local effet_grp = 0
+
+ if effet[3,3] >= 0.05 { // Si option group, on s'interesse Ă l'interaction temps x group, et MAJ modĂšle >>> modĂšle final = modĂšle 4 + contrainte 1999 (Interaction = 0)
+ /* Affichage des estimations sur le trait latent du modĂšle 4 */
+ di
+ di _col(10) in ye "Latent trait estimates"
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+ di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=var_m4[1,1]' _col(62) %6.2f `=var_m4[2,1]'
+ di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=var_m4[1,2]' _col(62) %6.2f `=var_m4[2,2]'
+ di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=covar_m4[1,1]' _col(62) %6.2f `=covar_m4[2,1]'
+ if "`group'" != "" {
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f effet[1,1] _col(62) %6.2f effet[2,1] _col(77) %6.4f effet[3,1]
+ }
+ di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f effet[1,2] _col(62) %6.2f effet[2,2] _col(77) %6.4f effet[3,2]
+
+ if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f effet[1,3] _col(62) %6.2f effet[2,3] _col(77) %6.4f effet[3,3]
+ }
+ di _col(10) "{hline 80}"
+ di
+ di in ye ">>> Time x group interaction : no significant test, estimate of model 4 with constraint of time x group interaction at 0 "
+ di
+ local yn_inter = 0
+ local listconst "`listconst' 1999"
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_4, skip)
+
+ matrix val_m4 = r(table)
+ }
+ else {
+ local yn_inter = 1
+ }
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm4=r(estimate)
+ local segeffm4=r(se)
+ local ubgeffm4=r(ub)
+ local lbgeffm4=r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm4p=r(p)
+ local gpm4chi=r(chi2)
+ local gpm4df=r(df)
+
+ /*time effect*/
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local lbteffm4=r(lb)
+ local ubteffm4=r(ub)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+ /* Calcul des difficultés (delta_j) */
+if "`group'" != "" {
+ matrix mod4 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod4 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4= r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se= r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4=r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se=r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4= r(estimate)
+ local delta`t'_`j'_`p'g0m4_se= r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4=r(estimate)
+ local delta`t'_`j'_`p'g0m4_se=r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod4[1,`=4*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)#0bn.`gp'"], val_m4[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)#0bn.`gp'"],val_m4[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)#0bn.`gp'"],val_m4[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm4p'
+
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4p'
+
+ if `yn_inter' == 1 { //Slmt si model avec interaction
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[1,3]
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[2,3]
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[4,3]
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[5,3]
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[3,3]
+ }
+
+}
+else {
+ matrix mod4[1,`=2*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)"],val_m4[6,"/var(THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)"],val_m4[5,"/var(THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm4'
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm4'
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm4'
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm4'
+ matrix mod4[5,`=2*`nbmoda_sum'+2+1+1'] = `tm4chi'
+ matrix mod4[6,`=2*`nbmoda_sum'+2+1+1'] = `tm4df'
+ matrix mod4[7,`=2*`nbmoda_sum'+2+1+1'] = `tm4p'
+}
+
+
+ /* Affichage des estimations des difficultés */
+di _col(5) in ye "{ul:MODEL 4} = Final model"
+di
+di _col(10) in ye "Item difficulties estimates (s.e.)"
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+}
+
+forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m4' " (" %4.2f `delta1_`j'_`p'g1m4_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m4' " (" %4.2f `delta2_`j'_`p'g1m4_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")"
+ }
+ }
+}
+
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+}
+
+ /* Affichage des estimations sur le trait latent du modĂšle final */
+di
+di _col(10) in ye "Latent trait distribution estimates"
+di _col(10) "{hline 80}"
+di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+di _col(10) "{hline 80}"
+
+if "`group'" == "" {
+ local fact_k = 2
+}
+else {
+ local fact_k = 4
+}
+
+di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+1']' _col(62) %6.2f =mod4[2,`=`fact_k'*`nbmoda_sum'+1']
+di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+2']' _col(62) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+2']'
+di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+3']' _col(62) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+3']'
+
+if "`group'" != "" {
+
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm4' _col(62) %6.2f `segeffm4' _col(77) %6.4f `gpm4p'
+}
+di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f `teffm4' _col(62) %6.2f `seteffm4' _col(77) %6.4f `tm4p'
+
+if "`group'" != "" {
+ if effet[3,3] < 0.05 {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f effet[1,3] _col(62) %6.2f effet[2,3] _col(77) %6.4f effet[3,3]
+ }
+ else {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) "0 (constrained)"
+ }
+}
+
+di _col(10) "{hline 80}"
+
+/***************************************/
+/* Calcul des valeurs de DIF et de RC */
+/*************************************/
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ matrix valeur_difrc_`j' = J(`nbdif_`j'',8,.)
+ matrix colnames valeur_difrc_`j' = DIFT1 DIFT1_SE RC_GP0 RC_GP0_SE RC_GP1 RC_GP1_SE
+ }
+}
+
+forvalues j=1/`nbitems'{
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" {
+ *DIF
+ if "`nodif'"=="" {
+ if (dif_rc[`j',1] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ if `p' == 1 {
+ qui lincom -[1.``j'']:1.`gp'+[1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``j'']:1.`gp' - [`p'.``j'']:1.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ *RC GROUP 0
+ if (dif_rc[`j',3] != . & dif_rc[`j',5] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:0.`gp' + [1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:0.`gp' - [`p'.``=`j'+`nbitems''']:0.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ *RC GROUP 1
+ if (dif_rc[`j',3] != . & dif_rc[`j',7] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:1.`gp' + [1.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:1.`gp' - [`p'.``=`j'+`nbitems''']:1.`gp' -[`=`p'-1'.``j'']:1.`gp' + [`p'.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ else {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']_cons + [1.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']_cons - [`p'.``=`j'+`nbitems''']_cons -[`=`p'-1'.``j'']_cons + [`p'.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+}
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ forvalues p = 1/`nbdif_`j'' {
+ forvalues k = 1/8 {
+ if valeur_difrc_`j'[`p',`k'] == . {
+ matrix valeur_difrc_`j'[`p',`k'] = 0
+ }
+ }
+ }
+ }
+}
+
+ /* Affichage des estimations des valeurs de DIF et de RC */
+di
+di _col(10) in ye "Values of differences between groups and values of recalibration"
+if "`group'" != "" & "`nodif'"==""{
+ di _col(10) "{hline 70}"
+ di _col(30) "Difference of" _col(52) "RECALIBRATION"
+ di _col(30) "groups at T1" _col(47) in ye abbrev("`gp'",15) "=0" _col(62) abbrev("`gp'",15) " =1"
+ di _col(10) "{hline 70}"
+}
+else if "`group'" != "" & "`nodif'"!="" {
+ di _col(10) "{hline 50}"
+ di _col(32) "RECALIBRATION"
+ di in ye _col(27) "`gp'=`=rep[1,1]'" _col(47) "`gp'=`=rep[2,1]'"
+ di _col(10) "{hline 50}"
+}
+else {
+ di _col(10) "{hline 30}"
+ di _col(15) "RECALIBRATION"
+ di _col(10) "{hline 30}"
+}
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" & "`nodif'" == "" {
+ di in ye _col(10) "``j''"
+ }
+ else {
+ di in ye _col(10) "``j''"
+ }
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" & "`nodif'"=="" {
+ di in gr _col(10) "`p'" _col(29) %6.2f `=valeur_difrc_`j'[`p',1]' " (" %4.2f `=valeur_difrc_`j'[`p',2]' ")" ///
+ _col(47) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(62) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else if "`group'" != "" & "`nodif'"!="" {
+ di in gr _col(10) "`p'" _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(45) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")"
+ }
+ }
+ }
+}
+
+if "`group'" != "" & "`nodif'"=="" {
+ di _col(10) "{hline 70}"
+}
+else if "`group'" != "" & "`nodif'"!=""{
+ di _col(10) "{hline 50}"
+}
+else {
+ di _col(10) "{hline 30}"
+}
+di
+
+ *****************************************************
+ ** OUTPUTS POUR SIMULATIONS **
+ *****************************************************
+
+/*
+forvalues j= `nbitems' (-1) 1 {
+ if `nbmoda_`j'' >= 2 {
+ return matrix val_difrc_item`j'=valeur_difrc_`j'
+ }
+}
+
+* ModĂšle 4
+return matrix table_m4 = val_m4
+return matrix covariance_m4 = covar_m4
+return matrix variance_m4 = var_m4
+return matrix se_diff_m4 = delta_m4_se
+return matrix difficultiesm4 = delta_m4
+
+if "`group'" != "" {
+ return scalar with_inter=`yn_inter'
+ *Inter
+ return scalar interm4df=effet[5,3]
+ return scalar interm4chi=effet[4,3]
+ return scalar interm4p=effet[3,3]
+ return scalar interm4se=effet[2,3]
+ return scalar interm4=effet[1,3]
+
+ *Retour paramÚtres théta modÚle 4
+ if effet[3,3] < 0.05 { // Si modĂšle avec inter
+ return scalar teffm4df=effet[5,2]
+ return scalar teffm4chi=effet[4,2]
+ return scalar teffm4p=effet[3,2]
+ return scalar teffm4se=effet[2,2]
+ return scalar teffm4= effet[1,2]
+ * Effet groupe
+ return scalar gpeffm4df=effet[5,1]
+ return scalar gpeffm4chi=effet[4,1]
+ return scalar gpeffm4p=effet[3,1]
+ return scalar gpeffm4se=effet[2,1]
+ return scalar gpeffm4=effet[1,1]
+ }
+ if effet[3,3] >= 0.05 {
+ * Effet temps
+ return scalar teffm4df=`tm4df'
+ return scalar teffm4chi=`tm4chi'
+ return scalar teffm4p=`tm4p'
+ return scalar teffm4se=`seteffm4'
+ return scalar teffm4=`teffm4'
+ * Effet groupe
+ return scalar gpeffm4df=`gpm4df'
+ return scalar gpeffm4chi=`gpm4chi'
+ return scalar gpeffm4p=`gpm4p'
+ return scalar gpeffm4se=`segeffm4'
+ return scalar gpeffm4=`geffm4'
+ }
+}
+else {
+ if effet[3,3] < 0.05 { // Si modĂšle avec inter
+ return scalar teffm4df=effet[5,2]
+ return scalar teffm4chi=effet[4,2]
+ return scalar teffm4p=effet[3,2]
+ return scalar teffm4se=effet[2,2]
+ return scalar teffm4= effet[1,2]
+ }
+ if effet[3,3] >= 0.05 {
+ * Effet temps
+ return scalar teffm4df=`tm4df'
+ return scalar teffm4chi=`tm4chi'
+ return scalar teffm4p=`tm4p'
+ return scalar teffm4se=`seteffm4'
+ return scalar teffm4=`teffm4'
+ }
+}
+
+* Boucle de RC
+if `nb_step3' != 0 {
+ forvalues item = 1/`nbitems' {
+ forvalues s =1/`=`nb_step3'-1' {
+ if dif_rc[`item',4] == 0 & dif_rc[`item',3]==`s' & `nbmoda_`item'' > 2 {
+ return matrix commU_bcle`s'=commU_`s'
+ }
+ }
+ }
+}
+
+if `nb_step3' != 0 {
+ forvalues s =1/`nb_step3' {
+ return matrix ptest_rc_bcle`s'=ptest_rc_`s'
+ return matrix chitest_rc_bcle`s'=chitest_rc_`s'
+ return matrix dftest_rc_bcle`s'=dftest_rc_`s'
+ }
+}
+
+* ModĂšle 2
+return matrix table_m2 = val_m2
+return matrix covariance_m2 = covar_m2
+return matrix variance_m2 = var_m2
+return matrix se_diff_m2 = delta_m2_se
+return matrix difficultiesm2 = delta_m2
+
+* Effet temps
+if "`group'" != "" {
+ * Interaction
+ return scalar interm2df=`interm2df'
+ return scalar interm2chi=`interm2chi'
+ return scalar interm2p=`interm2p'
+ return scalar interm2se=`seinterm2'
+ return scalar interm2=`interm2'
+}
+return scalar teffm2df=`tm2df'
+return scalar teffm2chi=`tm2chi'
+return scalar teffm2p=`tm2p'
+return scalar teffm2se=`seteffm2'
+return scalar teffm2=`teffm2'
+
+if "`group'" != "" { // SI option group
+ * Effet groupe
+ return scalar gpeffm2df=`gpm2df'
+ return scalar gpeffm2chi=`gpm2chi'
+ return scalar gpeffm2p=`gpm2p'
+ return scalar gpeffm2se=`segeffm2'
+ return scalar gpeffm2=`geffm2'
+}
+
+* ModĂšle 1
+return matrix table_m1 = val_m1
+return matrix covariance_m1 = covar_m1
+return matrix variance_m1 = var_m1
+return matrix se_diff_m1 = delta_m1_se
+return matrix difficultiesm1 = delta_m1
+
+if "`group'" != "" { // Si option group
+ * Effet groupe
+ return scalar gpeffm1df=`gpm1df'
+ return scalar gpeffm1chi=`gpm1chi'
+ return scalar gpeffm1p=`gpm1p'
+ return scalar gpeffm1se=`segeffm1'
+ return scalar gpeffm1=`geffm1'
+}
+
+* ModĂšle C
+if "`group'" != "" & "`nodif'"=="" {
+ if `nb_stepC' != 0 {
+ forvalues s =1/`nb_stepC' {
+ return matrix ptest_dif_bcle`s'=ptest_dif_`s'
+ return matrix chitest_dif_bcle`s'=chitest_dif_`s'
+ return matrix dftest_dif_bcle`s'=dftest_dif_`s'
+ }
+
+ if `nb_stepC' != 1 {
+ * Effet groupe
+ return scalar gpeffmCdf=`gcmCFindf'
+ return scalar gpeffmCchi=`gcmCFinchi'
+ return scalar gpeffmCp=`gcmCFinp'
+ return scalar gpeffmCse=`segeffmCFin'
+ return scalar gpeffmC=`geffmCFin'
+ *Retour modĂšle C Final
+ return matrix table_mC = val_mC
+ return matrix variance_mC = var_mC
+ return matrix se_diff_mC = delta_mCFin_se
+ return matrix difficultiesmC = delta_mCFin
+ }
+ }
+
+ * ModĂšle B
+ return matrix table_mB = val_mB
+ return matrix variance_mB = var_mB
+ return matrix se_diff_mB = delta_mB_se
+ return matrix difficultiesmB = delta_mB
+
+ * Effet groupe
+ return scalar gpeffmBdf=`gcmBdf'
+ return scalar gpeffmBchi=`gcmBchi'
+ return scalar gpeffmBp=`gcmBp'
+ return scalar gpeffmBse=`segeffmB'
+ return scalar gpeffmB=`geffmB'
+
+ *ModĂšle A
+ return matrix table_mA = val_mA
+ return matrix variance_mA = var_mA
+ return matrix se_diff_mA = delta_mA_se
+ return matrix difficultiesmA = delta_mA
+
+}
+
+*Matrice dif_rc
+return matrix rcres=dif_rc
+
+forvalues j = 1/`nbitems' {
+ local colnam = "`colnam' item`j'"
+}
+
+return matrix modait= nbmod
+
+*Retour test modĂšle 1 vs modĂšle 2
+return scalar rstchi12=`rstestchi'
+return scalar rstdf12=`rstestdf'
+return scalar rstp12=`rstestp'
+
+if "`group'" != "" & "`nodif'"=="" {
+ *Retour test modĂšle A vs modĂšle B
+ return scalar diftchiAB=`diftestchi'
+ return scalar diftdfAB=`diftestdf'
+ return scalar diftpAB=`diftestp'
+}
+
+//return scalar nb_boucle_rc=`nb_step3'
+
+/*
+if "`group'" != "" & "`nodif'"==""{
+ return scalar nb_boucle_dif=`nb_stepC'
+}
+*/
+
+timer off 1
+qui timer list 1
+local temps = r(t1)
+local minute = floor(`=`temps'/60')
+local seconde = floor(`temps' - `=`minute'*60')
+//di "Time : `temps's = `minute'min `seconde's"
+*/
+
+//return scalar time = `temps'
+
+*******************************************************************************
+* New outputs
+
+if "`group'" == "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else if "`nodif'" != "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else {
+ matrix testlrm = J(2,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = mA_vs_mB m1_vs_m2
+ matrix testlrm[1,1] = (`diftestchi',`diftestdf',`diftestp')
+ matrix testlrm[2,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+
+return matrix model_4 = mod4
+return matrix model_2 = mod2
+
+end
+
diff --git a/Modules/ado/personal/r/rosali22.sthlp b/Modules/ado/personal/r/rosali22.sthlp
new file mode 100644
index 0000000..dbc1fa9
--- /dev/null
+++ b/Modules/ado/personal/r/rosali22.sthlp
@@ -0,0 +1,92 @@
+{smcl}
+{* february2019}{...}
+{hline}
+help for {hi:rosali22}{right:Myriam Blanchin - Priscilla Brisson}
+{hline}
+
+{title:Detection of Response Shift at Item-Level between 2 times}
+
+{p 8 14 2}{cmd:rosali22} {it:varlist} [{it:if}] [{it:in}] [, {cmdab:id}({it:string})
+{cmdab:moda}({it:# # [#]...}) {cmdab:group}({it:string}) {cmdab:nodif}]
+
+{p 4 4 4 140}{it:varlist} contains items' list : the first half of the items represents the items at time 1 and the second half the items at time 2. (at least 2 items).
+{break}{it:Data} : wide format, one line for one patient
+
+ {title:Description}
+
+{p 4 12 2 140}{cmd:rosali22}: {bf:R}esp{bf:O}nse {bf:S}hift {bf:AL}gorithm at {bf:I}tem-level (ROSALI),
+detection of Response-Shift between two measuring times based on partial credit model.
+Only uniform or non-uniform {bf:r}e{bf:c}alibration (RC) can be detected.
+A dichotomous group covariate can affect the estimation of the true change(group effect)
+and of response shift detected.
+Response shift can be common to both groups or differential.
+Detection of {bf:d}ifferential {bf:i}tem {bf:f}unctionning (DIF) between two groups with the option group.
+
+{p 4 12 2 140} {ye:PART 1: DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS AT FIRST TIME OF MEASUREMENT}
+{break} {it: Only with group option and without nodif option}
+{break} {ye:Model A :} Full model, transversal PCM : estimates of item difficulties free between groups, estimates of latent trait with group effect constrained to 0.
+{break} {ye:Model B :} Restricted model, transversal PCM : estimates of item difficulties with constraint of equality between groups, estimates of latent trait including group effect estimate.
+{break} .LR test between model A and model B. If this test is significant, algorithm proceeds to step C, otherwise algorithm proceeds to part 2, with constraint of equality between groups of item difficulties.
+{break} {ye:Step C :} an iterative step to detect which items have different item difficulties between groups at time 1. At each iteration, equality constraint of item difficulties between groups are relaxed one-by-one
+producing multiple models C (starting with model B). For each item, difference in item difficulties between groups is tested, a Bonferroni correction is applied. Item with the most significant test is selected and tested
+to determine if the difference in item difficulties is uniform or non-uniform (if number of answer categories is greater to 2). Model C is updated and step C is repeated to identify differences on the remaining items.
+{break} .When there is no more item with significant test or only one remaining item to be tested, ROSALI goes on part 2.
+
+{p 4 12 2 140} {ye:PART 2: DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES BETWEEN TIMES (RECALIBRATION)}
+{break} For each model, algorithm takes account detection of part 1.
+{break} {ye:Model 1 :} Full model, longitudinal PCM : estimates of item difficulties free across times for each group, estimates of latent trait with time effect and interaction time x group constrained to 0.
+{break} {ye:Model 2 :} Restricted model, longitudinal PCM : estimates of item difficulties with constraint of equality across times, estimates of latent trait including time effect and interaction time x group estimate.
+{break} .LR test between model 1 and model 2. If this test is significant, algorithm proceeds to step 3, otherwise algorithm proceeds to step 4, keeping model 2.
+{break} {ye:Step 3 :} an iterative step to detect which items have different item difficulties across times. At each iteration, equality constraint of item difficulties between times are relaxed one-by-one producing multiple
+models 3 (starting with model 2). For each item, recalibration is tested, a Bonferroni correction is applied. Item with the most significant test is selected and tested.
+{break} .If group option, item is tested to determine if the difference in item difficulties is the same for each group (common RC), in this case, model 3 is updated to take account common recalibration, or different
+(differential RC), in this case, recalibration is tested for each group with a Bonferroni correction.
+{break} .Type of recalibration : uniform or non-uniform, is finally tested (if number of answer categories is greater to 2). Model 3 is updated and step 3 is repeated to identify differences on the remaining items.
+{break} .When there is no more item with significant test or only one remaining item to be tested, ROSALI goes on part 4.
+{break} {ye:Model 4 :} Item difficulties and latent trait are estimated with a longitudinal PCM taking account difference or no between groups or times and the type uniform or non-uniform. If interaction time x group is
+not significant model 4 is updated with constraint of interaction equal to 0 and we obtained final model.
+
+{p 4 12 2 140} {cmd:automatic coding for answers categories}: Answers at items must be respect 2 conditions. If it is necessary algorithm recodes answers automatically. You can recodes answers before.
+{break} - Answers must be ordered and start with 0. If it's necesary, algorithm recodes automatically answers categories to the first answer is 0.
+{break} - It's necessary that all answers categories are used at two times of measurement (for each group if option was used).
+{break} .If the first answer is not used at one time (or in a group) at least: this answer is merged with next answer.
+{break} .If the last answer is not used at one time (or in a group) at least: this answer is merged with the previous answer.
+{break} .If an intermediate answer is not used at one time (or in one group) at least: this answer is merged with the next or previous answer of randomly way.
+{break} {it: examples :} If there is 4 answers categories, answers lightly are : 0, 1, 2 or 3.
+{break} - If answer 0 is not used at one time or for one group, answers 0 and 1 merged (patient who had answered 0 or 1 have now the answer 0, the answer 2 became answer 1 and answer 3 became answer 2)
+{break} - If answer 3 is not used at one time or for one group, answers 2 and 3 merged (patient who had answered 2 or 3 have now the answer 2, answers 0 and 1 remain the same)
+{break} - If answer 1 (resp. 2) is not used at one time or for one group, randomly answer 1 (resp. 2) merged with answer 0 (resp. 1) or with answer 2 (resp. 3).
+
+ {p 4 12 2 140} {cmd:automatic coding for groups}: Rosali needs to have one group 0 and one group 1. If it's necessary Rosali recodes group variable. You can recodes groups before.
+
+ {title:Options}
+
+{phang}{cmd:id}({it:string}) specifies the identifiant of individuals. Necessary to validate the data format.
+
+{phang}{cmd:moda}({it:# # [#]...}) specifies the number of answers categories for each item.
+
+{phang}{cmd:group}({it:string}) specifies the binary group variable, allows the detection of differential item functionning (DIF).
+
+{phang}{cmd:nodif} specifies to do only the part 2 of algorithm. No detection of DIF, only detection of response shift for each group. {it:Use only with group option.}
+
+{title:Outputs}
+
+{p 2}{bf:Matrix:}
+
+{phang}{cmd:r(test_model)}: Result of LRT between models A/B and models 1/2: chi-square, DF and p-value.
+
+{phang}{cmd:r(model_#)}: Item difficulties and latent trait of model 2 and 4 : Estimates, standard error, confidence interval at 95%, chi-square, DF and p-value.
+
+{title:Examples}
+
+{phang}{cmd: . rosali22 itemA1 itemA2 itemA3 itemB1 itemB2 itemB3, id(mat) } {it: // 3 items : A = time1 & B = time2 }
+
+{phang}{cmd: . rosali22 it1_t1-it9_t2 , id(idpat) moda(4 4 7 7 7 7 7 7 7) group(type_c) } {it: // 9 items, 4 answers for two first items and seven for others, detection by group of type_c }
+
+{title:Authors}
+
+{phang} Myriam Blanchin, Research engineer, PhD, SPHERE - UMR INSERM U1246, "methodS in Patient-centered outomes and HEalth ResEarch", University of Nantes, France {browse "mailto:myriam.blanchin@univ-nantes.fr":myriam.blanchin@univ-nantes.fr}
+{phang}Priscilla Brisson, SPHERE - UMR INSERM U1246, "methodS in Patient-centered outomes and HEalth ResEarch", University of Nantes, France
+{browse "mailto:priscilla.brisson@univ-nantes.fr":priscilla.brisson@univ-nantes.fr}
+
+
diff --git a/Modules/ado/personal/r/rosali23.ado b/Modules/ado/personal/r/rosali23.ado
new file mode 100644
index 0000000..0e4683f
--- /dev/null
+++ b/Modules/ado/personal/r/rosali23.ado
@@ -0,0 +1,3104 @@
+*! version 2.3 december2019
+*! Myriam Blanchin - Priscilla Brisson
+************************************************************************************************************
+* ROSALI: RespOnse-Shift ALgorithm at Item-level
+* Response-shift detection based on Rasch models family
+*
+* Version 1 : December 21, 2016 (Myriam Blanchin) /*rspcm122016*/
+* Version 1.1 : October 13, 2017 (Myriam Blanchin) /*option: MODA, automatic recoding of unused response categories*/
+* Version 2 : April, 2018 (Myriam Blanchin - Priscilla Brisson) /*option: GROUP, dichotomous group variable*/
+* Version 2.1 : October, 2018 (Myriam Blanchin - Priscilla Brisson) /* Version 1.1 + Version 2 */
+* Version 2.2 : February, 2019 (Priscilla Brisson) /* option nodif, optimization */
+* Version 2.3 : December, 2019 (Priscilla Brisson) /* option detail, + petites corrections */
+*
+* Myriam Blanchin, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* myriam.blanchin@univ-nantes.fr
+*
+* Priscilla Brisson, SPHERE, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* priscilla.brisson@univ-nantes.fr
+*
+* 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 rosali, rclass
+
+timer clear 1
+timer on 1
+
+syntax varlist(min=2 numeric) [if] [,GROUP(varlist) NODIF PRO DETail]
+
+preserve
+version 15
+tempfile saverspcm
+capture qui save `saverspcm',replace
+local save1=_rc
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`pro'" != "" {
+ di "START"
+}
+
+/**************************************************************************/
+set more off
+set matsize 5000
+
+local gp "`group'"
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+
+ /* VĂ©rif nb d'items pair */
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items at time 1 and the second half the items at time 2"
+ error 198
+ exit
+}
+
+local nbitems=`nbitems'/2
+
+
+if "`group'"=="" & "`nodif'"!="" {
+ di in red "nodif can only be used with the group option ({hi:nodif} option). Please correct this option."
+ error 198
+ exit
+}
+
+local nbc: word count `group'
+if `nbc' >= 2 {
+ di in red "Only one variable can be used for group option ({hi:group} option). Please correct this option."
+ error 198
+ exit
+}
+
+ /* VĂ©rif qu'il y a 2 groupes si l'option groupe est choisie */
+if "`group'"!="" {
+ qui tab `group'
+ local nbgrp = r(r)
+ if `nbgrp' != 2 {
+ di in red "The option group must be used with only 2 groups ({hi:group} option). Please correct this option."
+ error 420
+ exit
+ }
+}
+/* recoder la variable de groupe en 0, 1*/
+
+if "`group'"!="" {
+ qui tab `gp', matrow(rep)
+ qui matrix list rep
+ if rep[1,1]+rep[2,1] != 1 & rep[1,1]*rep[2,1] != 0 {
+ forvalues i=1/`=rowsof(rep)'{
+ qui replace `gp'=`i'-1 if `gp'==rep[`i',1]
+ di "WARNING : `gp' `=rep[`i',1]' is now `gp' `=`i'-1' "
+ }
+ }
+ forvalues g = 0/1 {
+ qui tab `gp' if `gp' == `g'
+ local nbp_gp`g' = r(N)
+ }
+}
+
+
+
+/*item rename*/
+/*
+Items au temps 1 : 1 Ă nbitems ``j''
+Items au temps 2 : nbitems Ă 2*nbitems ``=`j'+`nbitems'''
+
+Si t varie, puis num item : ``=(`t'-1)*`nbitems'+`j'''
+*/
+
+
+local com_z = 0 // Indicatrice de recodage
+ /*verif modalités répondues*/
+if "`gp'" == "" { // Si pas d'option groupe
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'', matrow(rect1_`j') // Récupération des infos moda du temps 1
+ local minm`j'_t1 = rect1_`j'[1,1]
+ local maxm`j'_t1 = rect1_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''', matrow(rect2_`j') // Récupération des infos moda du temps 2
+ local minm`j'_t2 = rect2_`j'[1,1]
+ local maxm`j'_t2 = rect2_`j'[r(r),1]
+
+ local minm_`j' = min(`minm`j'_t1',`minm`j'_t2') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1',`maxm`j'_t2')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j'''
+
+ if `minm_`j'' != 0 & `com_z' == 0 {
+ local com_z = 1
+ }
+
+
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`nbm_`j'' {
+ qui count if ``j'' == `m'
+ local nb_rn1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m'
+ local nb_rn2 = r(N)
+ local nb_rn = min(`nb_rn1',`nb_rn2')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' <= `minm`j'_t1' | `m' <= `minm`j'_t2' { // La moda 0 ou les moda min ne sont pas utilisées
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged "
+ local stop = 0
+ }
+ }
+ }
+ else if `m' >= `maxm`j'_t1' | `m' >= `maxm`j'_t2' | `m' == `maxm_`j'' { // La (ou les) moda max ne sont pas utilisée(s)
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems''' =`=`m'-`k'' if ``=`j'+`nbitems''' ==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k''
+ local v`k'1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k''
+ local v`k'2 = r(N)
+ if (`v`k'1' != 0 | `v`k'2' != 0) & `stop' != 0 {
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+else { // Cas oĂč l'option groupe est utilisĂ©e
+ forvalues j = 1 / `nbitems' {
+ local recoda_`j' = 0
+ qui tab ``j'' if `gp' == 0, matrow(rect1_g0_`j') matcell(nbrt1_g0_`j') // Récupération des infos moda du temps 1pour chaque groupe
+ local minm`j'_t1_g0 = rect1_g0_`j'[1,1]
+ local maxm`j'_t1_g0 = rect1_g0_`j'[r(r),1]
+
+ qui tab ``j'' if `gp' == 1, matrow(rect1_g1_`j') matcell(nbrt1_g1_`j')
+ local minm`j'_t1_g1 = rect1_g1_`j'[1,1]
+ local maxm`j'_t1_g1 = rect1_g1_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 0, matrow(rect2_g0_`j') matcell(nbrt2_g0_`j') // Récupération des infos moda du temps 2 pour chaque groupe
+ local minm`j'_t2_g0 = rect2_g0_`j'[1,1]
+ local maxm`j'_t2_g0 = rect2_g0_`j'[r(r),1]
+
+ qui tab ``=`j'+`nbitems''' if `gp' == 1 , matrow(rect2_g1_`j') matcell(nbrt2_g1_`j')
+ local minm`j'_t2_g1 = rect2_g0_`j'[1,1]
+ local maxm`j'_t2_g1 = rect2_g0_`j'[r(r),1]
+
+ local minm_`j' = min(`minm`j'_t1_g0',`minm`j'_t2_g0',`minm`j'_t1_g1',`minm`j'_t2_g1') // Info moda pour l'item j
+ local maxm_`j' = max(`maxm`j'_t1_g0',`maxm`j'_t2_g0',`maxm`j'_t1_g1',`maxm`j'_t2_g1')
+ local nbm_`j' = `=`maxm_`j''-`minm_`j''+1'
+
+ if `minm_`j'' != 0 & `com_z' == 0 {
+ local com_z = 1
+ }
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`maxm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=`r'+`minm_`j'''
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=`r'+`minm_`j'''
+ }
+
+ // Vérif. Que toutes les modas sont utilisées & concordance entre temps
+ forvalues m = 0/`=`nbm_`j''-1' {
+ qui count if ``j'' == `m' & `gp' == 0
+ local nb_rn1_g0 = r(N)
+ qui count if ``j'' == `m' & `gp' == 1
+ local nb_rn1_g1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 0
+ local nb_rn2_g0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `m' & `gp' == 1
+ local nb_rn2_g1 = r(N)
+ local nb_rn = min(`nb_rn1_g0',`nb_rn2_g0',`nb_rn1_g1',`nb_rn2_g1')
+
+ if `nb_rn' == 0 { // Une moda n'est pas utilisée
+ local recoda_`j' = 1
+ if `m' == 0 | `m' < `minm`j'_t1_g0' | `m' < `minm`j'_t2_g0' | `m' < `minm`j'_t1_g1' | `m' < `minm`j'_t2_g1' { // La moda 0 n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'+`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'+`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else if `m' == `=`nbm_`j''-1' | `m' >= `maxm`j'_t2_g0' | `m' >= `maxm`j'_t1_g1' | `m' >= `maxm`j'_t2_g1' { // La moda max n'est pas utilisée
+ local stop = 1
+ forvalues k = 1/`=`m'' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0 ) & `stop' != 0 {
+ qui replace ``j''= `=`m' - `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `=`m' - `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else { // Moda central non utilisée
+ if runiform()>0.5{ // Tirage au sort pour regrouper
+ local stop = 1
+ forvalues k = 1/`m' {
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' - `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' - `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0 {
+ qui replace ``j''= `=`m'-`k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m'-`k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'-`k'' merged"
+ local stop = 0
+ }
+ }
+ }
+ else {
+ local stop = 1
+ forvalues k = 1/`=`nbm_`j''-`m'' {
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 0
+ local v`k'1_0 = r(N)
+ qui count if ``j'' == `=`m' + `k'' & `gp' == 1
+ local v`k'1_1 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 0
+ local v`k'2_0 = r(N)
+ qui count if ``=`j'+`nbitems''' == `=`m' + `k'' & `gp' == 1
+ local v`k'2_1 = r(N)
+ if (`v`k'1_0' != 0 | `v`k'2_0' != 0 | `v`k'1_1' != 0 | `v`k'2_1' != 0) & `stop' != 0{
+ qui replace ``j''=`=`m' + `k'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''=`=`m' + `k'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `=`m'+`k'' merged"
+ local stop = 0
+ }
+ else {
+ if `stop' != 0 {
+ qui replace ``j''= `nbm_`j'' if ``j''==`m'
+ qui replace ``=`j'+`nbitems'''= `nbm_`j'' if ``=`j'+`nbitems'''==`m'
+ di "WARNING: items ``j'' & ``=`j'+`nbitems''': answers `m' and `nbm_`j'' merged"
+ local stop = 0
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+if `com_z' == 1 {
+ di
+ di "WARNING : Automatic recoding, the first response category is 0. see {help rosali22:help rosali22}."
+ di
+}
+
+forvalues j =1/`nbitems' {
+ qui tab ``j'', matrow(rec) // Récupération des infos moda du temps 1
+ local nbm`j'_t1 = r(r)
+
+ qui tab ``=`j'+`nbitems''' // Récupération des infos moda du temps 2
+ local nbm`j'_t2 = r(r)
+
+ local nbm_`j' = max(`nbm`j'_t1', `nbm`j'_t2')
+ //Recodage des réponses en 0, 1, 2, etc...
+ forvalues r = 0/`=`nbm_`j''-1' {
+ qui replace ``j'' = `r' if ``j'' == `=rec[`=`r'+1',1]'
+ qui replace ``=`j'+`nbitems''' = `r' if ``=`j'+`nbitems''' == `=rec[`=`r'+1',1]'
+ }
+}
+
+/* Calcul de nbmoda & nbdif */
+forvalues j = 1/`nbitems' {
+ qui tab ``j''
+ local nbmoda_`j' = r(r)
+ local nbdif_`j' = r(r) - 1
+}
+
+local maxdif = 0
+local nbmoda_sum = 0
+forvalues j = 1/`nbitems' {
+ if `maxdif' < `nbdif_`j'' {
+ local maxdif = `nbdif_`j''
+ }
+ local nbmoda_sum = `nbmoda_sum' + `nbdif_`j''
+}
+
+/* Au moins 2 mmoda par item */
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' == 1 {
+ di in red "``j'' have only one response category, each item need at least 2 response categories"
+ error 198
+ exit
+ }
+}
+
+local coln ""
+forvalues j =1 /`nbitems' {
+ local coln "`coln' ``j''"
+}
+
+matrix nbmod = J(2,`nbitems',.)
+
+matrix colnames nbmod = `coln'
+matrix rownames nbmod = NbModa Recoding
+
+forvalues j = 1/`nbitems' {
+ matrix nbmod[1,`j'] = `nbmoda_`j''
+ matrix nbmod[2,`j'] = `recoda_`j''
+}
+
+*Erreur si plus de 200 difficultés
+local nb_test = 0
+forvalues j=1/`nbitems' {
+ local nb_test = `nb_test'+`nbmoda_`j'' -1
+}
+
+if `nb_test' >= 200 {
+ di in red "The number of items difficulties must be less than 200 ({hi:moda} option option). Please correct this option."
+ error 198
+ exit
+}
+
+local nbitp = 0
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ local nbitp = `nbitp' + 1
+ }
+}
+
+qui count
+local nbpat = r(N)
+
+
+/*********************************
+* AFFICHAGE INITIAL
+*********************************/
+di _col(5) "{hline 78}"
+di _col(5) in ye %~30s "Time 1" _col(30) %~30s "Time 2" _col(55) "Nb of Answer Cat."
+di _col(5) "{hline 78}"
+forvalues j=1/`nbitems' {
+ di in gr _col(5) %~30s abbrev("``j''",20) _col(30) %~30s abbrev("``=`j'+`nbitems'''",20) _col(75) `nbmoda_`j''
+}
+di _col(5) "{hline 78}"
+if "`group'" != "" {
+ di _col(10) "Nb. of patients : " abbrev("`gp'",20) " 0 = `nbp_gp0' ;", abbrev("`gp'",20) " 1 = `nbp_gp1'"
+ di _col(5) "{hline 78}"
+}
+else {
+ di _col(20) "Nb. of patients : `nbpat'"
+ di _col(5) "{hline 78}"
+}
+di
+if `nbitems' == 1 {
+ di in red "2 items at least is necessary to detect DIF and/or RC at item level."
+ error 198
+ exit
+}
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' == 2 {
+ di "WARNING: ``j'' have only 2 response categories, the type uniform or non-uniform can't be detected."
+ }
+ if `nbmoda_`j'' == 1 {
+ di in red "``j'' uses only `nbmoda_`j'' response category, each item need at least 2 response categories used."
+ error 198
+ exit
+ }
+ if `nbmoda_`j'' == 0 {
+ di in red "``j'' uses no response category, each item needs at least 2 response categories used."
+ error 198
+ exit
+ }
+}
+di
+if "`group'" != "" {
+ di _col(2) in ye "For all models : - mean of latent trait of `gp' 0 at time 1 is constrained at 0"
+ di _col(19) "- Equality of variances between groups"
+ di
+}
+else {
+ di _col(2) in ye "For all models : mean of latent trait at time 1 is constrained at 0"
+ di
+}
+
+
+
+/*********************************
+* DEFINITION DES CONTRAINTES
+*********************************/
+
+if "`group'"!="" { // Contraintes si option groupe
+ *EGALITE ENTRE GROUPES A T1 (1-200)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=0+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``j'']1.`gp'
+ }
+ }
+
+ *DIF UNIFORME A T1 (201-400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=200+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'-[`p'.``j'']0bn.`gp'=`p'*[1.``j'']1.`gp'-`p'*[1.``j'']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 0 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp'
+ }
+ }
+
+ *EGALITES ENTRE T1 et T2, groupe 1 (601-800)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=600+`maxdif'*(`j'-1)+`p'' [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'
+ }
+ }
+
+ * RC COMMUNE (801-1000)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=800+`maxdif'*(`j'-1)+`p'' [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 0 (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'
+ }
+ }
+
+ * RC UNIFORME, groupe 1 (1201-1400)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1200+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp'
+ }
+ }
+
+ *Sans interaction temps x groupe
+ constraint 1999 [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'=[/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+}
+else { //Contraintes si pas d'option groupe
+ *EGALITE ENTRE T1 et T2 (401-600)
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ constraint `=400+`maxdif'*(`j'-1)+`p'' [`p'.``j'']:_cons = [`p'.``=`j'+`nbitems''']:_cons
+ }
+ }
+ *RC UNIFORME (1001-1200)
+ forvalues j=1/`nbitems'{
+ forvalues p=2/`nbdif_`j''{
+ constraint `=1000+`maxdif'*(`j'-1)+`p'' `p'*([1.``=`j'+`nbitems''']:_cons - [1.``j'']:_cons)=[`p'.``=`j'+`nbitems''']:_cons -[`p'.``j'']:_cons
+ }
+ }
+}
+
+/*********************************
+* MATRICE DES RESULTATS
+*********************************/
+matrix dif_rc=J(`nbitems',8,.)
+matrix colnames dif_rc=DIFT1 DIFU RC RC_DIF RCG0 RCUG0 RCG1 RCUG1
+local rown ""
+
+forvalues j =1 /`nbitems' {
+ local rown "`rown' ``j''"
+}
+matrix rownames dif_rc = `rown'
+
+*Nb modalité max
+local nbdif_max = 0
+forvalues j=1/`nbitems' {
+ if `nbdif_max' < `nbdif_`j'' {
+ local nbdif_max = `nbdif_`j''
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 1 : DIF A T1 ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+
+if "`group'"!="" & "`nodif'"=="" { // PARTIE 1 = Slmt si option group & pas de "nodif"
+ if "`detail'" != "" {
+ di _dup(59) "_ "
+ di
+ di _col(5) in ye "PART 1: DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS AT FIRST TIME OF MEASUREMENT"
+ }
+
+ *********************************
+ ** MODEL B **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading cons) var(0: THETA@v) var(1:THETA@v) latent(THETA) nocapslatent
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifB
+ matrix val_mB = r(table)
+ matrix esti_B = e(b)
+
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mB=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+
+ matrix colnames delta_mB = `name_partOneC'
+ matrix rownames delta_mB = `name_partOneL'
+ matrix delta_mB_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mB_se = `name_partOneC_se'
+ matrix rownames delta_mB_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB=r(estimate)
+ local delta`j'_`p'g`g'mB_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mB = r(estimate)
+ local delta`j'_`p'g`g'mB_se = r(se)
+ }
+ matrix delta_mB[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB'
+ matrix delta_mB_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mB_se'
+ }
+ }
+ }
+
+ matrix var_mB = (val_mB[1,"/var(THETA)#0bn.`gp'"]\val_mB[2,"/var(THETA)#0bn.`gp'"])
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmB=r(estimate)
+ local segeffmB=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmBp=r(p)
+ local gcmBchi=r(chi2)
+ local gcmBdf=r(df)
+
+
+ *********************************
+ ** MODEL A **
+ *********************************
+
+ local model ""
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading means) var(0: THETA@v) var(1:THETA@v) from(esti_B, skip) latent(THETA) nocapslatent
+
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifA
+ matrix val_mA = r(table)
+ matrix esti_A = e(b)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mA=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mA = `name_partOneC'
+ matrix rownames delta_mA = `name_partOneL'
+ matrix delta_mA_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+
+ matrix colnames delta_mA_se = `name_partOneC_se'
+ matrix rownames delta_mA_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA=r(estimate)
+ local delta`j'_`p'g`g'mA_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mA = r(estimate)
+ local delta`j'_`p'g`g'mA_se = r(se)
+ }
+ matrix delta_mA[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA'
+ matrix delta_mA_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mA_se'
+ }
+ }
+ }
+ //Variance et se mA
+ matrix var_mA = (val_mA[1,"/var(THETA)#0bn.`gp'"]\val_mA[2,"/var(THETA)#0bn.`gp'"])
+
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+
+ if "`detail'" != "" {
+ //Affichage modĂšle A
+ di
+ di in ye "PROCESSING STEP A"
+ di
+
+
+ /* Affichage des estimations des difficultés modÚle A */
+
+ di _col(5) in ye "{ul:MODEL A:} No group effect: mean of latent trait of group 1 = mean of latent trait of group 0,"
+ di _col(7) in ye "all item difficulties are freely estimated in both groups"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 70}"
+ di _col(30) in ye abbrev("`gp'",20) "=0" _col(60) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 70}"
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ di in gr _col(10) "`p'" _col(30) %6.2f `delta`j'_`p'g0mA' %6.2f " (" %3.2f `delta`j'_`p'g0mA_se' ")" _col(60) %6.2f `delta`j'_`p'g1mA' " (" %3.2f `delta`j'_`p'g1mA_se' ")"
+ }
+ }
+ di _col(10) "{hline 70}"
+ /* Affichage des estimations sur le trait latent du modĂšle A */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ di _col(10) "{hline 65}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error"
+ di _col(10) "{hline 65}"
+ di _col(10) in ye "Variance" in gr _col(45) %6.2f `=var_mA[1,1]' _col(62) %6.2f `=var_mA[2,1]'
+ di _col(10) in ye "Group effect (mean gp 1)" in gr _col(44) %6.2f "0 (constrained)"
+ di _col(10) "{hline 65}"
+
+ //*Affichage modĂšle B
+
+ di
+ di in ye "PROCESSING STEP B"
+ di
+
+ /* Affichage des estimations des difficultés modÚle B */
+
+ di _col(5) in ye "{ul:MODEL B:} Group effect estimated: mean of latent trait of group 1 free estimated,"
+ di _col(7) in ye "Same item difficulties estimated between groups"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 70}"
+ di _col(30) in ye abbrev("`gp'",20) "=0" _col(60) abbrev("`gp'",20) "=1"
+ di _col(10) "{hline 70}"
+
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ di in gr _col(10) "`p'" _col(30) %6.2f `delta`j'_`p'g0mB' " (" %3.2f `delta`j'_`p'g0mB_se' ")" _col(60) %6.2f `delta`j'_`p'g1mB' " (" %3.2f `delta`j'_`p'g1mB_se' ")"
+ }
+ }
+
+ di _col(10) "{hline 70}"
+ /* Affichage des estimations sur le trait latent du modĂšle B */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+ di _col(10) in ye "Variance" in gr _col(44) %6.2f `=var_mB[1,1]' _col(62) %6.2f `=var_mB[2,1]'
+ di _col(10) in ye "Group effect (mean gp 1)" in gr _col(44) %6.2f `geffmB' _col(62) %6.2f `segeffmB' _col(77) %6.4f `gcmBp'
+ di _col(10) "{hline 80}"
+ di
+ }
+
+ *****************************************************
+ * ModĂšle A vs ModĂšle B *
+ *****************************************************
+
+ qui lrtest modeldifA modeldifB
+ local diftestp=r(p)
+ local diftestchi=r(chi2)
+ local diftestdf=r(df)
+ if "`detail'" != "" {
+ //affichage lrtest
+ di _col(10) in ye "LIKELIHOOD-RATIO TEST MODEL A VS MODEL B : "
+ di _col(10) "{hline 50}"
+ di _col(10) in ye "Chi-square" _col(30) "DF" _col(50) "P-value"
+ di _col(10) in gr %6.2f `diftestchi' _col(30) %2.0f `diftestdf' _col(50) %6.4f `diftestp'
+ di _col(10) "{hline 50}"
+
+ if `diftestp'<0.05{
+ di _col(10) in ye "DIFFERENCE IN ITEM DIFFICULTIES BETWEEN GROUPS LIKELY"
+ }
+ else{
+ di _col(10) in ye "NO DIFFERENCE BETWEEN GROUPS DETECTED"
+ }
+ }
+
+ *********************************
+ *************MODEL C*************
+ *********************************
+ // Etape itérative si lrtest significatif
+ local nb_stepC = 0
+
+ if `diftestp'<0.05{ /*If pvalue(LRtest)<0.05 then step C*/
+ if "`detail'" {
+ di
+ di in ye "PROCESSING STEP C"
+ di
+ }
+ /*test DIF pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ while `boucle'<=`=`nbitp'-1' & `stop'==0{ /*on s'arrĂȘte quand on a libĂ©rĂ© du DIF sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_stepC = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle''
+ /*réinitialisation de la matrice de test*/
+ matrix test_difu_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_difu_`boucle'=chi_DIFU df_DIFU pvalueDIFU
+ matrix test_dif_`boucle'=J(`nbitems',3,.)
+ matrix colnames test_dif_`boucle'=chi_DIF df_DIF pvalueDIF
+ local nbsig=0
+ local minpval=1
+ local itemdif=0
+ if "`detail'" {
+ di _col(10) "{hline 70}"
+ di _col(10) in ye "Loop `boucle'" _col(50) "Adjusted alpha: " %6.4f `pajust'
+ di
+ di in ye _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-Value"
+ }
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ //if `nbdif_`j'' > 2 {
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF déjà détecté sur l'item j*/
+ /*on libĂšre le DIF de l'item i: pas de contraintes*/
+ forvalues k=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if `k'!=`j' & `nbmoda_`j'' >= 2 {
+ if dif_rc[`k',1]==. | dif_rc[`k',1]==0 {/*pas de DIF sur item k: contraintes 1-200*/
+ forvalues p=1/`nbdif_`k''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!= 0 & `nbmoda_`k'' > 2 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`k''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B) latent(THETA) nocapslatent
+ estimates store modeldif3b`boucle'it`i'
+
+ *************************
+ *****test DIF item i*****
+ *************************
+ qui test [1.``j'']1.`gp'=[1.``j'']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``j'']0bn.`gp', acc
+ }
+ }
+ matrix test_dif_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+ /* Test DIF Uniforme */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``j'']1.`gp'-[1.``j'']0bn.`gp')=[2.``j'']1.`gp'-[2.``j'']0bn.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``j'']1.`gp'-[1.``j'']0bn.`gp')=[`p'.``j'']1.`gp'-[`p'.``j'']0bn.`gp', acc
+ }
+ matrix test_difu_`boucle'[`j',1]=(r(chi2), r(df), r(p))
+ }
+
+ if test_dif_`boucle'[`j',3]<`pajust'{/*si DIF sur item i*/
+ local ++nbsig
+ if test_dif_`boucle'[`j',3]<`minpval'{
+ local minpval=test_dif_`boucle'[`j',2]
+ local itemdif=`j'
+ }
+ }
+ if "`detail'" != "" {
+ di in ye _col(12) %-30s abbrev("``j'' :",22) in gr _col(40) %6.3f test_dif_`boucle'[`j',1] _col(55) test_dif_`boucle'[`j',2] _col(60) %6.4f test_dif_`boucle'[`j',3]
+ }
+ }
+ }
+ /*si nb de tests significatifs=0, on arrĂȘte*/
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ if "`detail'" != "" {
+ di
+ di _col(20) in ye ">>> No significant test: no difference between groups detected, no DIF detected"
+ di _col(10) "{hline 70}"
+ }
+ }
+ else {
+ if "`detail'" != ""{
+ di
+ di _col(20) in ye ">>> No other significant tests"
+ di _col(10) "{hline 70}"
+ }
+ }
+ }
+ else{/*si nb de tests significatifs>0, mise à jour de la matrice de résultats*/
+ matrix dif_rc[`itemdif',1]=`boucle'
+ if "`detail'" != ""{
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Difference between groups on ``itemdif'' at time 1"
+ }
+ if `nbmoda_`itemdif'' > 2 {
+ if "`detail'" != "" {
+ di
+ di _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Uniform ? " in gr _col(40) %4.2f `=test_difu_`boucle'[`itemdif',1]' _col(55) `=test_difu_`boucle'[`itemdif',2]' _col(60) %4.2f `=test_difu_`boucle'[`itemdif',3]'
+ }
+ if test_difu_`boucle'[`itemdif',3]<0.05{ /*DIF NU détectée*/
+ matrix dif_rc[`itemdif',2]=0
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye " >>> ``itemdif'' : Non-uniform differences of item difficulties between groups at T1"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else{/*DIF U détectée*/
+ matrix dif_rc[`itemdif',2]=`boucle'
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye ">>> ``itemdif'' : Uniform differences of item difficulties between groups at T1"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ }
+ else {
+ // Différence entre groupes au temps 1 mais slmt 2 moda. donc pas de U ou NU
+ di _col(15) _dup(60) "-"
+ }
+ }
+ local ++boucle
+ }
+ }
+
+ /* MODELE FINAL DE LA PARTIE 1. Si DIFT1 détecté (=Au moins 2 boucles dans l'étape C)*/
+ if `nb_stepC' > 1 {
+ forvalues j=1/`nbitems'{
+ local model ""
+ local listconst ""
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { /*DIF U: contraintes 201-400*/
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA@`p')"
+ }
+ }
+
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) var(0: THETA@v) var(1:THETA@v) constraint(`listconst') from(esti_B) latent(THETA) nocapslatent
+ /* Stockage des estimations du modĂšle */
+ estimates store modeldifCFin
+ matrix val_mC = r(table)
+
+ /* Calcul des difficultés d'item (delta_j) */
+ matrix delta_mCFin=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC ""
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC "`name_partOneC' delta_`p'_gp`g'"
+ }
+ }
+ local name_partOneL ""
+ forvalues j=1/`nbitems' {
+ local name_partOneL "`name_partOneL' ``j''"
+ }
+ matrix colnames delta_mCFin = `name_partOneC'
+ matrix rownames delta_mCFin = `name_partOneL'
+
+ matrix delta_mCFin_se=J(`nbitems',`=`nbdif_max'*2',.)
+ local name_partOneC_se ""
+
+ forvalues p=1/`nbdif_max' {
+ forvalues g=0/1 {
+ local name_partOneC_se "`name_partOneC_se' delta_`p'_gp`g'_se"
+ }
+ }
+ matrix colnames delta_mCFin_se = `name_partOneC_se'
+ matrix rownames delta_mCFin_se = `name_partOneL'
+
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin=r(estimate)
+ local delta`j'_`p'g`g'mCFin_se=r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``j'']:`g'.`gp' - [`p'.``j'']:`g'.`gp'
+ local delta`j'_`p'g`g'mCFin = r(estimate)
+ local delta`j'_`p'g`g'mCFin_se = r(se)
+ }
+ matrix delta_mCFin[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin'
+ matrix delta_mCFin_se[`j',`=2*`p'-1+`g'']=`delta`j'_`p'g`g'mCFin_se'
+ }
+ }
+ }
+ if "`group'" != "" { //Variance et se mA
+ matrix var_mC = (val_mC[1,"/var(THETA)#0bn.`gp'"]\val_mC[2,"/var(THETA)#0bn.`gp'"])
+ }
+ /*group effect*/
+ qui lincom [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'
+ local geffmCFin=r(estimate)
+ local segeffmCFin=r(se)
+ qui test [/]:mean(THETA)#1.`gp'-[/]:mean(THETA)#0bn.`gp'=0
+ local gcmCFinp=r(p)
+ local gcmCFinchi=r(chi2)
+ local gcmCFindf=r(df)
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+//////// PARTIE 2 : RECALIBRATION ? ////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+if "`detail'" != "" {
+ di
+ di _dup(59) "_ "
+ di
+ if "`group'" != "" {
+ di in ye "PART 2 : DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES (RECALIBRATION)"
+ }
+ else {
+ di in ye "DETECTION OF DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES (RECALIBRATION)"
+ }
+}
+ *********************************
+ ** MODEL 2 **
+ *********************************
+
+local listconst "" // liste des contraintes si option groupe
+local listconst_g "" //LIste des contraintes sans option groupe (Notation peu logique !!)
+
+forvalues j=1/`nbitems'{
+ if "`group'" == "" { // Contraintes pas de RC pour tous les items
+ forvalues p=1/`nbdif_`j''{
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF Ă T1 sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 200*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 0 (401-600)*/
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ forvalues p=1/`nbdif_`j''{ /* egalites entre temps : groupe 1 (601-800)*/
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+}
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+di "gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') latent(THETA1 THETA2) nocapslatent"
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') latent(THETA1 THETA2) nocapslatent
+}
+
+/*Stockage des données du modÚle 2 */
+estimates store model2
+matrix val_m2 = r(table)
+matrix esti_2 = e(b)
+
+if "`group'" != "" {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)#0bn.`gp'"],val_m2[1,"/var(THETA2)#0bn.`gp'"]\val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m2[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m2[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m2 = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"]\val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix covar_m2 = (val_m2[1,"/cov(THETA1,THETA2)"]\val_m2[2,"/cov(THETA1,THETA2)"]\val_m2[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm2=r(estimate)
+ local segeffm2=r(se)
+ local ubgeffm2 = r(ub)
+ local lbgeffm2 = r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm2p=r(p)
+ local gpm2chi=r(chi2)
+ local gpm2df=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* [/]:mean(THETA1)*/
+ local teffm2=r(estimate)
+ local seteffm2=r(se)
+ local ubteffm2 = r(ub)
+ local lbteffm2 = r(lb)
+ qui test [/]:mean(THETA2) = 0 /* [/]:mean(THETA1)*/
+ local tm2p=r(p)
+ local tm2chi=r(chi2)
+ local tm2df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ local interm2=r(estimate)
+ local seinterm2=r(se)
+ local ubinterm2 = r(ub)
+ local lbinterm2 = r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ local interm2p=r(p)
+ local interm2chi=r(chi2)
+ local interm2df=r(df)
+}
+
+if "`group'" != "" {
+ matrix mod2 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod2 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod2 = `name_partTwoC'
+ matrix rownames mod2 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2= r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se= r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm2=r(estimate)
+ local delta`t'_`j'_`p'g`g'm2_se=r(se)
+ local delta`t'_`j'_`p'g`g'm2_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm2_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2'
+ matrix mod2[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_se'
+ matrix mod2[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_ub'
+ matrix mod2[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_lb'
+ matrix mod2[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm2_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2= r(estimate)
+ local delta`t'_`j'_`p'g0m2_se= r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m2=r(estimate)
+ local delta`t'_`j'_`p'g0m2_se=r(se)
+ local delta`t'_`j'_`p'g0m2_ub=r(ub)
+ local delta`t'_`j'_`p'g0m2_lb=r(lb)
+ local delta`t'_`j'_`p'g0m2_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ if `t' == 2 {
+ matrix mod2[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2'
+ matrix mod2[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_se'
+ matrix mod2[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_ub'
+ matrix mod2[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_lb'
+ matrix mod2[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m2_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod2[1,`=4*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)#0bn.`gp'"], val_m2[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)#0bn.`gp'"],val_m2[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)#0bn.`gp'"],val_m2[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)#0bn.`gp'"],val_m2[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm2p'
+
+ matrix mod2[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2'
+ matrix mod2[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = `seinterm2'
+ matrix mod2[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm2'
+ matrix mod2[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm2'
+ matrix mod2[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2chi'
+ matrix mod2[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2df'
+ matrix mod2[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = `interm2p'
+}
+else {
+ matrix mod2[1,`=2*`nbmoda_sum'+1'] = (val_m2[1,"/var(THETA1)"],val_m2[1,"/var(THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+1'] = (val_m2[2,"/var(THETA1)"],val_m2[2,"/var(THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+1'] = (val_m2[6,"/var(THETA1)"],val_m2[6,"/var(THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+1'] = (val_m2[5,"/var(THETA1)"],val_m2[5,"/var(THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1'] = (val_m2[1,"/cov(THETA1,THETA2)"])
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1'] = (val_m2[2,"/cov(THETA1,THETA2)"])
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1'] = (val_m2[6,"/cov(THETA1,THETA2)"])
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1'] = (val_m2[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod2[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm2'
+ matrix mod2[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm2'
+ matrix mod2[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm2'
+ matrix mod2[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm2'
+ matrix mod2[5,`=2*`nbmoda_sum'+2+1+1'] = `tm2chi'
+ matrix mod2[6,`=2*`nbmoda_sum'+2+1+1'] = `tm2df'
+ matrix mod2[7,`=2*`nbmoda_sum'+2+1+1'] = `tm2p'
+}
+
+ *********************************
+ ** MODEL 1 **
+ *********************************
+
+
+/*PCM longitudinal, no true change, group effect, interaction*/
+local listconst ""
+forvalues j=1/`nbitems'{ /*contraintes pour les autres items (si DIF NU sur item k, pas de contraintes*/
+ if dif_rc[`j',1]==. | dif_rc[`j',1]==0 {/*pas de DIF sur item k: contraintes 1*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else{
+ if `nbdif_`j'' > 1 {
+ if dif_rc[`j',2]!=. & dif_rc[`j',2] != 0 { /*diff T1 U: contraintes 201*/
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+}
+
+
+local model ""
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ local model "`model' (`p'.``j''<-THETA1@`p')(`p'.``=`j'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'"!="" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@0) means(1: THETA1@m1 THETA2@m1) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@0) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+
+/* Stockage des estimations du modĂšle 1 */
+estimates store model1
+matrix val_m1 = r(table)
+
+/* Calcul des difficultés d'item (delta_j) */
+matrix delta_m1 = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC ""
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' delta_t`t'_`p'_gp`g'"
+ }
+ }
+}
+
+local name_partTwoL ""
+forvalues j=1/`=`nbitems'*2' {
+ if `j' <= `nbitems' {
+ local name_partTwoL "`name_partTwoL' ``j''"
+ }
+ else {
+ local name_partTwoL "`name_partTwoL' ``=`nbitems'+`j'''"
+ }
+}
+
+matrix colnames delta_m1 = `name_partTwoC'
+matrix rownames delta_m1 = `name_partTwoL'
+
+matrix delta_m1_se = J(`nbitems',`=`nbdif_max'*4',.)
+local name_partTwoC_se ""
+
+forvalues p=1/`nbdif_max' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC_se "`name_partTwoC_se' delta_t`t'_`p'_gp`g'_se"
+ }
+ }
+}
+
+matrix colnames delta_m1_se = `name_partTwoC_se'
+matrix rownames delta_m1_se = `name_partTwoL'
+
+if "`group'"!="" {
+ forvalues t=1/2{
+ forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues g=0/1{
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1= r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm1=r(estimate)
+ local delta`t'_`j'_`p'g`g'm1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`g'+`t'']=`delta`t'_`j'_`p'g`g'm1_se'
+ }
+ }
+ }
+ }
+ }
+}
+else {
+ forvalues t=1/2 {
+ forvalues j=1/`nbitems' {
+ forvalues p = 1/`nbdif_`j'' {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1= r(estimate)
+ local delta`t'_`j'_`p'g0m1_se= r(se)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']:_cons
+ local delta`t'_`j'_`p'g0m1=r(estimate)
+ local delta`t'_`j'_`p'g0m1_se=r(se)
+ }
+ if `t' == 1 {
+ matrix delta_m1[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ if `t' == 2 {
+ matrix delta_m1[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1'
+ matrix delta_m1_se[`j',`=4*(`p'-1)+1+`t'']=`delta`t'_`j'_`p'g0m1_se'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)#0bn.`gp'"],val_m1[1,"/var(THETA2)#0bn.`gp'"]\val_m1[2,"/var(THETA1)#0bn.`gp'"],val_m1[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m1[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m1[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m1 = (val_m1[1,"/var(THETA1)"],val_m1[1,"/var(THETA2)"]\val_m1[2,"/var(THETA1)"],val_m1[2,"/var(THETA2)"])
+ matrix covar_m1 = (val_m1[1,"/cov(THETA1,THETA2)"]\val_m1[2,"/cov(THETA1,THETA2)"]\val_m1[4,"/cov(THETA1,THETA2)"])
+}
+
+/*group effect*/
+if "`group'"!="" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm1=r(estimate)
+ local segeffm1=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ local gpm1p=r(p)
+ local gpm1chi=r(chi2)
+ local gpm1df=r(df)
+}
+
+ *************************************************************
+ ***********************AFFICHAGE*****************************
+ *************************************************************
+if "`detail'" != "" {
+ // Affichage du modĂšle 1
+ di
+ di in ye "PROCESSING STEP 1"
+ di
+ /* Affichage des estimations des difficultés */
+
+ if "`group'" != "" {
+ di _col(5) in ye "{ul:MODEL 1:} Group effect estimated, no time effect (mean of latent trait of group 0 at T2) equal to mean of group 0 at T1),"
+ di _col(7) in ye "all item difficulties are freely estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di _col(5) in ye "{ul:MODEL 1}: no time effect,"
+ di _col(7) in ye "all item difficulties are freely estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+ }
+
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m1' " (" %4.2f `delta1_`j'_`p'g1m1_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m1' " (" %4.2f `delta2_`j'_`p'g1m1_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m1' " (" %4.2f `delta1_`j'_`p'g0m1_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m1' " (" %4.2f `delta2_`j'_`p'g0m1_se' ")"
+ }
+ }
+ }
+ if "`group'" != "" {
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di _col(10) "{hline 50}"
+ }
+ /* Affichage des estimations du trait latent du modĂšle 1 */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ if "`group'" != "" {
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+ }
+ else {
+ di _col(10) "{hline 70}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" "
+ di _col(10) "{hline 70}"
+ }
+ di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=var_m1[1,1]' _col(62) %6.2f `=var_m1[2,1]'
+ di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=var_m1[1,2]' _col(62) %6.2f `=var_m1[2,2]'
+ di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=covar_m1[1,1]' _col(62) %6.2f `=covar_m1[2,1]'
+ if "`group'" != "" {
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm1' _col(62) %6.2f `segeffm1' _col(77) %6.4f `gpm1p'
+ }
+ di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) "0 (constrained)"
+ if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) "0 (constrained)"
+ }
+ if "`group'" != "" {
+ di _col(10) "{hline 80}"
+ }
+ else {
+ di _col(10) "{hline 70}"
+ }
+ //Affichage du modĂšle 2
+ di
+ di in ye "PROCESSING STEP 2"
+ di
+ /* Affichage des estimations des difficultés */
+
+ if "`group'" != "" {
+ di _col(5) in ye "{ul:MODEL 2:} Group effect, time effect (mean of latent trait of group 0 at T2) free estimated, time x group interaction estimated,"
+ di _col(7) in ye "Same item difficulties estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di _col(5) in ye "{ul:MODEL 2}: time effect estimated (mean of latent trait group 0 at T2) free estimated,"
+ di _col(7) in ye "Same item difficulties estimated across times"
+ di
+ di _col(10) in ye "Item difficulties estimates (s.e.)"
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+ }
+
+ forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m2' " (" %4.2f `delta1_`j'_`p'g1m2_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m2' " (" %4.2f `delta2_`j'_`p'g1m2_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m2' " (" %4.2f `delta1_`j'_`p'g0m2_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m2' " (" %4.2f `delta2_`j'_`p'g0m2_se' ")"
+ }
+ }
+ }
+ if "`group'" != "" {
+ di _col(10) "{hline 85}"
+ }
+ else {
+ di _col(10) "{hline 50}"
+ }
+ /* Affichage des estimations du trait latent du modĂšle 2 */
+ di
+ di _col(10) in ye "Latent trait distribution estimates"
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+
+ if "`group'" == "" {
+ local fact_k = 2
+ }
+ else {
+ local fact_k = 4
+ }
+
+ di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+1']' _col(62) %6.2f =mod2[2,`=`fact_k'*`nbmoda_sum'+1']
+ di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+2']' _col(62) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+2']'
+ di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=mod2[1,`=`fact_k'*`nbmoda_sum'+3']' _col(62) %6.2f `=mod2[2,`=`fact_k'*`nbmoda_sum'+3']'
+
+ if "`group'" != "" {
+
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm2' _col(62) %6.2f `segeffm2' _col(77) %6.4f `gpm2p'
+ }
+ di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f `teffm2' _col(62) %6.2f `seteffm2' _col(77) %6.4f `tm2p'
+
+ if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f `interm2' _col(62) %6.2f `seinterm2' _col(77) %6.4f `interm2p'
+ }
+ di _col(10) "{hline 80}"
+ di
+}
+ *****************************************************
+ * ModĂšle 1 vs ModĂšle 2 *
+ *****************************************************
+qui lrtest model2 model1
+
+local rstestp=r(p)
+local rstestchi=r(chi2)
+local rstestdf=r(df)
+if "`detail'" != "" {
+ di _col(10) in ye "LIKELIHOOD-RATIO TEST MODEL 1 VS MODEL 2"
+ di _col(10) "{hline 50}"
+ di _col(10) in ye "Chi-square" _col(30) "DF" _col(50) "P-value"
+ di _col(10) in gr %6.2f `rstestchi' _col(30) %2.0f `rstestdf' _col(50) %6.4f `rstestp'
+ di _col(10) "{hline 50}"
+ if `rstestp'<0.05{
+ di _col(10) in ye "DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES LIKELY"
+ }
+ else{
+ di _col(10) in ye "NO DIFFERENCE IN ITEM DIFFICULTIES ACROSS TIMES DETECTED, NO RECALIBRATION DETECTED"
+ }
+}
+ *********************************
+ *************MODEL 3*************
+ *********************************
+// Etape itérative si lrtest significatif
+local nb_step3=0
+
+if `rstestp' < 0.05 { /* If pvalue(LRtest)<0.05 then step 3 */
+ if "`detail'" != "" {
+ di
+ di in ye "PROCESSING STEP 3"
+ di
+ }
+ /*test RC pour chaque item*/
+ local boucle = 1
+ local stop = 0
+ //matrix list dif_rc
+ while `boucle' <= `=`nbitp'-1' & `stop' == 0 { /*on s'arrĂȘte quand on a libĂ©rĂ© du RC sur (tous les items-1) ou lorsqu'il n'y a plus de tests significatifs*/
+ local nb_step3 = `boucle'
+ local pajust=0.05/`=`nbitp'+1-`boucle'' // local pajust=0.05/`=`nbitems'+1-`boucle'
+ if "`group'" != "" {
+ local pajust2 = 0.05/`nbgrp'
+ }
+ /*réinitialisation de la matrice de test*/
+ matrix test_rc_`boucle'=J(`nbitems',9,.)
+ matrix test_rcCOMM_`boucle'=J(`nbitems',3,.)
+ matrix test_rcU_`boucle'=J(`nbitems',6,.)
+ matrix colnames test_rc_`boucle'= chi_RC df_RC pvalue_RC chi_RCg0 df_RCg0 pvalue_RCg0 chi_RCg1 df_RCg1 pvalue_RCg1
+ matrix colnames test_rcCOMM_`boucle'= chi_RCCOMM df_RCCOMM pvalue_RCCOMM
+ matrix colnames test_rcU_`boucle'= chi_RCUg0 df_RCUg0 pvalue_RCUg0 chi_RCUg1 df_RCUg1 pvalue_RCUg1
+ local nbsig=0
+ local minpval=1
+ local itemrc=0
+ if "`detail'" != "" {
+ di _col(10) "{hline 70}"
+ di _col(10) in ye "Loop `boucle'" _col(50) "Adjusted alpha : " %6.4f `pajust'
+ di
+ di in ye _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-Value"
+ }
+
+
+ /*boucle de test*/
+ forvalues j=1/`nbitems'{
+ if `nbdif_`j'' >= 1 {
+ local model ""
+ local listconst ""
+ local listconst_g ""
+ if dif_rc[`j',3]==. { /*si pas de RC déjà détecté sur l'item j -> test item j*/
+ /*on libĂšre la RC de l'item j: pas de contraintes*/
+ forvalues k=1/`nbitems'{
+ if "`group'" == "" {
+ if `k'!=`j'{
+ if dif_rc[`k',3]==. | dif_rc[`k',3]==0 {/*pas de RC sur item k: contraintes 401-600*/
+ forvalues p=1/`nbdif_`k''{
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`k'-1)+`p'' "
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else {
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RC commune unif.
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst_g "`listconst_g' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ else {
+ /* Contraintes de DIF */
+ if dif_rc[`k',1]==.|dif_rc[`k',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=0+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`k',2]!=. & dif_rc[`k',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ if `k'!=`j'{ /*contraintes pour les autres items */
+ if dif_rc[`k',3]==. | dif_rc[`k',3]==0 {/*pas de RC sur item k: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p'' `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item k
+ if dif_rc[`k',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`k''{ /***************************** j=1 ou 2 ?****/
+ local listconst "`listconst' `=800+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`k'-1)+`p''
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RC commune unif.
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`k',5]==. | dif_rc[`k',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=400+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',6]!=. & dif_rc[`k',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1000+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`k',7]==. | dif_rc[`k',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`k''{
+ local listconst "`listconst' `=600+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ if dif_rc[`k',8]!=. & dif_rc[`k',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`k'' > 2 {
+ forvalues p=2/`nbdif_`k''{
+ local listconst "`listconst' `=1200+`maxdif'*(`k'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`k'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ if "`group'" == "" { // Sans l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) means(THETA1@0 THETA2@m20) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /*****************/
+ /*tests RC item j*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']_cons =[1.``=`j'+`nbitems''']_cons
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']_cons =[`p'.``=`j'+`nbitems''']_cons, acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+
+
+ /* RCU ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[2.``=`j'+`nbitems''']_cons -[2.``j'']_cons
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']_cons -[1.``j'']_cons)=[`p'.``=`j'+`nbitems''']_cons -[`p'.``j'']_cons , acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2), r(df),r(p))
+ }
+ }
+ else { // Avec l'option group
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /*****************/
+ /*tests RC item i*/
+ /*****************/
+
+ /* RC ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp', acc
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC COMMUNE ? */
+ qui test [1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ }
+ matrix test_rcCOMM_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ /* RC groupe 0 ? */
+ qui test [1.``j'']0bn.`gp'=[1.``=`j'+`nbitems''']0bn.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']0bn.`gp'=[`p'.``=`j'+`nbitems''']0bn.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[2.``=`j'+`nbitems''']0bn.`gp'-[2.``j'']0bn.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']0bn.`gp'-[1.``j'']0bn.`gp')=[`p'.``=`j'+`nbitems''']0bn.`gp'-[`p'.``j'']0bn.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',1]=(r(chi2),r(df),r(p))
+ }
+
+ /* RC groupe 1 ? */
+ qui test [1.``j'']1.`gp'=[1.``=`j'+`nbitems''']1.`gp'
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui test [`p'.``j'']1.`gp'=[`p'.``=`j'+`nbitems''']1.`gp', acc
+ }
+ }
+ matrix test_rc_`boucle'[`j',7]=(r(chi2),r(df),r(p))
+
+ /* RCU grp 1 ? */
+ if `nbmoda_`j'' > 2 {
+ qui test 2*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[2.``=`j'+`nbitems''']1.`gp'-[2.``j'']1.`gp'
+ forvalues p=3/`nbdif_`j''{
+ qui test `p'*([1.``=`j'+`nbitems''']1.`gp'-[1.``j'']1.`gp')=[`p'.``=`j'+`nbitems''']1.`gp'-[`p'.``j'']1.`gp', acc
+ }
+ matrix test_rcU_`boucle'[`j',4]=(r(chi2),r(df),r(p))
+ }
+ }
+ /******* Matrice test complĂšte *********/
+ if "`detail'" != "" {
+ di in ye _col(10) %-30s abbrev("``j'' :",22) in gr _col(40) %6.3f test_rc_`boucle'[`j',1] _col(55) test_rc_`boucle'[`j',2] _col(60) %6.4f test_rc_`boucle'[`j',3]
+ }
+ }
+ }
+ }
+ //matrix list test_rc_`boucle'
+ forvalues j=1/`nbitems'{
+ if test_rc_`boucle'[`j',3]<`pajust'{/*si RC sur item i*/
+ if test_rc_`boucle'[`j',3]<`minpval'{
+ local minpval=test_rc_`boucle'[`j',3]
+ local itemrc=`j'
+ }
+ }
+ }
+ if `itemrc' != 0 { // itemrc = numéro de l'item avec le test le + sig.
+ if "`group'" == "" { // Recalibration si pas d'option groupe
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ if "`detail'" != "" {
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Recalibration on ``itemrc''"
+ di _col(40) "Chi-square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Uniform RC ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(55) `=test_rcU_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ }
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { //RC Uniforme sur itemRC
+ matrix dif_rc[`itemrc',6]=`boucle'
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Uniform RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Non-uniform RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ }
+ else {
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Recalibration "
+ di _col(15) _dup(60) "-"
+ }
+ }
+ }
+ else { // Option groupe
+ if "`detail'" != "" {
+ di _col(15) _dup(60) "-"
+ di _col(15) in ye "Recalibration on ``itemrc''"
+ di
+ di _col(40) "Chi-Square" _col(55) "DF" _col(60) "P-value"
+ di _col(15) in ye "Common RC ? " in gr _col(40) %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' _col(55) `=test_rcCOMM_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcCOMM_`boucle'[`itemrc',3]'
+ }
+ if test_rcCOMM_`boucle'[`itemrc',3] < 0.05 { //RC différentielle
+ if "`detail'" != "" {
+ di
+ di _col(15) in ye "RC group 0 ? " in gr _col(40) %4.2f `=test_rc_`boucle'[`itemrc',4]' _col(55) `=test_rc_`boucle'[`itemrc',5]' _col(60) %6.4f `=test_rc_`boucle'[`itemrc',6]' "{it: - with adjusted alpha = `pajust2' }"
+ }
+ if test_rc_`boucle'[`itemrc',6] < `pajust2' { //RC gp 0
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',5]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ di _col(15) in ye "Uniform RC on gp 0 ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',1]' _col(55) `=test_rcU_`boucle'[`itemrc',2]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',3]'
+ if test_rcU_`boucle'[`itemrc',3] >= 0.05 { // RCU gp 0
+ matrix dif_rc[`itemrc',6]=`boucle'
+ local phrase_diff = ">>> ``itemrc'' : Uniform differential RC on group 0."
+ }
+ else {
+ matrix dif_rc[`itemrc',6]=0
+ local phrase_diff = ">>> ``itemrc'' : Non-uniform differential RC on group 0."
+ }
+ }
+ else {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 0."
+ }
+ }
+ if "`detail'" != "" {
+ di
+ di _col(15) in ye "RC group 1 ? " in gr _col(40) %4.2f `=test_rc_`boucle'[`itemrc',7]' _col(55) `=test_rc_`boucle'[`itemrc',8]' _col(60) %6.4f `=test_rc_`boucle'[`itemrc',9]' "{it: - with adjusted alpha = `pajust2' }"
+ }
+ if test_rc_`boucle'[`itemrc',9] < `pajust2' { //RC gp 1
+ local ++nbsig
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ if `nbmoda_`itemrc'' > 2 {
+ if "`detail'" != "" {
+ di _col(15) in ye "Uniform RC on gp 1 ? " in gr _col(40) %4.2f `=test_rcU_`boucle'[`itemrc',4]' _col(55) `=test_rcU_`boucle'[`itemrc',5]' _col(60) %6.4f `=test_rcU_`boucle'[`itemrc',6]'
+ }
+ if test_rcU_`boucle'[`itemrc',6] >= 0.05 { // RCU gp 1
+ matrix dif_rc[`itemrc',8]=`boucle'
+ if "`detail'" != "" {
+ di
+ }
+ if dif_rc[`itemrc',5] != `boucle' { //RC slmt sur g1
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 0 and uniform RC on group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 0 and uniform RC on group 1."
+ }
+ }
+ }
+ else { //RCNU gp 1
+ matrix dif_rc[`itemrc',8]=0
+ if "`detail'" != "" {
+ di
+ }
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 1."
+ }
+ else {
+ if dif_rc[`itemrc',6] == 0 { // + RCNU g0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, non-uniform RC on group 0 and non-uniform RC on group 1."
+ }
+ else { // + RCU G0
+ local phrase_diff = ">>> ``itemrc'' : Differential RC, uniform RC on group 0 and non-uniform RC on group 1."
+ }
+ }
+ }
+ }
+ else {
+ if dif_rc[`itemrc',5] != `boucle' {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 1."
+ }
+ else {
+ local phrase_diff = ">>> ``itemrc'' : Differential RC on group 0 and differential RC on group 1."
+ }
+ }
+ }
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye "`phrase_diff'"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else { // RC commune -> MAJ modĂšle 3
+ /*******************************************************************************************************************/
+ if `nbmoda_`itemrc'' == 2 {
+ if "`detail'" != "" {
+ di
+ di _col(14) in ye ">>> {ul:``itemrc''}: recalibration"
+ di _col(20) in ye "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ }
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ local ++nbsig
+ }
+ else {
+ matrix dif_rc[`itemrc',3]=`boucle'
+ matrix dif_rc[`itemrc',4]=0
+ matrix dif_rc[`itemrc',5]=`boucle'
+ matrix dif_rc[`itemrc',7]=`boucle'
+ //matrix list dif_rc
+ local model ""
+ local listconst ""
+ forvalues j=1/`nbitems'{
+ /* Contraintes de DIF */
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { // contraintes si pas de DIF (1-200)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ if `j' != `itemrc'{ /*contraintes pour les autres items */
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 {/*pas de RC sur item p: contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { //RC détectée sur l'item p
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else if dif_rc[`j',4] != 0 & dif_rc[`j',4]!=0. { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ qui local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+ else { // Contrainte de RC commune pour l'itemrc
+ forvalues p=1/`nbdif_`j''{
+ qui local listconst "`listconst' `=800+`maxdif'*(`itemrc'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`itemrc'-1)+`p''
+ }
+ }
+ }
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+
+ /************************/
+ /*tests RC item `itemrc'*/
+ /************************/
+ matrix commU_`boucle'=J(`nbitems',3,.) //Matrice des tests de RCU slmt si RC commune
+ matrix colnames commU_`boucle'= chi_RCU df_RCU p_RCU
+
+ /* RCU grp 0 ? */
+ if `nbmoda_`itemrc'' > 2 {
+ qui test 2*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[2.``=`itemrc'+`nbitems''']0bn.`gp'-[2.``itemrc'']0bn.`gp'
+ forvalues j=3/`nbdif_`itemrc''{
+ qui test `j'*([1.``=`itemrc'+`nbitems''']0bn.`gp'-[1.``itemrc'']0bn.`gp')=[`j'.``=`itemrc'+`nbitems''']0bn.`gp'-[`j'.``itemrc'']0bn.`gp', acc
+ }
+ matrix commU_`boucle'[`itemrc',1]=(r(chi2),r(df),r(p))
+ if "`detail'" != "" {
+ di _col(15) in ye "Uniform RC ?" in gr _col(40) %4.2f `=commU_`boucle'[`itemrc',1]' _col(55) `=commU_`boucle'[`itemrc',2]' _col(60) %6.4f `=commU_`boucle'[`itemrc',3]'
+ }
+ if commU_`boucle'[`itemrc',3] >= 0.05 { // RCU
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=`boucle'
+ matrix dif_rc[`itemrc',8]=`boucle'
+ if "`detail'" != "" {
+ di
+ //di _col(14) in ye ">>> {ul:``itemrc''}: recalibration"
+ //di _col(20) in ye "Common " in gr "{it:(Chi-s: " %4.2f `=test_rcCOMM_`boucle'[`itemrc',1]' ", DF: `=test_rcCOMM_`boucle'[`itemrc',2]' p-val. : " %4.2f `=test_rcCOMM_`boucle'[`itemrc',3]' ")}"
+ di _col(17) in ye ">>> ``itemrc'' : Uniform common RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ else {
+ local ++nbsig
+ matrix dif_rc[`itemrc',6]=0
+ matrix dif_rc[`itemrc',8]=0
+ if "`detail'" != "" {
+ di
+ di _col(17) in ye ">>> ``itemrc'' : Non-uniform common RC"
+ di _col(15) _dup(60) "-"
+ }
+ }
+ }
+ }
+ } // fin de RC commune
+ }
+ }
+ else {
+ local stop = 1
+ }
+ /*******************************************************************************************************************/
+ // Fin de RC sur item i
+ if `nbsig'==0{
+ local stop=1
+ if `boucle' == 1 {
+ if "`detail'" != "" {
+ di
+ di _col(20) in ye "No significant tests, no recalibration detected"
+ di _col(10) "{hline 70}"
+ di
+ }
+ }
+ else {
+ if "`detail'" != "" {
+ di
+ di _col(20) in ye ">>> No other significant tests"
+ di _col(10) "{hline 70}"
+ di
+ }
+ }
+ }
+ local ++boucle
+ }
+}
+
+
+
+ *********************************
+ *** BILAN ***
+ *********************************
+
+
+
+if "`group'" != "" & "`nodif'" == "" {
+ di
+ di _col(2) "{hline 80}"
+ di in ye _col(18) "Difference in"
+ di in ye _col(2) "Item" _col(18) "groups at T1" _col(36) "Recalibration" _col(54) "RC " abbrev("`gp'",10) " 0" _col(72) "RC " abbrev("`gp'",10) " 1"
+ di _col(2) "{hline 80}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ local difft1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ if (dif_rc[`j',1] != . ) {
+ if (dif_rc[`j',2]!=0) {
+ local difft1 "Uniform"
+ }
+ else {
+ local difft1 "Non-uniform"
+ }
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ if dif_rc[`j',1] != . {
+ local difft1 " X "
+ }
+ }
+ di in ye _col(2) abbrev("``j''",15) in gr _col(18) "`difft1'" _col(36) "`RC'" _col(54) "`RCg0'" _col(72) "`RCg1'"
+ }
+ di _col(2) "{hline 80}"
+}
+else if "`group'" != "" & "`nodif'" != "" {
+ di
+ di _col(10) "{hline 70}"
+ di in ye _col(10) "Item" _col(26) "Recalibration" _col(46) "RC `gp' 0" _col(62) "RC `gp' 1"
+ di _col(10) "{hline 70}"
+ forvalues j=1/`nbitems' {
+ local RC
+ local RCg0
+ local RCg1
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] == 0) {
+ local RC "Common"
+ }
+ if (dif_rc[`j',3] != . & dif_rc[`j',3] != 0 & dif_rc[`j',4] != 0) {
+ local RC "Differential"
+ }
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RCg0 "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RCg0 "Non-uniform"
+ }
+ if (dif_rc[`j',8]!=. & dif_rc[`j',8] != 0) {
+ local RCg1 "Uniform"
+ }
+ if ( dif_rc[`j',8] == 0) {
+ local RCg1 "Non-uniform"
+ }
+ }
+ else {
+ if dif_rc[`j',6] != . {
+ local RCg0 " X "
+ }
+ if dif_rc[`j',8] != . {
+ local RCg1 " X "
+ }
+ }
+ di in ye _col(10) "``j''" in gr _col(26) "`RC'" _col(44) "`RCg0'" _col(62) "`RCg1'"
+ }
+ di _col(10) "{hline 70}"
+}
+else if "`group'" == "" {
+ di
+ di _col(10) "{hline 40}"
+ di in ye _col(10) "Item" _col(36) "Recalibration"
+ di _col(10) "{hline 40}"
+ forvalues j=1/`nbitems' {
+ local RC
+ if dif_rc[`j',3] != . {
+ if `nbmoda_`j'' > 2 {
+ if (dif_rc[`j',6]!=. & dif_rc[`j',6] != 0) {
+ local RC "Uniform"
+ }
+ if (dif_rc[`j',6] == 0) {
+ local RC "Non-uniform"
+ }
+ }
+ else {
+ local RC " X "
+ }
+ }
+ di in ye _col(10) "``j''" in gr _col(38) "`RC'"
+ }
+ di _col(10) "{hline 40}"
+}
+
+
+ *********************************
+ ** MODEL 4 **
+ *********************************
+if "`detail'" != "" {
+ di
+ di in ye "PROCESSING STEP 4"
+ di
+}
+ //matrix list dif_rc, title ("Constraints")
+
+local model ""
+local listconst ""
+local listconst_g ""
+forvalues j=1/`nbitems'{
+ if "`group'" != "" {
+ if dif_rc[`j',1]==.|dif_rc[`j',1]==0 { /*si pas de DIF: contraintes 1-200 */
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=0+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=0+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ else { // Présence de DIF
+ if dif_rc[`j',2]!=. & dif_rc[`j',2]!=0 { // contraintes de DIF U (201-400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ if dif_rc[`j',3]==. | dif_rc[`j',3]==0 { /*pas de RC : contraintes 401-600 601-800*/
+ forvalues p=1/`nbdif_`j''{
+ if "`group'" == "" {
+ local listconst_g "`listconst_g' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ else {
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p'' `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ else { //RC détectée sur l'item j
+ if "`group'" == "" {
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst_g "`listconst_g' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else {
+ if dif_rc[`j',4]==0{ /*RC commune: contraintes 801-1000*/
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=800+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=800+`maxdif'*(`j'-1)+`p''
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RC commune unif.
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ else { // RC diff
+ if dif_rc[`j',5]==. | dif_rc[`j',5]==0 { // RC gp0 (400)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=400+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=400+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',6]!=. & dif_rc[`j',6]!=0 { // RCU gp0 (1001-1200)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1000+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1000+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ if dif_rc[`j',7]==. | dif_rc[`j',7]==0 { // RC gp1 (600)
+ forvalues p=1/`nbdif_`j''{
+ local listconst "`listconst' `=600+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=600+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ if dif_rc[`j',8]!=. & dif_rc[`j',8]!=0 { // RCU gp1 (1201-1400)
+ if `nbmoda_`j'' > 2 {
+ forvalues p=2/`nbdif_`j''{
+ local listconst "`listconst' `=1200+`maxdif'*(`j'-1)+`p''"
+ qui constraint list `=1200+`maxdif'*(`j'-1)+`p''
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+local model ""
+
+forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+}
+
+if "`group'" != "" {
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+else {
+ qui gsem `model', mlogit tol(0.01) iterate(100) means( THETA1@0 THETA2@m2) var(THETA1@v1 THETA2@v2) cov(THETA1*THETA2@cov12) constraint(`listconst_g') from(esti_2, skip) latent(THETA1 THETA2) nocapslatent
+}
+ /* Stockage des estimations du modĂšle */
+matrix val_m4 = r(table)
+matrix esti_4 = e(b)
+
+if "`group'" != "" {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)#0bn.`gp'"],val_m4[1,"/var(THETA2)#0bn.`gp'"]\val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[1,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[2,"/cov(THETA1,THETA2)#1.`gp'"]\val_m4[4,"/cov(THETA1,THETA2)#0.`gp'"],val_m4[4,"/cov(THETA1,THETA2)#1.`gp'"])
+}
+else {
+ matrix var_m4 = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"]\val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix covar_m4 = (val_m4[1,"/cov(THETA1,THETA2)"]\val_m4[2,"/cov(THETA1,THETA2)"]\val_m4[4,"/cov(THETA1,THETA2)"])
+}
+
+/* Matrice des tests effet grp, tps et inter */
+matrix effet = J(5,3,.)
+matrix colnames effet= Groupe Temps Interaction
+matrix rownames effet = Esti Std_Err Pvalue Chi DF
+
+/*group effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,1] =r(estimate)
+ matrix effet[2,1]=r(se)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,1]=r(p)
+ matrix effet[4,1]=r(chi2)
+ matrix effet[5,1]=r(df)
+}
+
+/*time effect*/
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,2]=r(estimate)
+ matrix effet[2,2]=r(se)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,2]=r(p)
+ matrix effet[4,2]=r(chi2)
+ matrix effet[5,2]=r(df)
+}
+else {
+ qui lincom [/]:mean(THETA2) /* -[/]:mean(THETA1)*/
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local ubteffm4 = r(ub)
+ local lbteffm4 = r(lb)
+ qui test [/]:mean(THETA2) /* -[/]:mean(THETA1) */ = 0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+*INTERACTION
+if "`group'" != "" {
+ qui lincom [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp'
+ matrix effet[1,3]=r(estimate)
+ matrix effet[2,3]=r(se)
+ local ubinterm4=r(ub)
+ local lbinterm4=r(lb)
+ qui test [/]:mean(THETA2)#1.`gp'-[/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#1.`gp'+[/]:mean(THETA1)#0bn.`gp' = 0
+ matrix effet[3,3]=r(p)
+ matrix effet[4,3]=r(chi2)
+ matrix effet[5,3]=r(df)
+}
+
+if "`group'" != "" {
+ local effet_tps = 0
+ local effet_grp = 0
+
+ if effet[3,3] >= 0.05 { // Si option group, on s'interesse Ă l'interaction temps x group, et MAJ modĂšle >>> modĂšle final = modĂšle 4 + contrainte 1999 (Interaction = 0)
+ /* Affichage des estimations sur le trait latent du modĂšle 4 */
+ if "`detail'" != "" {
+ di
+ di _col(10) in ye "Latent trait estimates"
+ di _col(10) "{hline 80}"
+ di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+ di _col(10) "{hline 80}"
+ di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=var_m4[1,1]' _col(62) %6.2f `=var_m4[2,1]'
+ di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=var_m4[1,2]' _col(62) %6.2f `=var_m4[2,2]'
+ di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=covar_m4[1,1]' _col(62) %6.2f `=covar_m4[2,1]'
+ if "`group'" != "" {
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f effet[1,1] _col(62) %6.2f effet[2,1] _col(77) %6.4f effet[3,1]
+ }
+ di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f effet[1,2] _col(62) %6.2f effet[2,2] _col(77) %6.4f effet[3,2]
+
+ if "`group'" != "" {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f effet[1,3] _col(62) %6.2f effet[2,3] _col(77) %6.4f effet[3,3]
+ }
+ di _col(10) "{hline 80}"
+ di
+ di in ye ">>> Time x group interaction : no significant test, estimate of model 4 with constraint of time x group interaction at 0 "
+ di
+ }
+ local yn_inter = 0
+ local listconst "`listconst' 1999"
+ qui di "`listconst'"
+ local model ""
+ forvalues jj=1/`nbitems'{
+ forvalues p=1/`nbdif_`jj''{
+ local model "`model' (`p'.``jj''<-THETA1@`p')(`p'.``=`jj'+`nbitems'''<-THETA2@`p')"
+ }
+ }
+ qui gsem `model', mlogit tol(0.01) iterate(100) group(`gp') ginvariant(coef loading) means(0: THETA1@0 THETA2@m20) means(1: THETA1@m11 THETA2@m21) var(0: THETA1@v1 THETA2@v2) var(1:THETA1@v1 THETA2@v2) cov(0: THETA1*THETA2@cov12) cov(1: THETA1*THETA2@cov12) constraint(`listconst') from(esti_4, skip) latent(THETA1 THETA2) nocapslatent
+
+ matrix val_m4 = r(table)
+ }
+ else {
+ local yn_inter = 1
+ }
+
+ /*group effect*/
+ qui lincom [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local geffm4=r(estimate)
+ local segeffm4=r(se)
+ local ubgeffm4=r(ub)
+ local lbgeffm4=r(lb)
+ qui test [/]:mean(THETA1)#1.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local gpm4p=r(p)
+ local gpm4chi=r(chi2)
+ local gpm4df=r(df)
+
+ /*time effect*/
+ qui lincom [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'
+ local teffm4=r(estimate)
+ local seteffm4=r(se)
+ local lbteffm4=r(lb)
+ local ubteffm4=r(ub)
+ qui test [/]:mean(THETA2)#0bn.`gp'-[/]:mean(THETA1)#0bn.`gp'=0
+ local tm4p=r(p)
+ local tm4chi=r(chi2)
+ local tm4df=r(df)
+}
+
+ /* Calcul des difficultés (delta_j) */
+if "`group'" != "" {
+ matrix mod4 = J(7,`=`nbmoda_sum'*4+6',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ forvalues g = 0/1 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_gp`g'_t`t'"
+ }
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) GROUP_Effect TIME_Effect INTER_TxG "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+else {
+ matrix mod4 = J(7,`=`nbmoda_sum'*2+4',.)
+ local name_partTwoC ""
+ forvalues j = 1/`nbitems' {
+ forvalues p=1/`nbdif_`j'' {
+ forvalues t=1/2 {
+ local name_partTwoC "`name_partTwoC' d_j`j'_p`p'_t`t'"
+ }
+ }
+ }
+ local name_partTwoC "`name_partTwoC' VAR(THETA1) VAR(THETA2) COV(TH1,TH2) TIME_Effect "
+ matrix colnames mod4 = `name_partTwoC'
+ matrix rownames mod4 = Estimate se Upper_b Lower_b Chi_square DF pvalue
+}
+
+*Difficultés
+forvalues j=1/`nbitems'{
+ forvalues p=1/`nbdif_`j''{
+ forvalues t=1/2{
+ if "`group'" != "" { // groupe binaire
+ forvalues g=0/1 {
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4= r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se= r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ if `p'>1 {
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp' - [`p'.``=(`t'-1)*`nbitems'+`j''']:`g'.`gp'
+ local delta`t'_`j'_`p'g`g'm4=r(estimate)
+ local delta`t'_`j'_`p'g`g'm4_se=r(se)
+ local delta`t'_`j'_`p'g`g'm4_ub=r(ub)
+ local delta`t'_`j'_`p'g`g'm4_lb=r(lb)
+ local delta`t'_`j'_`p'g`g'm4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4'
+ matrix mod4[2,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_se'
+ matrix mod4[3,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_ub'
+ matrix mod4[4,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_lb'
+ matrix mod4[7,`=4*(`p'-1)+`g'+`t'+1+4*`place'']=`delta`t'_`j'_`p'g`g'm4_p'
+ }
+ }
+ }
+ else { // groupe unique (=gp0)
+ qui lincom -[`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4= r(estimate)
+ local delta`t'_`j'_`p'g0m4_se= r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ if `p'>1{
+ qui lincom [`=`p'-1'.``=(`t'-1)*`nbitems'+`j''']_cons - [`p'.``=(`t'-1)*`nbitems'+`j''']_cons
+ local delta`t'_`j'_`p'g0m4=r(estimate)
+ local delta`t'_`j'_`p'g0m4_se=r(se)
+ local delta`t'_`j'_`p'g0m4_ub=r(ub)
+ local delta`t'_`j'_`p'g0m4_lb=r(lb)
+ local delta`t'_`j'_`p'g0m4_p=r(p)
+ }
+ local place = 0
+ local compt = 1
+ while `compt' < `j' {
+ local place = `place' + `nbdif_`compt''
+ local ++compt
+ }
+ if `t' == 1 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ if `t' == 2 {
+ matrix mod4[1,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4'
+ matrix mod4[2,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_se'
+ matrix mod4[3,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_ub'
+ matrix mod4[4,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_lb'
+ matrix mod4[7,`=2*(`p'-1)+`t'+2*`place'']=`delta`t'_`j'_`p'g0m4_p'
+ }
+ }
+ }
+ }
+}
+
+if "`group'" != "" {
+ matrix mod4[1,`=4*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)#0bn.`gp'"], val_m4[1,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)#0bn.`gp'"],val_m4[2,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)#0bn.`gp'"],val_m4[6,"/var(THETA2)#0bn.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)#0bn.`gp'"],val_m4[5,"/var(THETA2)#0bn.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)#0.`gp'"])
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)#0.`gp'"])
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1'] = `geffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1'] = `segeffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1'] = `ubgeffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1'] = `lbgeffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1'] = `gpm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1'] = `gpm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1'] = `gpm4p'
+
+
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1'] = `teffm4'
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1'] = `seteffm4'
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1'] = `ubteffm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1'] = `lbteffm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4chi'
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4df'
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1'] = `tm4p'
+
+ if `yn_inter' == 1 { //Slmt si model avec interaction
+ matrix mod4[1,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[1,3]
+ matrix mod4[2,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[2,3]
+ matrix mod4[3,`=4*`nbmoda_sum'+2+1+1+1+1'] = `ubinterm4'
+ matrix mod4[4,`=4*`nbmoda_sum'+2+1+1+1+1'] = `lbinterm4'
+ matrix mod4[5,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[4,3]
+ matrix mod4[6,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[5,3]
+ matrix mod4[7,`=4*`nbmoda_sum'+2+1+1+1+1'] = effet[3,3]
+ }
+
+}
+else {
+ matrix mod4[1,`=2*`nbmoda_sum'+1'] = (val_m4[1,"/var(THETA1)"],val_m4[1,"/var(THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+1'] = (val_m4[2,"/var(THETA1)"],val_m4[2,"/var(THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+1'] = (val_m4[6,"/var(THETA1)"],val_m4[6,"/var(THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+1'] = (val_m4[5,"/var(THETA1)"],val_m4[5,"/var(THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1'] = (val_m4[1,"/cov(THETA1,THETA2)"])
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1'] = (val_m4[2,"/cov(THETA1,THETA2)"])
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1'] = (val_m4[6,"/cov(THETA1,THETA2)"])
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1'] = (val_m4[5,"/cov(THETA1,THETA2)"])
+
+ matrix mod4[1,`=2*`nbmoda_sum'+2+1+1'] = `teffm4'
+ matrix mod4[2,`=2*`nbmoda_sum'+2+1+1'] = `seteffm4'
+ matrix mod4[3,`=2*`nbmoda_sum'+2+1+1'] = `ubteffm4'
+ matrix mod4[4,`=2*`nbmoda_sum'+2+1+1'] = `lbteffm4'
+ matrix mod4[5,`=2*`nbmoda_sum'+2+1+1'] = `tm4chi'
+ matrix mod4[6,`=2*`nbmoda_sum'+2+1+1'] = `tm4df'
+ matrix mod4[7,`=2*`nbmoda_sum'+2+1+1'] = `tm4p'
+}
+
+
+ /* Affichage des estimations des difficultés */
+di _col(5) in ye "{ul:MODEL 4} = Final model"
+di
+di _col(10) in ye "Item difficulties estimates (s.e.)"
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+ di _col(30) "Time 1" _col(70) "Time 2"
+ di in ye _col(20) abbrev("`gp'",15) "=0" _col(38) abbrev("`gp'",15) "=1" _col(58) abbrev("`gp'",15) "=0" _col(76) abbrev("`gp'",15) "=1"
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+ di _col(30) "Time 1" _col(45) "Time 2"
+ di _col(10) "{hline 50}"
+}
+
+forvalues j=1/`nbitems' {
+ di in ye _col(10) "``j''"
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" {
+ di in gr _col(10) "`p'" _col(20) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(38) %6.2f `delta1_`j'_`p'g1m4' " (" %4.2f `delta1_`j'_`p'g1m4_se' ")" ///
+ _col(58) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")" _col(76) %6.2f `delta2_`j'_`p'g1m4' " (" %4.2f `delta2_`j'_`p'g1m4_se' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `delta1_`j'_`p'g0m4' " (" %4.2f `delta1_`j'_`p'g0m4_se' ")" _col(42) %6.2f `delta2_`j'_`p'g0m4' " (" %4.2f `delta2_`j'_`p'g0m4_se' ")"
+ }
+ }
+}
+
+if "`group'" != "" {
+ di _col(10) "{hline 85}"
+}
+else {
+ di _col(10) "{hline 50}"
+}
+
+ /* Affichage des estimations sur le trait latent du modĂšle final */
+di
+di _col(10) in ye "Latent trait distribution estimates"
+di _col(10) "{hline 80}"
+di _col(45) in ye "Estimate" _col(60) "Standard error" _col(77) "P-value"
+di _col(10) "{hline 80}"
+
+if "`group'" == "" {
+ local fact_k = 2
+}
+else {
+ local fact_k = 4
+}
+
+di _col(10) in ye "Variance Time 1" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+1']' _col(62) %6.2f =mod4[2,`=`fact_k'*`nbmoda_sum'+1']
+di _col(10) in ye "Variance Time 2" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+2']' _col(62) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+2']'
+di _col(10) in ye "Covariance" in gr _col(44) %6.2f `=mod4[1,`=`fact_k'*`nbmoda_sum'+3']' _col(62) %6.2f `=mod4[2,`=`fact_k'*`nbmoda_sum'+3']'
+
+if "`group'" != "" {
+
+ di _col(10) in ye "Group effect (mean gp 1 at T1)" in gr _col(44) %6.2f `geffm4' _col(62) %6.2f `segeffm4' _col(77) %6.4f `gpm4p'
+}
+di _col(10) in ye "Time effect (mean gp 0 at T2)" in gr _col(44) %6.2f `teffm4' _col(62) %6.2f `seteffm4' _col(77) %6.4f `tm4p'
+
+if "`group'" != "" {
+ if effet[3,3] < 0.05 {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) %6.2f effet[1,3] _col(62) %6.2f effet[2,3] _col(77) %6.4f effet[3,3]
+ }
+ else {
+ di _col(10) in ye "TimexGroup inter" in gr _col(44) "0 (constrained)"
+ }
+}
+
+di _col(10) "{hline 80}"
+
+/***************************************/
+/* Calcul des valeurs de DIF et de RC */
+/*************************************/
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ matrix valeur_difrc_`j' = J(`nbdif_`j'',8,.)
+ matrix colnames valeur_difrc_`j' = DIFT1 DIFT1_SE RC_GP0 RC_GP0_SE RC_GP1 RC_GP1_SE
+ }
+}
+
+forvalues j=1/`nbitems'{
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" {
+ *DIF
+ if "`nodif'"=="" {
+ if (dif_rc[`j',1] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ if `p' == 1 {
+ qui lincom -[1.``j'']:1.`gp'+[1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``j'']:1.`gp' - [`p'.``j'']:1.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',1] = r(estimate)
+ matrix valeur_difrc_`j'[`p',2] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ *RC GROUP 0
+ if (dif_rc[`j',3] != . & dif_rc[`j',5] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:0.`gp' + [1.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:0.`gp' - [`p'.``=`j'+`nbitems''']:0.`gp' -[`=`p'-1'.``j'']:0.`gp' + [`p'.``j'']:0.`gp'
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ *RC GROUP 1
+ if (dif_rc[`j',3] != . & dif_rc[`j',7] != . ) {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']:1.`gp' + [1.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']:1.`gp' - [`p'.``=`j'+`nbitems''']:1.`gp' -[`=`p'-1'.``j'']:1.`gp' + [`p'.``j'']:1.`gp'
+ matrix valeur_difrc_`j'[`p',5] = r(estimate)
+ matrix valeur_difrc_`j'[`p',6] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+ else {
+ forvalues p=1/`nbdif_`j'' {
+ qui lincom -[1.``=`j'+`nbitems''']_cons + [1.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ if `p' > 1 {
+ qui lincom [`=`p'-1'.``=`j'+`nbitems''']_cons - [`p'.``=`j'+`nbitems''']_cons -[`=`p'-1'.``j'']_cons + [`p'.``j'']_cons
+ matrix valeur_difrc_`j'[`p',3] = r(estimate)
+ matrix valeur_difrc_`j'[`p',4] = round(r(se),0.01)
+ }
+ }
+ }
+ }
+}
+
+forvalues j = 1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ forvalues p = 1/`nbdif_`j'' {
+ forvalues k = 1/8 {
+ if valeur_difrc_`j'[`p',`k'] == . {
+ matrix valeur_difrc_`j'[`p',`k'] = 0
+ }
+ }
+ }
+ }
+}
+
+ /* Affichage des estimations des valeurs de DIF et de RC */
+if "`group'" != "" {
+ di
+ di _col(10) in ye "Values of differences between groups and values of recalibration"
+}
+else {
+ di
+ di _col(10) in ye "Values of recalibration"
+}
+if "`group'" != "" & "`nodif'"==""{
+ di _col(10) "{hline 70}"
+ di _col(30) "Difference of" _col(52) "RECALIBRATION"
+ di _col(30) "groups at T1" _col(47) in ye abbrev("`gp'",15) "=0" _col(62) abbrev("`gp'",15) " =1"
+ di _col(10) "{hline 70}"
+}
+else if "`group'" != "" & "`nodif'"!="" {
+ di _col(10) "{hline 50}"
+ di _col(32) "RECALIBRATION"
+ di in ye _col(27) "`gp'=`=rep[1,1]'" _col(47) "`gp'=`=rep[2,1]'"
+ di _col(10) "{hline 50}"
+}
+else {
+ di _col(10) "{hline 30}"
+ di _col(15) "RECALIBRATION"
+ di _col(10) "{hline 30}"
+}
+
+forvalues j=1/`nbitems' {
+ if `nbmoda_`j'' >= 2 {
+ if "`group'" != "" & "`nodif'" == "" {
+ di in ye _col(10) "``j''"
+ }
+ else {
+ di in ye _col(10) "``j''"
+ }
+ forvalues p=1/`nbdif_`j'' {
+ if "`group'" != "" & "`nodif'"=="" {
+ di in gr _col(10) "`p'" _col(29) %6.2f `=valeur_difrc_`j'[`p',1]' " (" %4.2f `=valeur_difrc_`j'[`p',2]' ")" ///
+ _col(47) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(62) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else if "`group'" != "" & "`nodif'"!="" {
+ di in gr _col(10) "`p'" _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")" _col(45) %6.2f `=valeur_difrc_`j'[`p',5]' " (" %4.2f `=valeur_difrc_`j'[`p',6]' ")"
+ }
+ else {
+ di in gr _col(10) "`p'" _col(25) %6.2f `=valeur_difrc_`j'[`p',3]' " (" %4.2f `=valeur_difrc_`j'[`p',4]' ")"
+ }
+ }
+ }
+}
+
+if "`group'" != "" & "`nodif'"=="" {
+ di _col(10) "{hline 70}"
+}
+else if "`group'" != "" & "`nodif'"!=""{
+ di _col(10) "{hline 50}"
+}
+else {
+ di _col(10) "{hline 30}"
+}
+di
+
+
+*******************************************************************************
+* New outputs
+
+if "`group'" == "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else if "`nodif'" != "" {
+ matrix testlrm = J(1,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = m1_vs_m2
+ matrix testlrm[1,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+else {
+ matrix testlrm = J(2,3,.)
+ matrix colnames testlrm = chi_square df pvalue
+ matrix rownames testlrm = mA_vs_mB m1_vs_m2
+ matrix testlrm[1,1] = (`diftestchi',`diftestdf',`diftestp')
+ matrix testlrm[2,1] = (`rstestchi',`rstestdf',`rstestp')
+ return matrix test_model = testlrm
+}
+
+return matrix model_4 = mod4
+return matrix model_2 = mod2
+
+capture qui use `saverspcm', clear
+
+end
+
diff --git a/Modules/ado/personal/r/rsbynpirt.ado b/Modules/ado/personal/r/rsbynpirt.ado
new file mode 100644
index 0000000..1f44d07
--- /dev/null
+++ b/Modules/ado/personal/r/rsbynpirt.ado
@@ -0,0 +1,162 @@
+*! Version 1 20July2015
+************************************************************************************************************
+* rsbynpirt: Traces of items
+* Version 1: July 20, 2015 /*ICC*/
+*
+* Historic:
+* Version 1 (2015-07-20): Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2015 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 rsbynpirt
+version 8.0
+syntax varlist(numeric min=4) [, noGraph]
+
+preserve
+local nbitems : word count `varlist'
+tokenize `varlist'
+if mod(`nbitems',2)!=0 {
+ di in red "You must indicate an even number of items"
+ exit
+}
+else {
+ local nbitems=`nbitems'/2
+}
+local listofitems1
+local listofitems2
+forvalues i=1/`nbitems' {
+ local listofitems1 `listofitems1' ``i''
+ local listofitems2 `listofitems2' ``=`i'+`nbitems'''
+}
+
+tempvar varscore1 varscore2
+qui gen `varscore1'=0
+qui gen `varscore2'=0
+label variable `varscore1' "Total score time 1"
+label variable `varscore2' "Total score time 2"
+local scoremax=0
+local flag=0
+
+
+
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui replace `varscore1'=`varscore1'+``i''
+ qui replace `varscore2'=`varscore2'+``=`i'+`nbitems'''
+ qui su ``i''
+ local modamax`i'=r(max)
+ qui su ``=`i'+`nbitems'''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+}
+
+
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore1'
+local maxscore=r(max)
+qui su `varscore1'
+if `r(max)'>`maxscore' {
+ local maxscore=r(max)
+}
+tempfile rsbynpirtfile rsbynpirtfile1 rsbynpirtfile2
+tempvar score
+qui save `rsbynpirtfile', replace
+qui traces `listofitems1', nograph icc saveicc
+qui drop _all
+*matrix list r(matscore)
+tempname mat1
+qui matrix `mat1'=r(matscore)
+qui svmat `mat1', names(t1item)
+forvalues i=1/`nbitems' {
+ local j: word `i' of `listofitems1'
+ qui rename t1item`i' `j'
+}
+qui rename t1item`=`nbitems'+1' `score'
+qui contract `score' `listofitems1'
+qui sort `score'
+qui save `rsbynpirtfile1', replace
+
+qui use `rsbynpirtfile', clear
+qui traces `listofitems2', nograph icc saveicc
+qui drop _all
+tempname mat2
+qui matrix `mat2'=r(matscore)
+qui svmat `mat2', names(t2item)
+forvalues i=1/`nbitems' {
+ local j: word `i' of `listofitems2'
+ qui rename t2item`i' `j'
+}
+qui rename t2item`=`nbitems'+1' `score'
+qui contract `score' `listofitems2'
+qui sort `score'
+qui merge 1:1 `score' using `rsbynpirtfile1'
+
+if "`graph'"=="" {
+ forvalues i=1/`nbitems' {
+ twoway (line ``i'' `score') (line ``=`i'+`nbitems''' `score'), name(``i'',replace)
+ }
+}
+qui drop if `score'==0|`score'==`scoremax'
+
+di
+di "Items" _col(18) "AUC t1" _col(28) "AUC t2" _col(38) "Var AUC" _col(46) "Diff ICC" _col(57) "SD Diff"
+di "{hline 63}"
+forvalues i=1/`nbitems' {
+ qui su ``i''
+ local AUC``i''=r(sum)
+ local AUC``i''=(`AUC``i'''+`modamax`i''/2)/(`scoremax'*`modamax`i'')*100
+ qui su ``=`i'+`nbitems'''
+ local AUC`=`i'+`nbitems''=r(sum)
+ local AUC`=`i'+`nbitems''=(`AUC`=`i'+`nbitems'''+`modamax`i''/2)/(`scoremax'*`modamax`i'')*100
+ tempname diff``i''
+ gen `diff``i'''=abs(``i''-``=`i'+`nbitems''')
+ qui su `diff``i'''
+ local d``i''=`r(sum)'/(`scoremax'*`modamax`i'')*100
+ local var``i''=`r(sd)'*100
+ di "``i''/``=`i'+`nbitems'''" _col(20) %4.1f `AUC``i''' _col(30) %4.1f `AUC`=`i'+`nbitems''' _col(40) %5.1f `=`AUC``i'''-`AUC`=`i'+`nbitems'''' _col(50) %4.1f `d``i''' _col(60) %4.1f `var``i'''
+}
+qui restore , preserve
+end
+
+
diff --git a/Modules/ado/personal/r/rsoort.ado b/Modules/ado/personal/r/rsoort.ado
new file mode 100644
index 0000000..12f5163
--- /dev/null
+++ b/Modules/ado/personal/r/rsoort.ado
@@ -0,0 +1,832 @@
+*! version 1.4 29January2014
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+* Version 1.1 (2013-06-03): Jean-Benoit Hardouin /*some improvements*/
+* Version 1.2 (2013-06-03): Jean-Benoit Hardouin /*model1 model2 model3 and covariances options*/
+* Version 1.3 (2013-06-03): Jean-Benoit Hardouin /**/
+* Version 1.4 (2014-01-29): Jean-Benoit Hardouin /*add an iterate option on model 1*/
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013-2014 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=2 numeric) [if] [in] [,METHod(string) nom1 nocov12 UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch html(string) model1 model2 model4 COVariances(string) MATrixrs(string)]
+tempfile saversoort
+qui save `saversoort',replace
+preserve
+if "`matrixrs'"!="" {
+ if "`uniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:uniformrecalibration} options in the same time"
+ error
+ }
+ if "`nonuniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:nonuniformrecalibration} options in the same time"
+ error
+ }
+ if "`reprioritization'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:reprioritization} options in the same time"
+ error
+ }
+}
+
+
+if "`html'" != "" {
+ di ""
+}
+
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+if "`html'"== "" {
+ di _col(20) "{hline 30}"
+ di _col(20) in gr "Time 1" _col(40) "Time 2"
+ di _col(20) "{hline 30}"
+ forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+ }
+ di _col(20) "{hline 30}"
+}
+else {
+ di ""
+ di ""
+ di "Time 1 | Time2 |
"
+ di ""
+ forvalues i=1/`nbitems' {
+ di "``i'' | ``=`i'+`nbitems''' |
"
+ }
+ di "
"
+}
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+if "`model1'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+local cov12b
+forvalues i=1/`nbitems' {
+ local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
+}
+if "`cov12'"!="" {
+ local cov12b
+}
+if "`m1'"=="" {
+`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covariances') iterate(100)
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+local bic1=r(bic)
+}
+else {
+local chi21=.
+local df1=.
+}
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+if "`model2'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+
+di "`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')"
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ *di " | | Test of global Response-Shift | Comparison with model 1 |
"
+ di "Models | Chi-square | df | p-value | BIC |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %6.4f `p1' " | " %7.2f `bic1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %6.4f `p2' " | " %7.2f `bic2' " |
"
+ di "
"
+}
+else {
+ di "{hline 51}"
+ di in gr /*_col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"*/
+ di in gr "Models" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 51}"
+ di in gr "Model 1" _col(20) %8.2f in ye `chi21' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
+ di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
+ di "{hline 51}"
+}
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+if "`matrixrs'"=="" {
+ forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `reprioritization'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `reprioritization'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+ }
+}
+else {
+ matrix `RS'=`matrixrs'
+}
+*matrix list `RS'
+
+if "`search'"=="" {
+
+ if "`html'"=="" {
+ di
+ di "{hline 88}"
+ di in green _col(40) "Model 3"
+ di "{hline 88}"
+ di
+ di in white _col(10) "Non uniform Recalibration"
+ }
+ else {
+ di "
Model 3
"
+ di ""
+ di "Non uniform Recalibration"
+ }
+ local continue=1
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ }
+ local prec_chi2=`chi22'
+ local testNU_varchi2=0
+ local testNU_p=1
+
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Uniform recalibration
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Uniform Recalibration"
+ }
+ else {
+ di ""
+ di "Uniform Recalibration"
+ }
+ local continue=1
+ local var
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Reprioritization
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Reprioritization"
+ }
+ else {
+ di ""
+ di "Reprioritization"
+ }
+
+ local continue=1
+ local var
+ local sem
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+local bic3=r(bic)
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+if "`html'"=="" {
+ di
+ di "{hline 74}"
+ di in gr _col(22) "Non uniform" _col(46) "Uniform"
+ di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(58) "Reprioritization"
+ di "{hline 74}"
+}
+else {
+ di ""
+ di ""
+ di "Items | Non-uniform Recalibration | Uniform Recalibration | Repriorisation |
"
+ di ""
+}
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ if "`html'"=="" {
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+ }
+ else {
+ di "``i'' | `recNU' | `recU' | `rep' |
"
+ }
+}
+if "`html'"=="" {
+ di "{hline 74}"
+}
+else {
+ di "
"
+}
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+if "`model4'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) cov(`cov12b' `covariances') method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local df4=r(df_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+local bic4=r(bic)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di "Models | chi2 | df | p | BIC | RMSEA | IC90%(RMSEA) | SRMR | CFI | TLI |
"
+ di ""
+ if "`m1'"=="" {
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %7.2f `bic1' " | " %6.4f `p1' " | " %6.4f `rmsea1' " | " %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' " | " %6.4f `srmr1' " | " %6.2f `cfi1' " | " %6.2f `tli1' " |
"
+ }
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %7.2f `bic2' " | " %6.4f `p2' " | " %6.4f `rmsea2' " | " %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' " | " %6.4f `srmr2' " | " %6.2f `cfi2' " | " %6.2f `tli2' " |
"
+ di "Model 4 | " %8.2f `chi24' " | " %4.0f `df4' " | " %7.2f `bic4' " | " %6.4f `p4' " | " %6.4f `rmsea4' " | " %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' " | " %6.4f `srmr4' " | " %6.2f `cfi4' " | " %6.2f `tli4' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 95}"
+ di in gr "Models" _col(14) "chi2" _col(22) "df" _col(31) "p" _col(40) "BIC" _col(47) "RMSEA" _col(55) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+ di "{hline 95}"
+ if "`m1'"=="" {
+ di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `df1' _col(26) %6.4f `p1' _col(36) %7.2f `bic1' _col(46) %6.4f `rmsea1' _col(54) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+ }
+ di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `df2' _col(26) %6.4f `p2' _col(36) %7.2f `bic2' _col(46) %6.4f `rmsea2' _col(54) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+ *di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+ di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `df4' _col(26) %6.4f `p4' _col(36) %7.2f `bic4' _col(46) %6.4f `rmsea4' _col(54) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+ di "{hline 95}"
+}
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di " | Estimation | s.e. | z | p-value |
"
+ di ""
+ di "True change (Model 2) | " %8.4f `truechange2' " | " %8.4f `=sqrt(`Vtruechange2')' " | " %6.2f `=`truechange2'/sqrt(`Vtruechange2')' " | " %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))' " |
"
+ di "True change (Model 4) | " %8.4f `truechange' " | " %8.4f `=sqrt(`Vtruechange')' " | " %6.2f `=`truechange'/sqrt(`Vtruechange')' " | " %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 77}"
+ di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+ di "{hline 77}"
+ di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+ di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+ di "{hline 77}"
+ di
+}
+qui use `saversoort',clear
+
+
+
+end
diff --git a/Modules/ado/personal/r/rsoort.hlp b/Modules/ado/personal/r/rsoort.hlp
new file mode 100644
index 0000000..3acb1a6
--- /dev/null
+++ b/Modules/ado/personal/r/rsoort.hlp
@@ -0,0 +1,69 @@
+{smcl}
+{* 3June2013}{...}
+{hline}
+help for {hi:rsoort}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title: Oort's Structural Equations Modeling (SEM) based procedure to detect Response Shift}
+
+{p 8 14 2}{cmd:rsoort} {it:varlist} {ifin} [{cmd:,} {cmdab:meth:od}({it:string}) {cmdab:unif:ormrecalibration}({it:varlist}) {cmdab:nonunif:ormrecalibration}({it:varlist}) {cmdab:rep:rioritization}({it:varlist}) {cmdab:nos:earch}]
+
+{p 8 14 2}{it:varlist} is a list of two or more existing variables. You must first enter the list of variables to first measurement followed by the list of variables (in the same order) in the second measurement time.
+
+{title:Description}
+
+{p 4 8 2}{cmd:rsoort} provides the Oort's procedure based on Structural Equation Modeling (SEM) in order to detect Response-Shift in a set of variables.
+
+{title:Options}
+
+{p 4 8 2}{cmd:method}. By default, maximum likelihood estimations of the models parameters are used. You can use alternative methods of estimation like {cmd:mlmv} for
+maximum likelihood handling missing data or {cmd:adf} for asymptotic distribution free method.
+
+{p 4 8 2}{cmd:uniformrecalibation} allows defining variables suspected to be affected by uniform recalibration (you should give the name of the variable to the first
+measurement). In this case, the procedure force the concerned variable to be affected by uniform recalibration and this kind of response-shift is searched only on the
+other variables.
+
+{p 4 8 2}{cmd:nonuniformrecalibation} allows defining variables suspected to be affected by non uniform recalibration (you should give the name of the variable to the
+first measurement). In this case, the procedure force the concerned variable to be affected by non uniform recalibration and this kind of response-shift is searched
+only on the other variables.
+
+{p 4 8 2}{cmd:reprioritization} allows defining variables suspected to be affected by reprioritization (you should give the name of the variable to the first
+measurement). In this case, the procedure force the concerned variable to be affected by reprioritization and this kind of response-shift is searched only on the other
+variables.
+
+{p 4 8 2}{cmd:nosearch} avoids the procedure to be run (this is useful only if you precise the {cmd:uniformrecalibation}, {cmd:nonuniformrecalibation} or
+{cmd:reprioritization} options)
+
+
+
+{title:Example}
+
+ {p 8 8}{inp:. rsoort var1t1-var10t1 var1t2-var10t2}
+
+ {p 8 8}{inp:. rsoort var1t1-var10t1 var1t2-var10t2, unif(var3t1 var7t1) rep(var8t1)}
+
+ {p 8 8}{inp:. rsoort var1t1-var10t1 var1t2-var10t2, unif(var3t1 var7t1) rep(var8t1) nosearch}
+
+
+{title:References}
+
+{p 4 8 2}Oort F.J. Using structural equation modeling to detect response shifts and true change. {it: Quality of life Research}, vol.14(3), 2005, pp. 587-598.
+
+{p 4 8 2}Oort F.J., Visser M.R., Sprangers M.A. An application of structural equation modeling to detect response shifts and true change in quality of life data from cancer patients undergoing invasive surgery. {it: Quality of life Research}, vol.14(3), 2005, pp. 599-609.
+
+{p 4 8 2}Oort F.J. Towards a formal definition of response shift (in reply to G.W. Donaldson)., {it: Quality of life Research}, vol.14(10), 2005, pp. 2353-2355.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275-SPHERE "Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help sem}{p_end}
diff --git a/Modules/ado/personal/r/rsoort11.zip b/Modules/ado/personal/r/rsoort11.zip
new file mode 100644
index 0000000..909c7d2
Binary files /dev/null and b/Modules/ado/personal/r/rsoort11.zip differ
diff --git a/Modules/ado/personal/r/rsoort12.ado b/Modules/ado/personal/r/rsoort12.ado
new file mode 100644
index 0000000..9e6ac0f
--- /dev/null
+++ b/Modules/ado/personal/r/rsoort12.ado
@@ -0,0 +1,770 @@
+*! version 1.1 3June2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+* Version 1.1 (2013-06-03): Jean-Benoit Hardouin /*some improvements*/
+* Version 1.2 (2013-06-03): Jean-Benoit Hardouin /*model1 model2 model3 and covariances options*/
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=2 numeric) [if] [in] [,METHod(string) UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch html(string) model1 model2 model4 COVariances(string)]
+tempfile saversoort
+qui save `saversoort',replace
+
+if "`html'" != "" {
+ di ""
+}
+
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+if "`html'"== "" {
+ di _col(20) "{hline 30}"
+ di _col(20) in gr "Time 1" _col(40) "Time 2"
+ di _col(20) "{hline 30}"
+ forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+ }
+ di _col(20) "{hline 30}"
+}
+else {
+ di ""
+ di ""
+ di "Time 1 | Time2 |
"
+ di ""
+ forvalues i=1/`nbitems' {
+ di "``i'' | ``=`i'+`nbitems''' |
"
+ }
+ di "
"
+}
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+if "`model1'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`covariances')
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+local bic1=r(bic)
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+if "`model2'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') `covariances'
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ *di " | | Test of global Response-Shift | Comparison with model 1 |
"
+ di "Models | Chi-square | df | p-value | BIC |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %6.4f `p1' " | " %7.2f `bic1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %6.4f `p2' " | " %7.2f `bic2' " |
"
+ di "
"
+}
+else {
+ di "{hline 51}"
+ di in gr /*_col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"*/
+ di in gr "Models" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 51}"
+ di in gr "Model 1" _col(20) %8.2f in ye `chi21' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
+ di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
+ di "{hline 51}"
+}
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+
+forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `reprioritization'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `reprioritization'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+}
+*matrix list `RS'
+
+if "`search'"=="" {
+
+ if "`html'"=="" {
+ di
+ di "{hline 88}"
+ di in green _col(40) "Model 3"
+ di "{hline 88}"
+ di
+ di in white _col(10) "Non uniform Recalibration"
+ }
+ else {
+ di "
Model 3
"
+ di ""
+ di "Non uniform Recalibration"
+ }
+ local continue=1
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ }
+ local prec_chi2=`chi22'
+ local testNU_varchi2=0
+ local testNU_p=1
+
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') `covariances'
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Uniform recalibration
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Uniform Recalibration"
+ }
+ else {
+ di ""
+ di "Uniform Recalibration"
+ }
+ local continue=1
+ local var
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') `covariances'
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Reprioritization
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Reprioritization"
+ }
+ else {
+ di ""
+ di "Reprioritization"
+ }
+
+ local continue=1
+ local var
+ local sem
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') `covariances'
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | Unavailable |
"
+ }
+ else {
+ di in gr "``j''" _col(20) %8.2f in ye `chi2encours' _col(40) "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') `covariances'
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+local bic3=r(bic)
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+if "`html'"=="" {
+ di
+ di "{hline 74}"
+ di in gr _col(22) "Non uniform" _col(46) "Uniform"
+ di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(58) "Reprioritization"
+ di "{hline 74}"
+}
+else {
+ di ""
+ di ""
+ di "Items | Non-uniform Recalibration | Uniform Recalibration | Repriorisation |
"
+ di ""
+}
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ if "`html'"=="" {
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+ }
+ else {
+ di "``i'' | `recNU' | `recU' | `rep' |
"
+ }
+}
+if "`html'"=="" {
+ di "{hline 74}"
+}
+else {
+ di "
"
+}
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+if "`model4'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) `covariances'
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+local bic4=r(bic)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di "Models | chi2 | df | p | BIC | RMSEA | IC90%(RMSEA) | SRMR | CFI | TLI |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `dfc1' " | " %7.2f `bic1' " | " %6.4f `p1' " | " %6.4f `rmsea1' " | " %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' " | " %6.4f `srmr1' " | " %6.2f `cfi1' " | " %6.2f `tli1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `dfc2' " | " %7.2f `bic2' " | " %6.4f `p2' " | " %6.4f `rmsea2' " | " %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' " | " %6.4f `srmr2' " | " %6.2f `cfi2' " | " %6.2f `tli2' " |
"
+ di "Model 4 | " %8.2f `chi24' " | " %4.0f `dfc4' " | " %7.2f `bic4' " | " %6.4f `p4' " | " %6.4f `rmsea4' " | " %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' " | " %6.4f `srmr4' " | " %6.2f `cfi4' " | " %6.2f `tli4' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 95}"
+ di in gr "Models" _col(14) "chi2" _col(22) "df" _col(31) "p" _col(40) "BIC" _col(47) "RMSEA" _col(55) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+ di "{hline 95}"
+ di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(26) %6.4f `p1' _col(36) %7.2f `bic1' _col(46) %6.4f `rmsea1' _col(54) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+ di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `dfc2' _col(26) %6.4f `p2' _col(36) %7.2f `bic2' _col(46) %6.4f `rmsea2' _col(54) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+ *di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+ di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `dfc4' _col(26) %6.4f `p4' _col(36) %7.2f `bic4' _col(46) %6.4f `rmsea4' _col(54) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+ di "{hline 95}"
+}
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di " | Estimation | s.e. | z | p-value |
"
+ di ""
+ di "True change (Model 2) | " %8.4f `truechange2' " | " %8.4f `=sqrt(`Vtruechange2')' " | " %6.2f `=`truechange2'/sqrt(`Vtruechange2')' " | " %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))' " |
"
+ di "True change (Model 4) | " %8.4f `truechange' " | " %8.4f `=sqrt(`Vtruechange')' " | " %6.2f `=`truechange'/sqrt(`Vtruechange')' " | " %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 77}"
+ di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+ di "{hline 77}"
+ di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+ di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+ di "{hline 77}"
+ di
+}
+qui use `saversoort',clear
+
+
+
+end
diff --git a/Modules/ado/personal/r/rsoort13.ado b/Modules/ado/personal/r/rsoort13.ado
new file mode 100644
index 0000000..41b1284
--- /dev/null
+++ b/Modules/ado/personal/r/rsoort13.ado
@@ -0,0 +1,820 @@
+*! version 1.3 12June2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* rsoort: Response Shift detection with the Oort procedure
+*
+* Historic:
+* Version 1 (2013-02-25): Jean-Benoit Hardouin
+* Version 1.1 (2013-06-03): Jean-Benoit Hardouin /*some improvements*/
+* Version 1.2 (2013-06-03): Jean-Benoit Hardouin /*model1 model2 model3 and covariances options*/
+* Version 1.3 (2013-06-03): Jean-Benoit Hardouin /**/
+*
+*
+* Jean-benoit Hardouin - Department of Biomathematics and Biostatistics - University of Nantes - France
+* EA 4275-SPHERE "bioStatistics, Pharmacoepidemiology and Human sciEnces Research tEam"
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* Copyright 2013 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
+************************************************************************************************************/
+
+
+/***********************************************************************************************************
+INTRODUCTION
+***********************************************************************************************************/
+
+
+program define rsoort,eclass
+syntax varlist(min=2 numeric) [if] [in] [,METHod(string) nocov12 UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch html(string) model1 model2 model4 COVariances(string) MATrixrs(string)]
+tempfile saversoort
+qui save `saversoort',replace
+preserve
+if "`matrixrs'"!="" {
+ if "`uniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:uniformrecalibration} options in the same time"
+ error
+ }
+ if "`nonuniformrecalibration'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:nonuniformrecalibration} options in the same time"
+ error
+ }
+ if "`reprioritization'"!="" {
+ di in red "You cannot use the {bf:matrixrs} and the {bf:reprioritization} options in the same time"
+ error
+ }
+}
+
+
+if "`html'" != "" {
+ di ""
+}
+
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+tokenize `varlist'
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+local nbitems=`nbitems'/2
+
+if "`html'"== "" {
+ di _col(20) "{hline 30}"
+ di _col(20) in gr "Time 1" _col(40) "Time 2"
+ di _col(20) "{hline 30}"
+ forvalues i=1/`nbitems' {
+ di in ye _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+ }
+ di _col(20) "{hline 30}"
+}
+else {
+ di ""
+ di ""
+ di "Time 1 | Time2 |
"
+ di ""
+ forvalues i=1/`nbitems' {
+ di "``i'' | ``=`i'+`nbitems''' |
"
+ }
+ di "
"
+}
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+
+if "`model1'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+local cov12b
+forvalues i=1/`nbitems' {
+ local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
+}
+if "`cov12'"!="" {
+ local cov12b
+}
+`qui' sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''),var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covariances')
+qui estat gof, stat(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+local bic1=r(bic)
+*di
+*di in green " ***********************************Model 1********************************************"
+*di in gr _col(14) "chi2" _col(22) "df" _col(35) "p" _col(41) "rmsea" _col(51) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+*di in ye _col(10) %8.2f `chi21' _col(20) %4.0f `dfc1' _col(30) %6.4f `p1' _col(40) %6.4f `rmsea1' _col(50) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+local sem
+local var
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+}
+
+if "`model2'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange2=`b'[1,`=`nbitems'*4+1']
+local Vtruechange2=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof, stat(all)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+
+local chi221=abs(`chi21'-`chi22')
+local df21=`df2'-`df1'
+local p21=1-chi2(`df21',`chi221')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ *di " | | Test of global Response-Shift | Comparison with model 1 |
"
+ di "Models | Chi-square | df | p-value | BIC |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %6.4f `p1' " | " %7.2f `bic1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %6.4f `p2' " | " %7.2f `bic2' " |
"
+ di "
"
+}
+else {
+ di "{hline 51}"
+ di in gr /*_col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"*/
+ di in gr "Models" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 51}"
+ di in gr "Model 1" _col(20) %8.2f in ye `chi21' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
+ di in gr "Model 2" _col(20) %8.2f in ye `chi22' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
+ di "{hline 51}"
+}
+
+
+/**************************************************************************************************************
+Model 3
+***************************************************************************************************************/
+
+
+/**************************************************************************************************************
+Model 3 / Non uniform recalibration
+***************************************************************************************************************/
+
+tempname RS RSprec
+qui matrix `RS'=J(`nbitems',3,0)
+qui matrix `RSprec'=J(`nbitems',3,0)
+local df3=`dfc2'
+
+*set trace on
+
+if "`matrixrs'"=="" {
+ forvalues i=1/`nbitems' {
+ local nbUR:word count `uniformrecalibration'
+ forvalues j=1/`nbUR' {
+ local itemj: word `j' of `uniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',2]=1
+ }
+ }
+ local nbNUR:word count `nonuniformrecalibration'
+ forvalues j=1/`nbNUR' {
+ local itemj: word `j' of `nonuniformrecalibration'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',1]=1
+ }
+ }
+ local nbR:word count `reprioritization'
+ forvalues j=1/`nbR' {
+ local itemj: word `j' of `reprioritization'
+ if "``i''"=="`itemj'" {
+ matrix `RS'[`i',3]=1
+ }
+ }
+ }
+}
+else {
+ matrix `RS'=`matrixrs'
+}
+*matrix list `RS'
+
+if "`search'"=="" {
+
+ if "`html'"=="" {
+ di
+ di "{hline 88}"
+ di in green _col(40) "Model 3"
+ di "{hline 88}"
+ di
+ di in white _col(10) "Non uniform Recalibration"
+ }
+ else {
+ di "
Model 3
"
+ di ""
+ di "Non uniform Recalibration"
+ }
+ local continue=1
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ }
+ local prec_chi2=`chi22'
+ local testNU_varchi2=0
+ local testNU_p=1
+
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testNU_varchi2_temp=0
+ local testNU_p_temp=0
+ local testNU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ local var
+ forvalues j=1/`nbitems' {
+ local sem
+ local var
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',1]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `var`i''
+ }
+ if `RS'[`i',1]==1&`i'!=`j' {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==0 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ }
+ else if `i'==`j'&`RS'[`j',1]==1 {
+ local sem `sem' `sem`i''
+ local var `var' `varrecNU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testNU_varchi2_temp') {
+ local continue=1
+ local testNU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testNU_p_temp =1-chi2(1,`testNU_varchi2_temp')
+ local testNU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testNU_item_temp'!=0) {
+ matrix `RS'[`testNU_item_temp',1]=1
+ local ++df3
+ local testNU_varchi2=`testNU_varchi2_temp'
+ local testNU_p=`testNU_p_temp'
+ local testNU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Uniform recalibration
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Uniform Recalibration"
+ }
+ else {
+ di ""
+ di "Uniform Recalibration"
+ }
+ local continue=1
+ local var
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testU_varchi2_temp=0
+ local testU_p_temp=0
+ local testU_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ if `RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==0 {
+ local sem `sem' `semrecU`i''
+ }
+ else if `i'==`j'&`RS'[`j',2]==1 {
+ local sem `sem' `semrecU`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testU_varchi2_temp') {
+ local continue=1
+ local testU_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testU_p_temp =1-chi2(1,`testU_varchi2_temp')
+ local testU_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testU_item_temp'!=0) {
+ matrix `RS'[`testU_item_temp',2]=1
+ local ++df3
+ local testU_varchi2=`testU_varchi2_temp'
+ local testU_p=`testU_p_temp'
+ local testU_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+
+
+
+
+ /**************************************************************************************************************
+ Model 3 / Reprioritization
+ ***************************************************************************************************************/
+
+ if "`html'"=="" {
+ di
+ di in white _col(10) "Reprioritization"
+ }
+ else {
+ di ""
+ di "Reprioritization"
+ }
+
+ local continue=1
+ local var
+ local sem
+ forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ }
+ local testU_varchi2=0
+ local testU_p=1
+ if "`html'"=="" {
+ di "{hline 88}"
+ di in gr _col(59) "Comparison with previous model"/* _col(79) "Comparison with model 1"*/
+ di in gr "Items" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" _col(59) "Chi-square" _col(73) "df" _col(82) "p-value" /*_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 88}"
+ }
+ else {
+ di " | | | | | Comparison with previous model |
"
+ di "Items | Chi-square | df | p-value | BIC | Chi-square | df | p-value |
"
+ di ""
+ }
+
+ while (`continue') {
+ local cpt=0
+ local testR_varchi2_temp=0
+ local testR_p_temp=0
+ local testR_item_temp=0
+ local chi2encours_temp=-1
+ local continue=0
+ local sem
+ forvalues j=1/`nbitems' {
+ local sem
+ local already=0
+ forvalues i=1/`nbitems' {
+ if `RS'[`i',3]==0&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `sem`i''
+ }
+ else if `RS'[`i',3]==0&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecU`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==0&`i'!=`j' {
+ local sem `sem' `semrep`i''
+ }
+ else if `RS'[`i',3]==1&`RS'[`i',2]==1&`i'!=`j' {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==0 {
+ local sem `sem' `semrecUrep`i''
+ }
+ else if `i'==`j'&`RS'[`j',3]==0&`RS'[`i',2]==1&`RS'[`i',1]==1 {
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==0 {
+ local sem `sem' `semrep`i''
+ local already=1
+ }
+ else if `i'==`j'&`RS'[`j',3]==1&`RS'[`i',2]==1 {
+ local sem `sem' `semrecUrep`i''
+ local already=1
+ }
+ }
+ if (`already'!=1) {
+ qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+ qui estat gof
+ local chi2encours=r(chi2_ms)
+ local dfencours=r(df_ms)
+ local pencours=r(p_ms)
+ local bicencours=r(bic)
+ if (abs(`chi2encours'-`prec_chi2')>invchi2(1,0.95)&abs(`chi2encours'-`prec_chi2')>`testR_varchi2_temp'&`chi2encours'<`prec_chi2') {
+ local continue=1
+ local testR_varchi2_temp =abs(`chi2encours'-`prec_chi2' )
+ local testR_p_temp =1-chi2(1,`testR_varchi2_temp')
+ local testR_item_temp=`j'
+ local chi2encours_tmp=`chi2encours'
+ local tmp=`chi2encours'
+ }
+ if ( `chi2encours'<`prec_chi2') {
+ if "`html'" != "" {
+ di "``j'' | " %8.2f `chi2encours' " | " %4.0f `dfencours' " | " %6.4f `pencours' " | " %7.2f `bicencours' " | " %8.2f `=abs(`chi2encours'-`prec_chi2' )' " | 1 | " %6.4f `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' " |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(20) %8.2f in ye `chi2encours' _col(30) %4.0f `dfencours' _col(37) %6.4f `pencours' _col(45) %7.2f `bicencours' _col(61) %8.2f `=abs(`chi2encours'-`prec_chi2' )' _col(74) "1" %6.4f _col(83) `=1-chi2(1,abs(`chi2encours'-`prec_chi2' ))' /*_col(82) %8.2f `=abs(`chi2encours'-`chi21')' _col(90) %6.0f `=abs(`df3'+1-`dfc1')' _col(100) %6.4f `=1-chi2(abs(`df3'+1-`dfc1'),abs(`chi2encours'-`chi21'))'*/
+ }
+ }
+ else {
+ if "`html'" != "" {
+ di "``j'' | Unavailable |
"
+ }
+ else {
+ di in gr abbrev("``j''",14) _col(17) in ye /*%8.2f in ye `chi2encours' _col(40)*/ "Unavailable"
+ }
+ }
+ local ++cpt
+ }
+ }
+ if (`testR_item_temp'!=0) {
+ matrix `RS'[`testR_item_temp',3]=1
+ local ++df3
+ local testR_varchi2=`testR_varchi2_temp'
+ local testR_p=`testR_p_temp'
+ local testR_item_temp=0
+ local prec_chi2=`tmp'
+ }
+ if (`cpt'!=0) {
+ if "`html'" != "" {
+ di "
|
"
+ }
+ else {
+ di "{hline 88}"
+ }
+ }
+ }
+ if "`html'" != "" {
+ di "
"
+ }
+}
+
+/**************************************************************************************************************
+Model 3 Final
+***************************************************************************************************************/
+
+di
+local continue=1
+local var
+local sem
+forvalues i=1/`nbitems' {
+ local sem`i' "(T1@load`i' _cons@int`i'->``i'') (T2@load`i' _cons@int`i'->``=`i'+`nbitems''')"
+ local semrecU`i' "(T1@load`i' _cons->``i'') (T2@load`i' _cons->``=`i'+`nbitems''')"
+ local semrecUrep`i' "(T1 _cons->``i'') (T2 _cons->``=`i'+`nbitems''')"
+ local semrep`i' "(T1 _cons@int`i'->``i'') (T2 _cons@int`i'->``=`i'+`nbitems''')"
+ local var`i' "var(e.``i''@var`i') var(e.``=`i'+`nbitems'''@var`i')"
+ local varrecNU`i' "var(e.``i'') var(e.``=`i'+`nbitems''')"
+ if `RS'[`i',1]==1 {
+ local var "`var' `varrecNU`i''"
+ }
+ if `RS'[`i',1]==0 {
+ local var "`var' `var`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==0 {
+ local sem "`sem' `sem`i''"
+ }
+ if `RS'[`i',2]==0&`RS'[`i',3]==1 {
+ local sem "`sem' `semrep`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==0 {
+ local sem "`sem' `semrecU`i''"
+ }
+ if `RS'[`i',2]==1&`RS'[`i',3]==1 {
+ local sem "`sem' `semrecUrep`i''"
+ }
+}
+qui sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) method(`method') cov(`cov12b' `covariances')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof
+local tli3=r(tli)
+local cfi3=r(cfi)
+local srmr3=r(srmr)
+local rmsea3=r(rmsea)
+local ubrmsea3=r(ub90_rmsea)
+local lbrmsea3=r(lb90_rmsea)
+local chi23=r(chi2_ms)
+local dfc3=`df3'
+local p3=r(p_ms)
+local bic3=r(bic)
+
+
+/**************************************************************************************************************
+Bilan
+***************************************************************************************************************/
+
+if "`html'"=="" {
+ di
+ di "{hline 74}"
+ di in gr _col(22) "Non uniform" _col(46) "Uniform"
+ di in gr "Items" _col(20) "Recalibration" _col(40) "Recalibration" _col(58) "Reprioritization"
+ di "{hline 74}"
+}
+else {
+ di ""
+ di ""
+ di "Items | Non-uniform Recalibration | Uniform Recalibration | Repriorisation |
"
+ di ""
+}
+forvalues i=1/`nbitems' {
+ local recNU
+ local recU
+ local rep
+ if (`RS'[`i',1]==1) {
+ local recNU "*"
+ }
+ if (`RS'[`i',2]==1) {
+ local recU "*"
+ }
+ if (`RS'[`i',3]==1) {
+ local rep "*"
+ }
+ if "`html'"=="" {
+ di in gr "``i''" in ye _col(32) "`recNU'" _col(52) "`recU'" _col(73) "`rep'"
+ }
+ else {
+ di "``i'' | `recNU' | `recU' | `rep' |
"
+ }
+}
+if "`html'"=="" {
+ di "{hline 74}"
+}
+else {
+ di "
"
+}
+
+
+/**************************************************************************************************************
+Model 4
+***************************************************************************************************************/
+
+if "`model4'"=="" {
+ local qui qui
+}
+else {
+ local qui
+}
+`qui' sem `sem',var(T1@1) var(T2) means(T1@0) means(T2) `var' iterate(100) cov(`cov12b' `covariances') method(`method')
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+local truechange=`b'[1,`=`nbitems'*4+1']
+local Vtruechange=`V'[`=`nbitems'*4+1',`=`nbitems'*4+1']
+qui estat gof,stat(all)
+local tli4=r(tli)
+local cfi4=r(cfi)
+local srmr4=r(srmr)
+local rmsea4=r(rmsea)
+local ubrmsea4=r(ub90_rmsea)
+local lbrmsea4=r(lb90_rmsea)
+local chi24=r(chi2_ms)
+local df4=r(df_ms)
+local dfc4=`df3'+1
+local p4=r(p_ms)
+local chi2encours=r(chi2_ms)
+local bic4=r(bic)
+
+local z=`truechange'/sqrt(`Vtruechange')
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di "Models | chi2 | df | p | BIC | RMSEA | IC90%(RMSEA) | SRMR | CFI | TLI |
"
+ di ""
+ di "Model 1 | " %8.2f `chi21' " | " %4.0f `df1' " | " %7.2f `bic1' " | " %6.4f `p1' " | " %6.4f `rmsea1' " | " %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' " | " %6.4f `srmr1' " | " %6.2f `cfi1' " | " %6.2f `tli1' " |
"
+ di "Model 2 | " %8.2f `chi22' " | " %4.0f `df2' " | " %7.2f `bic2' " | " %6.4f `p2' " | " %6.4f `rmsea2' " | " %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' " | " %6.4f `srmr2' " | " %6.2f `cfi2' " | " %6.2f `tli2' " |
"
+ di "Model 4 | " %8.2f `chi24' " | " %4.0f `df4' " | " %7.2f `bic4' " | " %6.4f `p4' " | " %6.4f `rmsea4' " | " %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' " | " %6.4f `srmr4' " | " %6.2f `cfi4' " | " %6.2f `tli4' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 95}"
+ di in gr "Models" _col(14) "chi2" _col(22) "df" _col(31) "p" _col(40) "BIC" _col(47) "RMSEA" _col(55) "IC90%(RMSEA)" _col(72) "SRMR" _col(83) "CFI" _col(93) "TLI"
+ di "{hline 95}"
+ di in green "Model 1" in ye _col(10) %8.2f `chi21' _col(20) %4.0f `df1' _col(26) %6.4f `p1' _col(36) %7.2f `bic1' _col(46) %6.4f `rmsea1' _col(54) %6.4f `lbrmsea1' "-" %6.4f `ubrmsea1' _col(70) %6.4f `srmr1' _col(80) %6.2f `cfi1' _col(90) %6.2f `tli1'
+ di in green "Model 2" in ye _col(10) %8.2f `chi22' _col(20) %4.0f `df2' _col(26) %6.4f `p2' _col(36) %7.2f `bic2' _col(46) %6.4f `rmsea2' _col(54) %6.4f `lbrmsea2' "-" %6.4f `ubrmsea2' _col(70) %6.4f `srmr2' _col(80) %6.2f `cfi2' _col(90) %6.2f `tli2'
+ *di in green "Model 3" in ye _col(10) %8.2f `chi23' _col(20) %4.0f `dfc3' _col(30) %6.4f `p3' _col(40) %6.4f `rmsea3' _col(50) %6.4f `lbrmsea3' "-" %6.4f `ubrmsea3' _col(70) %6.4f `srmr3' _col(80) %6.2f `cfi3' _col(90) %6.2f `tli3'
+ di in green "Model 4" in ye _col(10) %8.2f `chi24' _col(20) %4.0f `df4' _col(26) %6.4f `p4' _col(36) %7.2f `bic4' _col(46) %6.4f `rmsea4' _col(54) %6.4f `lbrmsea4' "-" %6.4f `ubrmsea4' _col(70) %6.4f `srmr4' _col(80) %6.2f `cfi4' _col(90) %6.2f `tli4'
+ di "{hline 95}"
+}
+
+
+if "`html'" != "" {
+ di ""
+ di ""
+ di " | Estimation | s.e. | z | p-value |
"
+ di ""
+ di "True change (Model 2) | " %8.4f `truechange2' " | " %8.4f `=sqrt(`Vtruechange2')' " | " %6.2f `=`truechange2'/sqrt(`Vtruechange2')' " | " %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))' " |
"
+ di "True change (Model 4) | " %8.4f `truechange' " | " %8.4f `=sqrt(`Vtruechange')' " | " %6.2f `=`truechange'/sqrt(`Vtruechange')' " | " %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))' " |
"
+ di "
"
+}
+else {
+ di
+ di "{hline 77}"
+ di _col(23) in gr "Estimation" _col(44) "s.e." _col(60) "z" _col(71) "p-value"
+ di "{hline 77}"
+ di in gr "True change (Model 2)" in ye _col(25) %8.4f `truechange2' _col(40) %8.4f `=sqrt(`Vtruechange2')' _col(56) %6.2f `=`truechange2'/sqrt(`Vtruechange2')' _col(72) %6.4f `=2-2*normal(abs(`truechange2')/sqrt(`Vtruechange2'))'
+ di in gr "True change (Model 4)" in ye _col(25) %8.4f `truechange' _col(40) %8.4f `=sqrt(`Vtruechange')' _col(56) %6.2f `=`truechange'/sqrt(`Vtruechange')' _col(72) %6.4f `=2-2*normal(abs(`truechange')/sqrt(`Vtruechange'))'
+ di "{hline 77}"
+ di
+}
+qui use `saversoort',clear
+
+
+
+end
diff --git a/Modules/ado/personal/r/rsoortBP.ado b/Modules/ado/personal/r/rsoortBP.ado
new file mode 100644
index 0000000..0befedd
--- /dev/null
+++ b/Modules/ado/personal/r/rsoortBP.ado
@@ -0,0 +1,2208 @@
+/*
+Regarder si les modĂšles convergent dans la partie 1
+Prévoir le cas du cross loading (=> numéro des contraintes, etc)
+*/
+
+capture program drop rsoortBP
+program define rsoortBP,rclass
+syntax varlist(min=2 numeric) [if] [in], PARTition(numlist) [lt(string) METHod(string) UNIFormrecalibration(varlist) NONUNIFormrecalibration(varlist) REPrioritization(varlist) noSearch CFARmsea(real -999) CFACfi(real -999) CFAOR iterate(integer 100) onlycovl Test Hierarchical sb adjust Group(varlist) trace *]
+version 15
+
+preserve
+
+//rename *, lower
+
+local P:word count `partition'
+local S:word count `lt'
+
+if "`lt'" != "" {
+ if `P'!=`S' {
+ di in red "The number of arguments in lt() must be equal to the number of arguments in partition()"
+ exit 119
+ }
+ else {
+ tokenize `lt'
+ forvalues i = 1/`S' {
+ local ltname`i' = "``i''"
+ }
+ }
+}
+else {
+ forvalues i = 1/`P' {
+ local ltname`i' = "LT`i'"
+ }
+}
+
+
+
+
+order `varlist'
+
+if "`trace'" != "" {
+ local qui ""
+}
+else {
+ local qui "qui"
+}
+
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+tokenize `varlist'
+
+local nbitems:word count `varlist'
+
+*di "`varlist'"
+local varlist
+forvalues i=1/`nbitems' {
+ //di "``i''"
+ capture rename ``i'', lower
+ local low = lower("``i''")
+ local var`i' = `low'
+ local varlist `varlist' `low'
+}
+tokenize `varlist'
+*di "`varlist'"
+
+/*
+local i = 1
+foreach x in `varlist' {
+ local var`i' = lower("`x'")
+ di "ok"
+ rename `x' `var`i''
+ local ++i
+}
+*/
+local nbitems:word count `varlist'
+local mod=mod(`nbitems',2)
+if `mod'!=0 {
+ di in red "You must enter an even number of items : the first half of the items represents the items in time 1 and the second half the items in time 2"
+ error
+}
+local nbitems=`nbitems'/2
+
+local nbdims:word count `partition'
+
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+
+if `C' != `nbitems' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables specified in varlist"
+ exit 119
+}
+
+
+
+if `cfarmsea' == -999{
+ local cfarmsea
+}
+if `cfacfi' == -999{
+ local cfacfi
+}
+
+if "`method'"=="" {
+ local method "ml"
+}
+
+local i = 1
+local j = 0
+foreach p in `partition' {
+ local part`i' = `p'+`j'
+ local ++i
+ local j = `j'+`p'
+
+}
+
+if "`sb'" != "" {
+ local sb = "vce(sbentler)"
+}
+
+
+di as result _col(20) "{hline 35}"
+di as text _col(20) "Time 1" _col(40) "Time 2"
+di as text _col(20) "{hline 35}"
+local j = 1
+forvalues i=1/`nbitems' {
+ *set trace on
+ if (!missing("`part`j''")) {
+ if (`i' ==1|`i'==`=`part`j''+1') {
+ if `i'!=1 local ++j
+ di _col(20) "`ltname`j''" _col(40) "`ltname`j''"
+ }
+ }
+ *set trace off
+ di _col(20) "``i''" _col(40) "``=`i'+`nbitems'''"
+}
+di as result _col(20) "{hline 35}"
+
+
+/**************************************************************************************************************
+DIF time 1 (if "group" is option specified)
+***************************************************************************************************************/
+
+
+ /**************************************************************************************************************
+ DIF : Model A
+ ***************************************************************************************************************/
+
+
+
+if "`group'" !="" {
+
+
+
+
+tokenize `varlist'
+
+local ii = 1
+local s
+local stop = 0
+local i = 1
+
+
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local ++i
+}
+
+local i = 1
+foreach x in `partition' {
+ local part`i' = `x'
+}
+
+//tokenize `varlist'
+forvalues i=1/`nbitems' {
+ local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
+}
+
+//di "`varlist'"
+
+local k = 1
+local i = 1
+local j = 0
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while (`j'<`pp') {
+ local bloca`k' `bloca`k'' `var`i''
+ local blocb`k' `blocb`k'' `var`=`i'+`nbitems'''
+ //di "`var`i''"
+ local i = `i'+1
+ local j = `j'+1
+ }
+ //di in red `j'
+ //order `var`j''-`var`pp''
+ //order `var`=`j'+`nbitems'''-`var`=`pp'+`nbitems'''
+
+
+ local ++k
+}
+
+di "`bloca1'"
+di "`bloca2'"
+di "`blocb1'"
+di "`blocb2'"
+
+
+
+local i = 1
+local j = 1
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ local s `s' (L`i'_1 -> `bloca`i'')
+ local cl `cl' means(L`i'_1@0) var(L`i'_1@1)
+ forvalues k = 1/`=`nbdims'-1' {
+ if (`=`i'+`k''<=`nbdims') {
+ local covl `covl' L`i'_1*L`=`i'+`k''_1
+ }
+ }
+
+ local j = `pp'+1
+ local i = `i'+1
+}
+
+
+
+local z "`s', `cl' iterate(`iterate') method(`method') `sb' group(`group') ginvariant(covex)"
+
+di in red "DIF : model A (without search for modification indices)"
+
+di as text "sem `z' "
+
+sem `z'
+
+est store modelAwo
+
+if "`cfarmsea'"!="" {
+ local stoprmsea=0
+ while `stoprmsea'==0 {
+ qui estat gof
+ di in red "rmsea="round(`r(rmsea)',0.001)
+ if r(rmsea)<`cfarmsea' {
+ local stoprmsea = 1
+ }
+ else {
+ estat mindices, showpclass(merrvar)
+ tempvar rname chi df p ccovnum
+ mat m = r(mindices)
+ matrix m2 = m[.,1..3]
+ svmat2 m2 , rnames(`rname') names(`chi' `df' `p') full
+ gsort -`chi'
+ local nrows = rowsof(m2)
+ gen `ccovnum' = _n
+ list `ccovnum' `rname' `chi' in 1/`nrows'
+
+ local num = `ccovnum'[1]
+ constraint get `num'
+ local c`num' = r(contents)
+ di "`c`num''"
+ constraint drop `num'
+
+ *if (mĂȘme dimension) {
+ local coverror = `rnames'[1]
+ di "`coverror'"
+ *}
+ constraint 1001 [/]cov(L1_1,L2_1)#0bn.grp_v1 - [/]cov(L1_1,L2_1)#1.grp_v1 = 0
+
+ }
+ }
+
+
+
+
+
+
+ stop
+}
+
+
+
+
+
+
+
+
+
+
+ /**************************************************************************************************************
+ DIF : Model B
+ ***************************************************************************************************************/
+
+levelsof `group', local(levs)
+tokenize `levs'
+local length = wordcount("`levs'")
+forvalues l = 1/`length' {
+ local level`l' = ``l''
+}
+local l
+
+local i = 1
+local j = 1
+local pp = 0
+local s
+local cl
+foreach p in `partition' {
+ local l = 1
+ local pp = `pp'+`p'
+ local s `s' (L`i'_1 -> `bloca`i'')
+ local cl `cl' means(`level1':L`i'_1@0) var(`level1':L`i'_1@1)
+ forvalues k = 1/`=`nbdims'-1' {
+ if (`=`i'+`k''<=`nbdims') {
+ local covl `covl' L`i'_1*L`=`i'+`k''_1
+ }
+ }
+
+ local j = `pp'+1
+ local i = `i'+1
+}
+
+
+
+/* définition des contraintes */
+
+constraint drop _all
+tokenize `varlist'
+
+local c = 1
+local i = 1
+local j = 1
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while `j'<= `pp' {
+ constraint `c' [``j'']`level1'bn.`group'#c.L`i'_1 - [``j'']`level2'.`group'#c.L`i'_1 = 0
+ local ++j
+ local ++c
+ }
+ local ++i
+}
+
+local i = 1
+foreach v of varlist `varlist' {
+ if `i'<=`nbitems' {
+ constraint `c' [``i'']`level1'bn.`group' - [``i'']`level2'bn.`group' = 0
+ local ++c
+ local ++i
+ }
+}
+
+local i = 1
+foreach v of varlist `varlist' {
+ if `i'<=`nbitems' {
+ constraint `c' [/]var(e.``i'')#`level1'bn.`group' - [/]var(e.``i'')#`level2'bn.`group' = 0
+ local ++c
+ local ++i
+ }
+}
+
+
+
+constraint list
+
+
+
+
+
+//local z "`s', `cl' iterate(`iterate') method(`method') `sb' group(`group') ginvariant(mcoef mcons merrvar) noanchor forcenoanchor"
+//local z "`s', `cl' iterate(`iterate') method(`method') `sb' group(`group') ginvariant(covex) constraints(1/`=`nbitems'*3')"
+//local z "`s', `cl' iterate(`iterate') method(`method') `sb' group(`group') ginvariant(mcoef mcons merrvar ) constraints(`=`nbitems'+1'/`=`nbitems'*3') noanchor forcenoanchor"
+local z "`s', `cl' iterate(`iterate') method(`method') `sb' group(`group') ginvariant(mcoef) noanchor forcenoanchor"
+
+di in red "DIF : model B"
+
+di as text "sem `z' constraints(`=`nbitems'+1'/`=`nbitems'*3') "
+
+sem `z' constraints(1/`=`nbitems'*3')
+
+est store modelB
+est store modelBref
+
+lrtest modelA modelB
+
+
+if r(p) < 0.05 {
+local stop = 0
+
+while (`stop'!=1) {
+
+ estat ginvariant, showpclass(mcoef mcons merrvar)
+ qui ret li
+ matrix m = r(test)
+ matrix m2 = m[.,4..6]
+ tempvar number rname chi df p
+ svmat2 m2, rnames(`rname') names(`chi' `df' `p') full
+ gen `number' = .
+ local c = 1
+ forvalues i = 1(2)`=`nbitems'*2' {
+ qui replace `number' = `c' in `i'
+ local ++c
+ }
+
+ local c = `=`nbitems'+1'
+ forvalues i = 2(2)`=`nbitems'*2' {
+ qui replace `number' = `c' in `i'
+ local ++c
+ }
+
+ local c = `=`nbitems'*2+1'
+ forvalues i = `=`nbitems'*2+1'/`=`nbitems'*3' {
+ qui replace `number' = `c' in `i'
+ local ++c
+ }
+
+ qui sort `p'
+ list `number' `rname' `chi' `df' `p' in 1/`=`nbitems'*3'
+ //list `number' `p'
+ local num = `number'[1]
+ //di `num'
+ constraint get `num'
+ local c`num' = r(contents)
+ di "`c`num''"
+ constraint drop `num'
+ constraint list _all
+
+ di in red "ModÚle aprÚs avoir retiré `c`num''"
+
+ sem `z' constraints(1/`=`nbitems'*3')
+
+ est store modelBtest
+ lrtest modelBref modelBtest
+
+ if r(p) >= 0.05 {
+ local stop = 1
+ }
+ else {
+ est store modelBref
+ di in red "donc on retire `c`num''"
+ }
+
+ *estat ginvariant, showpclass(mcoef mcons merrvar)
+
+}
+
+} // fin if LRT < 0.05
+
+
+/*************************************************************************************************************
+Model 1
+**************************************************************************************************************/
+
+
+stop
+} // fin if(group)
+
+
+
+
+/*************
+Response-Shift
+*************/
+
+
+/**************************************************************************************************************
+Model 1
+***************************************************************************************************************/
+tokenize `varlist'
+
+local ii = 1
+local s
+local stop = 0
+local i = 1
+
+
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local ++i
+}
+
+local i = 1
+foreach x in `partition' {
+ local part`i' = `x'
+}
+
+forvalues i=1/`nbitems' {
+ local cov12b `cov12b' e.``i''*e.``=`i'+`nbitems'''
+}
+
+local k = 1
+local i = 1
+local j = 0
+local pp = 0
+local cl
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while (`j'<`pp') {
+ local bloca`k' `bloca`k'' `var`i''
+ local blocb`k' `blocb`k'' `var`=`i'+`nbitems'''
+ //di "`var`i''"
+ local i = `i'+1
+ local j = `j'+1
+ }
+ //di in red `j'
+ //order `var`j''-`var`pp''
+ //order `var`=`j'+`nbitems'''-`var`=`pp'+`nbitems'''
+
+
+ local ++k
+}
+
+
+local i = 1
+local j = 1
+local pp = 0
+local s
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ local s `s' (L`i'_1 -> `bloca`i'') (L`i'_2 -> `blocb`i'')
+ local cl `cl' means(L`i'_1@0) means(L`i'_2@0) var(L`i'_1@1) var(L`i'_2@1)
+ local covl `covl' L`i'_1*L`i'_2
+ forvalues k = 1/`=`nbdims'-1' {
+ if (`=`i'+`k''<=`nbdims') {
+ local covl `covl' L`i'_1*L`=`i'+`k''_1 L`i'_2*L`=`i'+`k''_2 // uniquement mĂȘme trait latent ou mĂȘme temps
+ //local covl `covl' L`i'_1*L`=`i'+`k''_1 L`i'_2*L`=`i'+`k''_2 L`i'_1*L`=`i'+`k''_2
+ }
+ }
+
+ local j = `pp'+1
+ local i = `i'+1
+}
+
+
+if "`onlycovl'" != "" {
+ local z "`s', covstruct(_lexogenous, diagonal) `cl' cov(`cov12b' `covl') iterate(`iterate') method(`method') `sb'"
+}
+else {
+ local z "`s', `cl' cov(`cov12b') iterate(`iterate') method(`method') `sb'"
+}
+
+
+//local z1 "`s', covstruct(_lexogenous, diagonal) cov(`cov12b' `covl') iterate(`iterate') method(`method') `sb'"
+
+`qui' di "sem `z'"
+
+di as result "Step 1: Measurement model"
+di as text "Model 1 estimation..."
+
+qui sem `z'
+
+//ll
+
+
+
+qui est store model1
+
+
+//local s "sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''), var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covs')"
+//sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''), var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covs') iterate(`iterate') nolog
+
+//estat gof, stat(all)
+
+
+if ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+
+while (`ii' == 1 | "`e'" != "") & `stop'!=1 {
+ if `ii' == 1 & ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ di
+ di _n "{bf:step 1:} {text:(model 1 without auto-search of modification indices)}"
+ }
+
+ if "`covs'" != "" & ("`cfarmsea'"!="" | "`cfacfi'"!=""){
+ di _n "{bf:step `ii':} {text:`covsi'}"
+ }
+ local covsi
+
+ /* Model 1 without covariances between errors */
+
+ qui sem `z' cov(`covs')
+ est store model1
+ //qui sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''), var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covs') iterate(`iterate') nolog
+ qui estat gof, stat(all)
+
+ /* Looking for modification indices */
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ local stoprmsea = 0
+ local stopcfi = 0
+ if "`cfarmsea'"!="" {
+ qui estat gof
+ di "rmsea =" round(r(rmsea),0.001)
+ if r(rmsea)<=`cfarmsea' {
+ local stoprmsea = 1
+ }
+ //else local stoprmsea = 0
+ }
+ else local stoprmsea = 1
+ if "`cfacfi'"!="" {
+ qui estat gof
+ di "cfi =" round(r(cfi),0.001)
+ if r(cfi)>=`cfacfi' {
+ local stopcfi = 1
+ }
+ //else local stopcfi = 0
+ }
+ else local stopcfi = 1
+
+
+
+ /* OR */
+ if "`cfaor'"!="" {
+ if `stoprmsea'==1 | `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ /* AND */
+ if "`cfaor'"=="" {
+ if `stoprmsea'==1 & `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ }
+
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") & `stop'!=1 {
+ qui estat mindices, showpclass(mcons merrvar)
+ tempname mm nomcol
+ mat `mm' = r(mindices)
+ //mat li `mm'
+
+ svmat2 `mm' , r(`nomcol') full
+ gsort - `mm'1
+
+ local nrows = rowsof(`mm')
+
+ local y = 1
+ local i = 0
+ //local partition `nbitems' `nbitems'
+ foreach x of numlist `partition' {
+ local ++i
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues w = `y'/`s' {
+ local class_`var`w'' = `i'
+ local class_`var`=`w'+`nbitems''' = `i'+`nbitems'
+ *di "`var`w''"
+ *di "`class_`var`w'''"
+ *di "`var`=`w'+`nbitems'''"
+ *di "`class_`var`=`w'+`nbitems''''"
+ }
+ local y = `s'+1
+ }
+
+ local f1b
+ local f2b
+ local f
+ local f1
+ local f2
+ forvalues i = 1/`nrows' {
+ local tmp3=`nomcol'[`i']
+ lstrfun e, subinstr("`tmp3'","cov(","",.)
+ lstrfun e, subinstr("`e'","/","",.)
+ lstrfun e, subinstr("`e'",")","",.)
+ lstrfun e, subinstr("`e'",":_cons","",.)
+ lstrfun e, subinstr("`e'",",","*",.)
+
+ lstrfun d, subinstr("`e'",","," ",.)
+ lstrfun d, subinstr("`d'","e.","",.)
+ lstrfun d, subinstr("`d'","*"," ",.)
+
+ qui replace `nomcol' = "`d'" in `i'
+
+ local d = `nomcol'[`i']
+
+ //tokenize "`d'"
+ local v1 = substr("`d'",1,strpos("`d'", " "))
+ local v2 = substr("`d'",strpos("`d'", " ")+1,.)
+
+
+
+
+ if ("`class_`v1''" != "`class_`v2''") /*| (`class_`v1'' > `nbitems') */ { /*** enlever le | si on cherche aussi au temps2 ***/
+ qui replace `nomcol' = "" in `i'
+ }
+
+ local tmp3=`nomcol'[`i']
+
+
+ if "`tmp3'" != "" {
+ //di in red "`tmp3'"
+ local e1 = substr("`tmp3'",1,strpos("`tmp3'", " ")-1)
+ local e2 = substr("`tmp3'",strpos("`tmp3'", " ")+1,.)
+ local ni = `nbitems'*2
+ forvalues jj = 1/`ni' {
+ if `jj' <= `nbitems' {
+
+ if "`e1'" == "``jj''" {
+ local f1 = "``jj''"
+ local f1b = "``=`jj'+`nbitems'''"
+ }
+ if "`e2'" == "``jj''" {
+ local f2 = "``jj''"
+ local f2b = "``=`jj'+`nbitems'''"
+ }
+ }
+ else if `jj' > `nbitems' { /*** remettre si on cherche aussi au temps2 ***/
+ if "`e1'" == "``jj''" {
+ local f1 = "``jj''"
+ local f1b = "``=`jj'-`nbitems'''"
+ //di in red "`f1b'"
+
+ }
+ if "`e2'" == "``jj''" {
+ local f2 = "``jj''"
+ local f2b = "``=`jj'-`nbitems'''"
+ }
+ }
+
+ }
+ if "`f1b'"!="" & "`f2b'"!="" {
+ local f = "e.`f1b'*e.`f2b'"
+ //di in red "`f' en plus de `e'"
+ }
+
+
+ continue, break
+ }
+ else {
+ local e
+ local f
+ local f1b
+ local f2b
+ }
+ }
+
+ local covsi "`e' (`f') "
+ local covs `covs' `e' `f'
+ local f
+ drop `mm'1-`nomcol'
+
+ }
+
+ //if e(converged) == 0 di in red "Warning : model did not converge after 50 iterations"
+ local ++ii
+
+}
+
+}
+
+
+
+/* Model 1 final */
+
+
+//di "{bf:Model 1 (step 1):}"
+//local s "sem (T1->`1'-``nbitems'')(T2->``=`nbitems'+1''-``=`nbitems'*2''), var(T1@1) var(T2@1) means(T1@0) means(T2@0) method(`method') cov(`cov12b' `covs') "
+//di as text "`s'"
+//di "sem `z' cov(`covs')"
+local sem1 `z' cov(`covs')
+//sem
+
+//est replay model1
+
+qui estat gof, stats(all)
+local tli1=r(tli)
+local cfi1=r(cfi)
+local srmr1=r(srmr)
+local rmsea1=r(rmsea)
+local ubrmsea1=r(ub90_rmsea)
+local lbrmsea1=r(lb90_rmsea)
+local chi21=r(chi2_ms)
+local df1=r(df_ms)
+local dfc1=6*`nbitems'+1
+local p1=r(p_ms)
+local bic1=r(bic)
+
+if "`sb'" != "" {
+ local cmodel1 = e(sbc_ms)
+ //local chi21=r(chi2_ms)
+}
+
+//di in red `chi21'
+
+*di as text "End of step 1"
+
+
+/**************************************************************************************************************
+Model 2
+***************************************************************************************************************/
+
+di
+if "`test'" != "" {
+ di as result "Step 2: Overall test of response shift"
+}
+else {
+ di as result "Step 2: Estimation of ""no response shift"" model (no overall test is performed because the ""test"" option was not specified)"
+}
+di as text "Model 2 estimation..."
+
+local i = 1
+local j = 1
+local pp = 0
+local s
+local k = 1
+local var
+local cl
+local covl
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while `j'<= `pp' {
+ local s `s' (L`i'_1@load`k' _cons@int`k' -> `var`j'') (L`i'_2@load`k' _cons@int`k' -> `var`=`j'+`nbitems''')
+ local var `var' var(e.`var`j''@var`k') var(e.`var`=`j'+`nbitems'''@var`k')
+ local ++j
+ local ++k
+ }
+ local cl `cl' means(L`i'_1@0) var(L`i'_1@1) var(L`i'_2) means(L`i'_2)
+ local covl `covl' L`i'_1*L`i'_2
+ forvalues g = 1/`=`nbdims'-1' {
+ if (`=`i'+`g''<=`nbdims') {
+ //di in red `g'
+ local covl `covl' L`i'_1*L`=`i'+`g''_1 L`i'_2*L`=`i'+`g''_2
+ }
+ }
+
+ local ++i
+}
+
+
+local z "`s', `var' covstruct(_lexogenous, diagonal) `cl' cov(`cov12b' `covl' `covs') iterate(`iterate') method(`method') `sb'"
+
+//di "sem `z'"
+//di "model 2"
+
+qui sem `z'
+local m2 = e(cmdline)
+//qui `m2' stand
+est store model2
+est store model2init
+
+
+/*
+tempname b V
+matrix `b'=r(table)
+matrix `V'=e(V)
+//mat li `V'
+
+local i = 1
+foreach p in `partition' {
+ local truechange_L`i'=`b'[1,`=`nbitems'*4+`i'']
+ local Vtruechange_L`i'=`V'[`=`nbitems'*4+`i'',`=`nbitems'*4+`i'']
+ //di `Vtruechange_L`i''
+ local ++i
+}
+
+
+//estat gof
+qui estat gof, stat(all)
+local iter2=e(ic)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local pclose2=r(pclose)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+local convergence2=e(converged)
+
+
+if "`sb'" != "" {
+ local cmodel2 = e(sbc_ms)
+ //local chi22=r(chi2_ms)
+}
+
+
+ereturn matrix b2=`b'
+ereturn scalar iter2=`iter2'
+ereturn scalar tli2=`tli2'
+ereturn scalar cfi2=`cfi2'
+ereturn scalar srmr2=`srmr2'
+ereturn scalar rmsea2=`rmsea2'
+ereturn scalar ubrmsea2=`ubrmsea2'
+ereturn scalar lbrmsea2=`lbrmsea2'
+ereturn scalar pclose2=`pclose2'
+ereturn scalar chi22=`chi22'
+ereturn scalar df2=`df2'
+ereturn scalar dfc2=`dfc2'
+ereturn scalar p2=`p2'
+ereturn scalar bic2=`bic2'
+ereturn scalar convergence2=`convergence2'
+
+local i = 1
+foreach p in `partition' {
+ ereturn scalar truechange_L`i'=`truechange_L`i''
+ ereturn scalar Vtruechange_L`i'=`Vtruechange_L`i''
+ ereturn scalar setruechange_L`i'=`=sqrt(`Vtruechange_L`i'')'
+ ereturn scalar ztruechange_L`i'=`=`truechange_L`i''/sqrt(`Vtruechange_L`i'')'
+ ereturn scalar ptruechange_L`i'=`=2-2*normal(abs(`truechange_L`i'')/sqrt(`Vtruechange_L`i''))'
+ local ++i
+}
+*/
+
+
+
+
+
+
+/**************************************************************************************************************
+Autre syntaxe
+***************************************************************************************************************/
+
+constraint drop _all
+tokenize `varlist'
+
+local all
+local i = 1
+local j = 1
+
+//local moins = 0
+foreach v of varlist `varlist' {
+ if `i'<=`nbitems' {
+ local current [/]var(e.``i'') - [/]var(e.``=`i'+`nbitems''') = 0
+ if !strpos("`all'","`current'") {
+ constraint `j' [/]var(e.``i'') - [/]var(e.``=`i'+`nbitems''') = 0
+ //local moins = 0
+ local ++j
+ }
+ /*else {
+ local moins = 1
+ }*/
+ local all `all' [/]var(e.``i'') - [/]var(e.``=`i'+`nbitems''') = 0
+ local ++i
+ }
+}
+
+
+
+local all
+local i = 1
+foreach v of varlist `varlist' {
+ if `i'<=`nbitems' {
+ local current [/]var(e.``i'') - [/]var(e.``=`i'+`nbitems''') = 0
+ if !strpos("`all'","`current'") {
+ constraint `j' [``i'']_cons - [``=`i'+`nbitems''']_cons = 0
+ local ++j
+ }
+ local all `all' [/]var(e.``i'') - [/]var(e.``=`i'+`nbitems''') = 0
+ local ++i
+ }
+}
+
+
+local c = `j'
+local i = 1
+local j = 1
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while `j'<= `pp' {
+ constraint `c' [``j'']L`i'_1 - [``=`j'+`nbitems''']L`i'_2 = 0
+ //local s `s' (L`i'_1@load`k' _cons@int`k' -> `var`j'') (L`i'_2@load`k' _cons@int`k' -> `var`=`j'+`nbitems''')
+ local ++j
+ local ++c
+ //local ++k
+ }
+ local ++i
+}
+
+//constraint list
+
+
+
+//di "Model 2 (step 2)" // "Model 2 (autre syntaxe)"
+//di "`sem1'"
+`qui' di "sem `sem1' `cl' constraints(1/`=`nbitems'*3')"
+//local sem2 "`s', covstruct(_lexogenous, diagonal) cov(`cov12b' `covl') iterate(`iterate') method(`method') constraints(1/`=`nbitems'*3')"
+//di "`sem2'"
+
+set matsize 11000
+qui sem `sem1' `cl' constraints(1/`=`nbitems'*3')
+est store model2
+est store model2init
+
+/*
+local m2 = e(cmdline)
+qui `m2' stand
+est store model2init
+*/
+
+
+
+
+
+
+
+
+if "`sb'" != "" {
+ local cmodel2 = e(sbc_ms)
+ //local chi22=r(chi2_ms)
+}
+
+
+
+
+tempname b V
+matrix `b'=r(table)
+matrix `V'=e(V)
+//mat li `V'
+
+local i = 1
+foreach p in `partition' {
+ local truechange_L`i'=`b'[1,`=`nbitems'*4+`i'']
+ local Vtruechange_L`i'=`V'[`=`nbitems'*4+`i'',`=`nbitems'*4+`i'']
+ local setruechange_L`i'=`=sqrt(`Vtruechange_L`i'')'
+ local ztruechange_L`i'=`=`truechange_L`i''/sqrt(`Vtruechange_L`i'')'
+ local ptruechange_L`i'=`=2-2*normal(abs(`truechange_L`i'')/sqrt(`Vtruechange_L`i''))'
+ local ++i
+}
+
+//estat gof
+qui estat gof, stat(all)
+local iter2=e(ic)
+local tli2=r(tli)
+local cfi2=r(cfi)
+local srmr2=r(srmr)
+local rmsea2=r(rmsea)
+local ubrmsea2=r(ub90_rmsea)
+local lbrmsea2=r(lb90_rmsea)
+local pclose2=r(pclose)
+local chi22=r(chi2_ms)
+local df2=r(df_ms)
+local dfc2=3*`nbitems'+3
+local p2=r(p_ms)
+local bic2=r(bic)
+local convergence2=e(converged)
+
+/*
+ereturn matrix b2=`b'
+ereturn scalar iter2=`iter2'
+ereturn scalar tli2=`tli2'
+ereturn scalar cfi2=`cfi2'
+ereturn scalar srmr2=`srmr2'
+ereturn scalar rmsea2=`rmsea2'
+ereturn scalar ubrmsea2=`ubrmsea2'
+ereturn scalar lbrmsea2=`lbrmsea2'
+ereturn scalar pclose2=`pclose2'
+ereturn scalar chi22=`chi22'
+ereturn scalar df2=`df2'
+ereturn scalar dfc2=`dfc2'
+ereturn scalar p2=`p2'
+ereturn scalar bic2=`bic2'
+ereturn scalar convergence2=`convergence2'
+*/
+
+local i = 1
+foreach p in `partition' {
+ return scalar truechange_L`i'_2=`truechange_L`i''
+ return scalar Vtruechange_L`i'_2=`Vtruechange_L`i''
+ return scalar setruechange_L`i'_2=`=sqrt(`Vtruechange_L`i'')'
+ return scalar ztruechange_L`i'_2=`=`truechange_L`i''/sqrt(`Vtruechange_L`i'')'
+ return scalar ptruechange_L`i'_2=`=2-2*normal(abs(`truechange_L`i'')/sqrt(`Vtruechange_L`i''))'
+ local ++i
+}
+
+/*
+local i = 1
+foreach p in `partition' {
+ di as text "Observed change (i.e. without accounting for response shift) for `ltname`i'' is " %4.3f `truechange_L`i'' " (p = " %4.3f `ptruechange_L`i'' ")"
+ local ++i
+}
+*/
+
+if "`test'"!="" {
+ if "`sb'"=="" {
+ local chi221=`chi22'-`chi21'
+ local df21=`df2'-`df1'
+ local p21=1-chi2(`df21',`chi221')
+ local cmodel1= 1
+ local cmodel2 = 1
+ }
+ else {
+ local cd=(`df2'*`cmodel2'-`df1'*`cmodel1')/(`df2'-`df1')
+ local df21=`df2'-`df1'
+ local chi221=(`chi22'-`chi21')/`cd'
+ local p21 = 1-chi2(`df21',`chi221')
+ //local adjust = " (sb)"
+ }
+ //di in red `chi21'
+ //di in red `chi22'
+
+ if (`p21'>0.05) {
+ local testno=" no"
+ }
+ else {
+ //local p21 = round(`p21',0.001)
+ //if `p21'<0.001 {
+ //local p21 = "< 0.001"
+ //}
+ local testno = ""
+ }
+
+ di "{hline 51}"
+ di in gr /*_col(39) "Test of global Response-Shift " _col(79) "Comparison with model 1"*/
+ di in gr "Models" _col(18) "Chi-square" _col(32) "df" _col(36) "p-value" _col(48) "BIC" /*_col(39) "Chi-square" _col(54) "df" _col(59) "p-value" *_col(79) "Chi-square" _col(94) "df" _col(99) "p-value"*/
+ di "{hline 51}"
+ di in gr "Model 1" _col(20) %8.2f `=`chi21'/`cmodel1'' _col(30) %4.0f `df1' _col(37) %6.4f `p1' _col(45) %7.2f `bic1'
+ di in gr "Model 2" _col(20) %8.2f `=`chi22'/`cmodel2'' _col(30) %4.0f `df2' _col(37) %6.4f `p2' _col(45) %7.2f `bic2' /*_col(40) %8.2f `=abs(`chi22'-`chi21')' _col(50) %6.0f `df21' %6.4f _col(60) `=1-chi2(`df21',abs(`chi22'-`chi21'))' *_col(82) %8.2f `=`=abs(`chi22'-`chi21')'' _col(90) %6.0f `df21' _col(100) %6.4f `=1-chi2(`df21',abs(`chi22'-`chi21'))'*/
+ di "{hline 51}"
+
+ di "chi2 = " %4.2f `chi221' " (`df21')"
+ di "p-value of global test = " %4.3f `p21'
+ //di "=> `no' Step 3"
+}
+else local testno = ""
+
+if "`testno'"=="" {
+
+}
+else {
+ di as text "We skip step 3 because the overall test for response shift is non significant"
+}
+
+*di as text "End of step 2"
+
+
+
+/*** Etape 3 ***/
+
+forvalues i = 1/`=`nbitems'*3' {
+ constraint get `i'
+ local c`i' = r(contents)
+ //local csave`i' = r(contents)
+}
+
+matrix numcont = J(1,`=`nbitems'*3',.)
+forvalues i = 1/`=`nbitems'*3'{
+ if `i'<=`nbitems' {
+ local noms "`noms' NUR_``i''"
+ }
+ else if `i' > `nbitems' & `i'<=`=`nbitems'*2' {
+ local noms "`noms' UR_``=`i'-`nbitems'''"
+ }
+ else if `i' > `=`nbitems'*2' {
+ local noms "`noms' REP_``=`i'-2*`nbitems'''"
+ }
+
+}
+matrix colnames numcont = `noms'
+
+if "`hierarchical'" != "" & "`testno'" !=" no"{
+
+
+/**************************************************************************************************************
+Model 3 / Non Uniform recalibration
+***************************************************************************************************************/
+
+di
+di as result "Step 3 --Non Uniform recalibration--"
+
+timer clear 20
+timer on 20
+local nbsign = 0
+di as text "Iteration 1 running"
+local pbconv = 0
+local o = 1
+local k = 1
+local j = 1
+local stop = 0
+//local nonunif
+while (`j'<=`nbitems' & `stop'!=1) {
+ local max = -1
+ local c = 0
+ local stop = 0
+ timer clear 10
+ timer on 10
+ forvalues i = 1/`nbitems' {
+ constraint get `i'
+ if r(defined)== 1 {
+ constraint drop `i'
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3') forcenoanchor
+ //constraint list
+ constraint `i' `c`i''
+ //constraint list
+ //di "AprÚs avoir enlevé `c`i'' : "
+ if "`adjust'" != "" {
+ local nbtest = `nbitems'-`j'+1
+ }
+ else local nbtest = 1
+ //di "nbtest = `nbtest'"
+ qui eret li
+ if e(converged) == 1 {
+ est store model3
+ if "`sb'" == "" {
+ `qui' lrtest model2 model3
+ if r(p) < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if r(chi2) > `max' & r(p) < `=0.05/`nbtest'' {
+ local max = r(chi2)
+ local c = `i'
+ }
+ }
+ else {
+ qui estat gof, stats(all)
+ local df3=r(df_ms)
+ local cmodel3 = e(sbc_ms)
+ local chi23=r(chi2sb_ms)
+ local cd=(`df2'*`cmodel2'-`df3'*`cmodel3')/(`df2'-`df3')
+ local df23=`df2'-`df3'
+ local chi223=(`chi22'-`chi23')/`cd'
+ local p23 = 1-chi2(`df23',`chi223')
+ //di "lr(sb) = `chi223'"
+ //di "p = `p23'"
+ if `p23' < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if `chi223' > `max' & `p23' < `=0.05/`nbtest'' {
+ local max = `chi223'
+ local c = `i'
+ }
+ }
+ }
+ else {
+ local ++pbconv
+ //`qui' di "model did not converge (`pbconv' in total)"
+ }
+
+ }
+ }
+ //local mmax = `max'
+ //di `mmax'
+ //local cc`j' = `c'
+ //di `cc`j''
+
+ if `c' == 0 {
+ //matrix numcont[1,`c']=0
+ local stop = 1
+ //di "stop"
+ }
+
+ if `c'!=0 {
+ constraint get `c'
+ matrix numcont[1,`c']=1
+ //di "donc on retire"
+ //di r(contents)
+ local reprio`k' = r(contents)
+ local ordre_reprio_`k' = `o'
+ local ++o
+ constraint drop `c'
+ local c`c'
+ local ++k
+ }
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3')
+ qui est store model2
+ if "`sb'" != "" {
+ qui estat gof, stats(all)
+ local df2=r(df_ms)
+ local cmodel2 = e(sbc_ms)
+ local chi22=r(chi2_ms)
+ }
+ timer off 10
+ qui timer list 10
+ local ++j
+ if `j'==2 {
+ if (`nbsign'==0) local nbsign=1
+ di as text "Iteration `j' running" " (Based on the results of the first iteration, step 3 --non-uniform recalibration-- should last approximately " `=round(`r(t10)'*`nbsign')' " seconds)"
+ }
+ else {
+ di as text "Iteration `j' running"
+ }
+}
+
+di as text "Constraints removed (non-uniform recalibration): "
+forvalues i = 1/`nbitems' {
+ if "`nonunif`i''"!="" di "`nonunif`i''"
+}
+
+
+
+/**************************************************************************************************************
+Model 3 / Uniform recalibration
+***************************************************************************************************************/
+
+
+
+di
+di as result "Step 3 --Uniform recalibration--"
+
+timer clear 20
+timer on 20
+local nbsign = 0
+di as text "Iteration 1 running..."
+local pbconv = 0
+local o = 1
+local k = 1
+local j = 1
+local stop = 0
+//local nonunif
+while (`j'<=`nbitems' & `stop'!=1) {
+ local max = -1
+ local c = 0
+ local stop = 0
+ timer clear 10
+ timer on 10
+ forvalues i = `=`nbitems'+1'/`=`nbitems'*2' {
+ constraint get `i'
+ if r(defined)== 1 {
+ constraint drop `i'
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3') forcenoanchor
+ //constraint list
+ constraint `i' `c`i''
+ //constraint list
+ //di "AprÚs avoir enlevé `c`i'' : "
+ if "`adjust'" != "" {
+ local nbtest = `nbitems'-`j'+1
+ }
+ else local nbtest = 1
+ //di "nbtest = `nbtest'"
+ qui eret li
+ if e(converged) == 1 {
+ est store model3
+ if "`sb'" == "" {
+ `qui' lrtest model2 model3
+ if r(p) < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if r(chi2) > `max' & r(p) < `=0.05/`nbtest'' {
+ local max = r(chi2)
+ local c = `i'
+ }
+ }
+ else {
+ qui estat gof, stats(all)
+ local df3=r(df_ms)
+ local cmodel3 = e(sbc_ms)
+ local chi23=r(chi2sb_ms)
+ local cd=(`df2'*`cmodel2'-`df3'*`cmodel3')/(`df2'-`df3')
+ local df23=`df2'-`df3'
+ local chi223=(`chi22'-`chi23')/`cd'
+ local p23 = 1-chi2(`df23',`chi223')
+ //di "lr(sb) = `chi223'"
+ //di "p = `p23'"
+ if `p23' < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if `chi223' > `max' & `p23' < `=0.05/`nbtest'' {
+ local max = `chi223'
+ local c = `i'
+ }
+ }
+ }
+ else {
+ local ++pbconv
+ //`qui' di "model did not converge (`pbconv' in total)"
+ }
+
+ }
+ }
+ //local mmax = `max'
+ //di `mmax'
+ //local cc`j' = `c'
+ //di `cc`j''
+
+ if `c' == 0 {
+ //matrix numcont[1,`c']=0
+ local stop = 1
+ //di "stop"
+ }
+
+ if `c'!=0 {
+ constraint get `c'
+ matrix numcont[1,`c']=1
+ //di "donc on retire"
+ //di r(contents)
+ local reprio`k' = r(contents)
+ local ordre_reprio_`k' = `o'
+ local ++o
+ constraint drop `c'
+ local c`c'
+ local ++k
+ }
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3')
+ qui est store model2
+ if "`sb'" != "" {
+ qui estat gof, stats(all)
+ local df2=r(df_ms)
+ local cmodel2 = e(sbc_ms)
+ local chi22=r(chi2_ms)
+ }
+ timer off 10
+ qui timer list 10
+ local ++j
+ if `j'==2 {
+ if (`nbsign'==0) local nbsign=1
+ di as text "Iteration `j' running..." " (Based on the results of the first iteration, step 3 --uniform recalibration-- should last approximately " `=round(`r(t10)'*`nbsign')' " seconds)"
+ }
+ else {
+ di as text "Iteration `j' running..."
+ }
+}
+di as text "Constraints removed (uniform recalibration): "
+forvalues i = 1/`=`nbitems'*3' {
+ if "`unif`i''"!="" di "`unif`i''"
+}
+
+
+/**************************************************************************************************************
+Model 3 / Reprioritization
+***************************************************************************************************************/
+
+di
+di as result "Step 3 --Reprioritization--"
+
+timer clear 20
+timer on 20
+local nbsign = 0
+di as text "Iteration 1 running..."
+local pbconv = 0
+local o = 1
+local k = 1
+local j = 1
+local stop = 0
+//local nonunif
+while (`j'<=`nbitems' & `stop'!=1) {
+ local max = -1
+ local c = 0
+ local stop = 0
+ timer clear 10
+ timer on 10
+ forvalues i = `=`nbitems'*2+1'/`=`nbitems'*3' {
+ constraint get `i'
+ if r(defined)== 1 {
+ constraint drop `i'
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3') forcenoanchor
+ //constraint list
+ constraint `i' `c`i''
+ //constraint list
+ //di "AprÚs avoir enlevé `c`i'' : "
+ if "`adjust'" != "" {
+ local nbtest = `nbitems'-`j'+1
+ }
+ else local nbtest = 1
+ //di "nbtest = `nbtest'"
+ qui eret li
+ if e(converged) == 1 {
+ est store model3
+ if "`sb'" == "" {
+ `qui' lrtest model2 model3
+ if r(p) < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if r(chi2) > `max' & r(p) < `=0.05/`nbtest'' {
+ local max = r(chi2)
+ local c = `i'
+ }
+ }
+ else {
+ qui estat gof, stats(all)
+ local df3=r(df_ms)
+ local cmodel3 = e(sbc_ms)
+ local chi23=r(chi2sb_ms)
+ local cd=(`df2'*`cmodel2'-`df3'*`cmodel3')/(`df2'-`df3')
+ local df23=`df2'-`df3'
+ local chi223=(`chi22'-`chi23')/`cd'
+ local p23 = 1-chi2(`df23',`chi223')
+ //di "lr(sb) = `chi223'"
+ //di "p = `p23'"
+ if `p23' < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ if `chi223' > `max' & `p23' < `=0.05/`nbtest'' {
+ local max = `chi223'
+ local c = `i'
+ }
+ }
+ }
+ else {
+ local ++pbconv
+ //`qui' di "model did not converge (`pbconv' in total)"
+ }
+
+ }
+ }
+ //local mmax = `max'
+ //di `mmax'
+ //local cc`j' = `c'
+ //di `cc`j''
+
+ if `c' == 0 {
+ //matrix numcont[1,`c']=0
+ local stop = 1
+ //di "stop"
+ }
+
+ if `c'!=0 {
+ constraint get `c'
+ matrix numcont[1,`c']=1
+ //di "donc on retire"
+ //di r(contents)
+ local reprio`k' = r(contents)
+ local ordre_reprio_`k' = `o'
+ local ++o
+ constraint drop `c'
+ local c`c'
+ local ++k
+ }
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3')
+ qui est store model2
+ if "`sb'" != "" {
+ qui estat gof, stats(all)
+ local df2=r(df_ms)
+ local cmodel2 = e(sbc_ms)
+ local chi22=r(chi2_ms)
+ }
+ timer off 10
+ qui timer list 10
+ local ++j
+ if `j'==2 {
+ if (`nbsign'==0) local nbsign=1
+ di as text "Iteration `j' running..." " (Based on the results of the first iteration, step 3 --reprioritization-- should last approximately " `=round(`r(t10)'*`nbsign')' " seconds)"
+ }
+ else {
+ di as text "Iteration `j' running..."
+ }
+}
+
+di as text "Constraints removed (reprioritization) : "
+forvalues i = 1/`nbitems' {
+ if "`reprio`i''"!="" di "`reprio`i''"
+}
+
+
+
+
+di as result "Summary of step 3 "
+/*
+di "`pbconv' model(s) did not converge"
+di
+di as text "The following constraints were removed:"
+forvalues i = 1/`=`nbitems'*3' {
+ if "`nonunif`i''"!="" di "`nonunif`i'' (order = `ordre_nonunif_`i'')"
+}
+forvalues i = 1/`=`nbitems'*3' {
+ if "`unif`i''"!="" di "`unif`i'' (order = `ordre_unif_`i'')"
+}
+forvalues i = 1/`=`nbitems'*3' {
+ if "`reprio`i''"!="" di "`reprio`i'' (order = `ordre_reprio_`i'')"
+}
+//constraint list
+*/
+}
+
+
+
+
+
+
+
+
+else if "`hierarchical'" == "" & "`testno'" !=" no"{
+
+di
+di as result "Step 3: Detection of response shift"
+
+timer clear 20
+timer on 20
+local nbsign = 0
+di as text "Iteration 1 running " _c
+local pbconv = 0
+local o = 1
+local k = 1
+local j = 1
+local stop = 0
+local nonunif
+while (`stop'!=1) {
+ local max = -1
+ local c = 0
+ local stop = 0
+ timer clear 10
+ timer on 10
+ forvalues i = 1/`=`nbitems'*3' {
+ constraint get `i'
+ if r(defined)== 1 {
+ //di as text "`j'_`i'"
+ constraint drop `i'
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3') forcenoanchor
+ //constraint list
+ constraint `i' `c`i''
+ //constraint list
+ `qui' di as text "After removing `c`i'' : "
+ qui eret li
+ if e(converged) == 1 {
+ est store model3
+ if "`sb'" == "" {
+ qui lrtest model2 model3
+ if "`adjust'" != "" {
+ local nbtest = `nbitems'*3-`j'+1
+ }
+ else local nbtest = 1
+ if r(p) < `=0.05/`nbtest'' {
+ local nbsign = `nbsign'+1
+ }
+ `qui' di "nbtest = `nbtest'"
+ if r(chi2) > `max' & r(p) < `=0.05/`nbtest'' {
+ local max = r(chi2)
+ local c = `i'
+ }
+ }
+ else {
+ qui estat gof, stats(all)
+ local df3=r(df_ms)
+ local cmodel3 = e(sbc_ms)
+ local chi23=r(chi2_ms)
+ //di in red "chi22 = `chi22'"
+ //di in red "chi23 = `chi23'"
+ //di in red `cmodel2'
+ //di in red `cmodel3'
+ local cd=(`df2'*`cmodel2'-`df3'*`cmodel3')/(`df2'-`df3')
+ local df23=`df2'-`df3'
+ local chi223=(`chi22'-`chi23')/`cd'
+ local p23 = 1-chi2(`df23',`chi223')
+ //di "df2 = `df2'"
+ //di "df3 = `df3'"
+ di as text "cd = `cd'"
+ //di "chi223 = `chi223'"
+ //di "df23 = `df23'"
+ di as text "lr(sb) = `chi223'"
+ di as text "p = `p23'"
+ if `chi223' > `max' & `p23' < 0.05 {
+ local max = `chi223'
+ local c = `i'
+ }
+ }
+ }
+ else {
+ local ++pbconv
+ `qui' di "model did not converge (`pbconv' in total)"
+ }
+
+ }
+ di %4.0f `=`i'/(`nbitems'*3)*100' "% " _c
+ }
+
+ if `c' == 0 {
+ //matrix numcont[1,`c']=0
+ local stop = 1
+ //di "stop"
+ }
+ if `c'!=0 {
+ //di in red `c'
+ matrix numcont[1,`c']=1
+ constraint get `c'
+ `qui' di "The following constraint was removed: "
+ `qui' di r(contents)
+ if `c'<=`nbitems' {
+ local nonunif`k' = r(contents)
+ local ordre_nonunif_`k' = `o'
+ local ++o
+ }
+ else if `c' > `nbitems' & `c'<=`=`nbitems'*2' {
+ local unif`k' = r(contents)
+ local ordre_unif_`k' = `o'
+ local ++o
+ }
+ else if `c' > `=`nbitems'*2' {
+ local reprio`k' = r(contents)
+ local ordre_reprio_`k' = `o'
+ local ++o
+ }
+ constraint drop `c'
+ local c`c'
+ local ++k
+ }
+ qui sem `sem1' `cl' constraints(1/`=`nbitems'*3') forcenoanchor
+ qui est store model2
+ if "`sb'" != "" {
+ qui estat gof, stats(all)
+ local df2=r(df_ms)
+ local cmodel2 = e(sbc_ms)
+ local chi22=r(chi2_ms)
+ }
+
+ timer off 10
+ qui timer list 10
+ local ++j
+ if `j'==2 {
+ di as text _n "(Based on the results of the first iteration, Step 3 should last approximately " `=round(`r(t10)'*`nbsign')' " seconds)"
+ di as text "Iteration 2 running " _c
+ }
+ else {
+ if `c'!=0 {
+ di as text _n "Iteration `j' running " _c
+ }
+ }
+}
+timer off 20
+qui timer list 20
+di _n "(Step 3 took "`=round(`r(t20)')' " seconds to complete)"
+di
+est store model3
+
+
+/*
+di as text "Contraintes libérées (recalibration non-uniforme) : "
+forvalues i = 1/`nbitems' {
+ if "`nonunif`i''"!="" di "`nonunif`i''"
+}*/
+
+
+di as result "Summary of step 3 "
+/*
+di
+di as text "`pbconv' model(s) did not converge"
+di
+di as text "The following constraints were removed:"
+forvalues i = 1/`=`nbitems'*3' {
+ if "`nonunif`i''"!="" di "`nonunif`i'' (order = `ordre_nonunif_`i'')"
+}
+forvalues i = 1/`=`nbitems'*3' {
+ if "`unif`i''"!="" di "`unif`i'' (order = `ordre_unif_`i'')"
+}
+forvalues i = 1/`=`nbitems'*3' {
+ if "`reprio`i''"!="" di "`reprio`i'' (order = `ordre_reprio_`i'')"
+}
+//constraint list
+*/
+}
+
+
+
+est store model4
+local m4 = e(cmdline)
+
+local i = 1
+foreach p in `partition' {
+ local cl `cl' means(L`i'_1@0) var(L`i'_1@1) var(L`i'_2@1) means(L`i'_2)
+ local ++i
+}
+
+
+
+
+mat mt = numcont'
+
+local maxlength = 0
+foreach v of varlist `varlist' {
+ if length("`v'")>`maxlength' {
+ local maxlength = length("`v'")
+ }
+}
+
+local et = "&|"
+forvalues i=1/`=`nbitems'*3' {
+ local et "`et'" "&"
+}
+matrix colnames mt = "1 if RS detected"
+
+if "`testno'" == "" {
+ di as text "Notation: "
+ di as text "RS = response shift"
+ di as text "NUR = non-uniform recalibration"
+ di as text "UR = uniform recalibration"
+ di as text "REP = reprioritization"
+ local esp
+ forvalues i = 1/`=`nbitems'*3+2' {
+ local esp = "`esp'&"
+ }
+ matlist mt, cspec(& %~`=`maxlength'+4's & %18.0f & ) rspec("`esp'")
+ mat li mt
+ matrix rsitems = mt
+ return matrix rsitems = mt
+ di
+ *di as text "End of step 3"
+}
+
+
+/***********************
+ Step 4
+************************/
+di as result "Step 4: Assessment of true change"
+qui est rep model4
+qui est rest model4
+
+tempname b V
+matrix `b'=e(b)
+matrix `V'=e(V)
+//mat li `V'
+
+local i = 1
+foreach p in `partition' {
+ local truechange_L`i'_4=`b'[1,`=`nbitems'*4+`i'']
+ local Vtruechange_L`i'_4=`V'[`=`nbitems'*4+`i'',`=`nbitems'*4+`i'']
+ local setruechange_L`i'_4=`=sqrt(`Vtruechange_L`i'_4')'
+ local ztruechange_L`i'_4=`=`truechange_L`i'_4'/sqrt(`Vtruechange_L`i'_4')'
+ local ptruechange_L`i'_4=`=2-2*normal(abs(`truechange_L`i'_4')/sqrt(`Vtruechange_L`i'_4'))'
+ local ++i
+}
+
+local i = 1
+foreach p in `partition' {
+ return scalar truechange_L`i'_4 = `truechange_L`i'_4'
+ return scalar Vtruechange_L`i'_4=`Vtruechange_L`i'_4'
+ return scalar setruechange_L`i'_4=`setruechange_L`i'_4'
+ return scalar ztruechange_L`i'_4=`ztruechange_L`i'_4'
+ return scalar ptruechange_L`i'_4=`ptruechange_L`i'_4'
+ local ++i
+}
+
+
+
+
+
+local i = 1
+foreach p in `partition' {
+ //di as text "True change (i.e. when accounting for response shift) for `ltname`i'' is " %4.3f `truechange_L`i'_4' " (p = " %4.3f `ptruechange_L`i'_4' ")"
+ //di as text "Without accounting for response shift, the estimated change for `ltname`i'' would be " %4.3f `truechange_L`i'' " (p = " %4.3f `ptruechange_L`i'' ")"
+ //di
+ local ++i
+}
+
+
+/* LR test for LT means */
+qui est rest model4
+local m4 = e(cmdline)
+
+
+forvalues i = 1/`P' {
+ local cm `cm' means(L`i'_2@0)
+}
+qui `m4' `cm'
+qui est store model4_0
+
+if `P' > 1 {
+ *di as text "Test if all LT means = 0 at time 2"
+ qui lrtest model4 model4_0
+ qui ret li
+ if r(p) > 0.05 {
+ di as text "LT means are not significantly different from 0 (p=" %4.3f r(p) ")"
+ }
+ else {
+ di as text "LT means are significantly different from 0 (p=" %4.3f r(p) ")"
+ }
+}
+
+/* Decomposition of observed change */
+
+di
+di as result "Decomposition of observed change"
+di
+/*
+di as text "Notation:"
+di as text "observed change = contribution of response shift + true change"
+di as text "contribution of reponse shift = contribution of recalibration + contribution of reprioritization"
+di
+*/
+
+qui est rest model4
+qui estat framework, fitted
+
+mat mu = r(mu)
+
+forvalues i = 1/`P' {
+ mat muLT`i' = mu[1,`nbitems'*2+`i'*2]
+}
+
+mat gamma = r(Gamma)
+
+mat gamma1 = gamma[1...,1..1]
+mat gamma2 = gamma[1...,2..2]
+forvalues i=1(2)`=`P'*2' {
+ mat g1 = gamma[1...,`i'..`i']
+ mat gamma1 = gamma1,g1
+ mat g2 = gamma[1...,`i'+1..`i'+1]
+ mat gamma2 = gamma2,g2
+}
+mat gamma1 = gamma1[1...,2...]
+mat gamma2 = gamma2[1...,2...]
+
+mat alpha = r(alpha)
+
+local v = 1
+local c = 1
+local i = 1
+local j = 1
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while `j'<= `pp' {
+ local tc = 0
+ local reprio = 0
+ mat mui = mu
+
+ local mu1 = mui[1,`j']
+ local mu2 = mui[1,`j'+`p']
+ local mu2mu1 = `mu2'-`mu1'
+ local oc`v' = `mu2mu1'
+
+ local recalibration = alpha[1,`j'+`p']-alpha[1,`j']
+
+ mat tc = gamma1[`j',1...]*muLT`i'[1...,1...]
+ forvalues k = 1/`P' {
+ local t = el(tc,1,`k')
+ local tc = `tc'+`t'
+ }
+ local tc`v' = `tc'
+
+ mat g1 = gamma1[`j',1...]
+ mat g2 = gamma2[`j'+`p',1...]
+ mat m = muLT`i'[1...,1...]
+
+ mat reprio = (gamma2[`j'+`p',1...]-gamma1[`j',1...])*muLT`i'[1...,1...]
+ *mat li reprio
+ forvalues k = 1/`P' {
+ local r = el(reprio,1,`k')
+ local reprio = `reprio'+`r'
+ }
+
+
+ local rs = `recalibration'+`reprio'
+ local rs`v' = `rs'
+
+ //di as text "Observed change for `var`v'' = " %10.3g `mu2mu1' " = " %10.3g `rs' " + " %10.3g `tc'
+ if (`rs'!=0) {
+ //di as text = "Contribution of response shift = " %10.3g `rs' " = " %10.3g `recalibration' " + " %10.3g `reprio'
+ }
+ else {
+ //di as text "(no repsonse shift for `var`v'')"
+ }
+ local ++j
+ local ++v
+ //di
+ }
+ local j = `j'+`p'
+ local pp = `pp'+`p'
+ local ++i
+}
+
+
+
+
+
+/* Table */
+
+local v = 1
+forvalues i=1/`=`nbitems'*3' {
+ if rsitems[`i',1]==1 {
+ if `i' > `nbitems' & `i'<=`=`nbitems'*2' {
+ local v = `i'-`nbitems'
+ }
+ if `i' > `=`nbitems'*2' & `i'<=. {
+ local v = `i'-`nbitems'-`nbitems'
+ }
+
+ if `i'<=`nbitems' {
+ local rsd`v' "`rsd`v''" "NUR "
+ }
+ if `i'>`nbitems' & `i'<=`=`nbitems'*2' {
+ local rsd`v' "`rsd`v''" "UR "
+ }
+ if `i'>`=`nbitems'*2' {
+ local rsd`v' "`rsd`v''" "REP "
+ }
+ }
+}
+
+
+di _col(0) "{hline 128}"
+di as result _col(0) "Variable" _col(25) "Response shift" _col(48) "Observed change" _col(72) "Response shift contribution" _col(105) "True change contribution"
+di as text _col(0) "{hline 128}"
+
+local i = 1
+foreach v of varlist `varlist' {
+ if `i' <= `nbitems' {
+ di as text _col(0) "`v'" _c
+ di _col(25) %10.2g "`rsd`i''" _c
+ di _col(48) %10.2g `oc`i'' _c
+ di _col(72) %10.2g `rs`i'' _c
+ di _col(105)%10.2g `tc`i''
+ }
+ local ++i
+}
+
+di as result _col(0) "{hline 128}"
+
+
+
+
+
+/* Effect-sizes */
+
+di
+di as result "Effect-sizes of observed change, response shift, and true change"
+di
+/*
+di as text "Notation:"
+di as text "observed change = contribution of response shift + true change"
+di as text "contribution of reponse shift = contribution of recalibration + contribution of reprioritization"
+*/
+
+qui est rest model4
+qui estat framework, fitted
+
+mat mu = r(mu)
+
+forvalues i = 1/`P' {
+ mat muLT`i' = mu[1,`nbitems'*2+`i'*2]
+}
+
+mat gamma = r(Gamma)
+
+mat gamma1 = gamma[1...,1..1]
+mat gamma2 = gamma[1...,2..2]
+forvalues i=1(2)`=`P'*2' {
+ mat g1 = gamma[1...,`i'..`i']
+ mat gamma1 = gamma1,g1
+ mat g2 = gamma[1...,`i'+1..`i'+1]
+ mat gamma2 = gamma2,g2
+}
+mat gamma1 = gamma1[1...,2...]
+mat gamma2 = gamma2[1...,2...]
+
+mat alpha = r(alpha)
+
+
+mat sigma = r(Sigma)
+
+
+
+local v = 1
+local c = 1
+local i = 1
+local j = 1
+local pp = 0
+foreach p in `partition' {
+ local pp = `pp'+`p'
+ while `j'<= `pp' {
+ local tc = 0
+ local reprio = 0
+ mat mui = mu
+
+ local mu1 = mui[1,`j']
+ local mu2 = mui[1,`j'+`p']
+ local mu2mu1 = `mu2'-`mu1'
+
+
+ /* standard deviations */
+ local sd1 = el(sigma,`j',`j')
+ local sd2 = el(sigma,`j'+`p',`j'+`p')
+ local covar = el(sigma,`j',`j'+`p')
+ local sd = sqrt(`sd1'+`sd2'-2*`covar')
+
+ *di "sd = " `sd'
+
+ local mu2mu1 = `mu2mu1'/`sd'
+ local oc`v' = `mu2mu1'
+
+
+ local recalibration = alpha[1,`j'+`p']-alpha[1,`j']
+ local recalibration = `recalibration'/`sd'
+
+ mat tc = gamma1[`j',1...]*muLT`i'[1...,1...]
+ forvalues k = 1/`P' {
+ local t = el(tc,1,`k')
+ local tc = `tc'+`t'
+ }
+
+
+ local tc = `tc'/`sd'
+ local tc`v' = `tc'
+ *di "tc = " `tc'
+
+
+ mat g1 = gamma1[`j',1...]
+ mat g2 = gamma2[`j'+`p',1...]
+ mat m = muLT`i'[1...,1...]
+
+ mat reprio = (gamma2[`j'+`p',1...]-gamma1[`j',1...])*muLT`i'[1...,1...]
+ *mat li reprio
+ forvalues k = 1/`P' {
+ local r = el(reprio,1,`k')
+ local reprio = `reprio'+`r'
+ }
+ local reprio = `reprio'/`sd'
+
+ local rs = `recalibration'+`reprio'
+ local rs`v' = `rs'
+
+ //di as text "Observed change for `var`v'' = " %4.3f `mu2mu1' " = " %4.3f `rs' " + " %4.3f `tc'
+ if (`rs'!=0) {
+ //di as text = "Contribution of response shift = " %4.3f `rs' " = " %4.3f `recalibration' " + " %4.3f `reprio'
+ }
+ else {
+ //di as text "(no repsonse shift for `var`v'')"
+ }
+ local ++j
+ local ++v
+ //di
+ }
+ local j = `j'+`p'
+ local pp = `pp'+`p'
+ local ++i
+}
+
+
+/* Table of effect-sizes */
+
+forvalues i=1/`nbitems' {
+ local rsd`i'
+}
+
+local v = 1
+
+forvalues i=1/`=`nbitems'*3' {
+ if rsitems[`i',1]==1 {
+ if `i' > `nbitems' & `i'<=`=`nbitems'*2' {
+ local v = `i'-`nbitems'
+ }
+ if `i' > `=`nbitems'*2' & `i'<=. {
+ local v = `i'-`nbitems'-`nbitems'
+ }
+
+ if `i'<=`nbitems' {
+ local rsd`v' "`rsd`v''" "NUR "
+ }
+ if `i'>`nbitems' & `i'<=`=`nbitems'*2' {
+ local rsd`v' "`rsd`v''" "UR "
+ }
+ if `i'>`=`nbitems'*2' {
+ local rsd`v' "`rsd`v''" "REP "
+ }
+ }
+}
+
+
+di _col(0) "{hline 128}"
+di as result _col(0) "Variable" _col(25) "Response shift" _col(48) "Observed change" _col(72) "Response shift contribution" _col(105) "True change contribution"
+di as text _col(0) "{hline 128}"
+
+local i = 1
+foreach v of varlist `varlist' {
+ if `i' <= `nbitems' {
+ di as text _col(0) "`v'" _c
+ di _col(25) %6.3f "`rsd`i''" _c
+ di _col(48) %6.3f `oc`i'' _c
+ di _col(72) %6.3f `rs`i'' _c
+ di _col(105)%6.3f `tc`i''
+ }
+ local ++i
+}
+
+di as result _col(0) "{hline 128}"
+
+/* radar plots */
+
+
+tempvar ocs tcs variable
+qui gen `ocs' = .
+qui gen `tcs' = .
+qui gen `variable' = ""
+forvalues i = 1/`nbitems' {
+ qui replace `variable' = "`var`i''" in `i'
+ qui replace `ocs' = `oc`i'' in `i'
+ qui replace `tcs' = `tc`i'' in `i'
+}
+
+//list `variable' `ocs' `tcs' in 1/`nbitems'
+qui replace `variable' = "a" if `variable'==""
+
+qui radar `variable' `ocs' `tcs' in 1/`nbitems', aspect(1) legend(lab(1 "Observed change") lab(2 "True change")) r(-1 -0.8 -0.5 0 0.5 0.8 1) note("") title(Effect-sizes of observed change and true change)
+
+
+
+
+/* return */
+
+matrix effectsizes = J(`nbitems',3,.)
+forvalues i = 1/`nbitems'{
+ mat effectsizes[`i',1] = `oc`i''
+ mat effectsizes[`i',2] = `rs`i''
+ mat effectsizes[`i',3] = `tc`i''
+ local names `names' `var`i''
+}
+mat rownames effectsizes = `names'
+
+return matrix effectsizes = effectsizes
+
+
+
+
+//di "modĂšle 2 avec variances Ă 1"
+qui `m2' `cl'
+//di "modĂšle 4 avec variances Ă 1"
+qui `m4' `cl'
+
+est drop model2
+//est dir
+
+
+restore
+end
diff --git a/Modules/ado/personal/s/old/simirt11.ado b/Modules/ado/personal/s/old/simirt11.ado
new file mode 100644
index 0000000..5109605
--- /dev/null
+++ b/Modules/ado/personal/s/old/simirt11.ado
@@ -0,0 +1,556 @@
+*! version 1.1 8december2005
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@orscentre.org
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2005 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW GRoup(real 0) DELtagroup(real 0)]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2 {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if `nbdim'==1 {
+ local dim1=`dim'
+ local nbitems=`dim1'
+ local dim=1
+ }
+ else if `nbdim'==2 {
+ local dim1:word 1 of `dim'
+ local dim2:word 2 of `dim'
+ local nbitems=`dim1'+`dim2'
+ local dim=2
+ }
+ else {
+ di in red "Your {hi:dim} option is uncorrect, please correct it. This option must indicate one or two integer(s)."
+ error 198
+ exit
+ }
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ if (`nbdiff'==3&`dim'==1)|(`nbdiff'==5&`dim'==2)|`nbdiff'==1 {
+ local typediff:word 1 of `diff'
+ if "`typediff'"!="gauss"&"`typediff'"!="uniform" {
+ local typediff values
+ }
+ }
+ if "`typediff'"=="values"&`nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ if "`diff'"=="" {
+ if `dim'==1 {
+ local diff gauss 0 1
+ }
+ else if `dim'==2 {
+ local diff gauss 0 1 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"=="" {
+ di in red "You must indicate the number of items to simulate with the {hi:dim} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else {
+ local nbdiff:word count `diff'
+ if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+}
+if "`draw'"!=""&`dim'!=1 {
+ di in red "The {hi:draw} option is available only with unidimensional simulated data."
+ error 198
+ exit
+}
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+local prefix1:word 1 of `prefix'
+if `dim'==2&`nbprefix'>=2 {
+ local prefix2:word 2 of `prefix'
+}
+else if `dim'==2 {
+ local prefix2:word 1 of `prefix'
+}
+if `dim'==2&"`prefix1'"=="`prefix2'" {
+ local prefix1 `prefix1'A
+ local prefix2 `prefix2'B
+}
+
+*di in ye "dim : `dim' ; diff : `diff' ; nbdiff : `nbdiff'"
+
+local nbcov:word count `cov'
+
+if `dim'==1&`nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+}
+else if `dim'==2&`nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+}
+else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+}
+
+if `nbcov'==1 {
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+}
+else if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+/*
+scalar define hour=real(substr("$S_TIME",1,2))
+scalar define min=real(substr("$S_TIME",4,2))
+scalar define sec=real(substr("$S_TIME",7,2))
+scalar define jour=real(substr("$S_DATE",1,2))
+*/
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+if $seed>2^31-1 {
+ global seed=int($seed/10)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `dim'==1 {
+ if `nbdiff'==3 {
+ local min:word 2 of `diff'
+ local max:word 3 of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min=-2
+ local max=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ }
+ local diff
+ forvalues i=1/`nbitems' {
+ local diff `diff' `=`min'+(`max'-`min')*`i'/(`nbitems'+1)'
+ }
+ }
+ if `dim'==2 {
+ if `nbdiff'==5 {
+ local min1:word 2 of `diff'
+ local max1:word 3 of `diff'
+ local min2:word 4 of `diff'
+ local max2:word 5 of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min1=-2
+ local max1=2
+ local min2=-2
+ local max2=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues i=1/`dim1' {
+ local diff `diff' `=`min1'+(`max1'-`min1')*`i'/(`dim1'+1)'
+ }
+ forvalues i=1/`dim2' {
+ local diff `diff' `=`min2'+(`max2'-`min2')*`i'/(`dim2'+1)'
+ }
+ }
+}
+if "`typediff'"=="gauss" {
+ if `dim'==1 {
+ if `nbdiff'==3 {
+ local mean:word 2 of `diff'
+ local var:word 3 of `diff'
+ }
+ else if `nbdiff'==1 {
+ local mean=0
+ local var=1
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues i=1/`nbitems' {
+ local tmp=invnorm(`i'/(`nbitems'+1))*sqrt(`var')+`mean'
+ local diff `diff' `tmp'
+ }
+ }
+ if `dim'==2 {
+ if `nbdiff'==5 {
+ local mean1:word 2 of `diff'
+ local var1:word 3 of `diff'
+ local mean2:word 4 of `diff'
+ local var2:word 5 of `diff'
+ }
+ else if `nbdiff'==1 {
+ local mean1=0
+ local var1=1
+ local mean2=0
+ local var2=1
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues i=1/`dim1' {
+ local tmp=invnorm(`i'/(`dim1'+1))*sqrt(`var1')+`mean1'
+ local diff `diff' `tmp'
+ }
+ forvalues i=1/`dim2' {
+ local tmp=invnorm(`i'/(`dim2'+1))*sqrt(`var2')+`mean2'
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if `nbcov'==3|`nbcov'==1 {
+ local tmp:word 1 of `cov'
+ matrix `matcov'[1,1]=`tmp'
+ if `nbcov'==3&`dim'==2 {
+ local tmp:word 2 of `cov'
+ matrix `matcov'[2,1]=`tmp'
+ local tmp:word 3 of `cov'
+ matrix `matcov'[3,1]=`tmp'
+ }
+}
+else {
+ matrix `matcov'[1,1]=1
+ if `dim'==2 {
+ matrix `matcov'[2,1]=1
+ matrix `matcov'[3,1]=0
+ }
+}
+if (`nbmu'==`dim') {
+ local tmp:word 1 of `mu'
+ matrix `matmu'[1,1]=`tmp'
+ if `dim'==2 {
+ local tmp:word 2 of `mu'
+ matrix `matmu'[2,1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`matcov'[3,1]/sqrt(`matcov'[1,1]*`matcov'[2,1])
+}
+
+/********************************************************************************
+ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+
+if "`draw'"!="" {
+ *set trace on
+ drop _all
+ qui set obs 2001
+ qui gen lt1=_n
+ qui replace lt1=(lt1-1001)/1000*4*sqrt(`cov')+`matmu'[1,1]
+ label variable lt1 "Latent trait"
+ local dess
+
+ forvalues i=1/`dim1' {
+ qui gen `prefix1'`i'=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(1/(1+exp(-`matdisc'[`i',1]*(lt1-`matdiff'[`i',1]))))^(`matacc'[`i',1])
+ local dess `dess' (line `prefix'`i' lt1)
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(off) ytitle("Probability of a positive response")
+}
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+drop _all
+qui set obs `nbobs'
+qui gen lt1=invnorm(uniform())
+if `dim'==2 {
+ qui gen lt2=invnorm(uniform())
+ qui replace lt2=`corr'*lt1+sqrt(1-(`corr')^2)*lt2
+ qui replace lt2=lt2*sqrt(`matcov'[2,1])+`matmu'[2,1]
+}
+qui replace lt1=lt1*sqrt(`matcov'[1,1])+`matmu'[1,1]
+
+if `dim'==1&`group'!=0 {
+ qui gen group=uniform()<`group'
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+}
+
+di in gr "{hline 75}"
+di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+di in gr "{hline 75}"
+forvalues i=1/`dim1' {
+ qui gen `prefix1'`i'=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(1/(1+exp(-`matdisc'[`i',1]*(lt1-`matdiff'[`i',1]))))^(`matacc'[`i',1])
+ qui replace `prefix1'`i'=uniform()<=`prefix1'`i'
+ di _col(1) in gr "`prefix1'`i'" _col(20) in ye %8.4f `matdiff'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+}
+if `dim'==2 {
+ di in gr "{hline 75}"
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ qui gen `prefix2'`=`i'-`dim1''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(1/(1+exp(-`matdisc'[`i',1]*(lt2-`matdiff'[`i',1]))))^(`matacc'[`i',1])
+ qui replace `prefix2'`=`i'-`dim1''=uniform()<=`prefix2'`=`i'-`dim1''
+ di _col(1) in gr "`prefix2'`=`i'-`dim1''" _col(20) in ye %8.4f `matdiff'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ }
+}
+di in gr "{hline 75}"
+di
+
+
+
+qui corr lt*,cov
+local var_1=r(Var_1)
+return scalar var_1=r(Var_1)
+if `dim'==2 {
+ local cov_12=r(cov_12)
+ local var_2=r(Var_2)
+ return scalar cov_12=r(cov_12)
+ return scalar var_2=r(Var_2)
+ qui corr lt*
+ local rho=r(rho)
+ return scalar rho=r(rho)
+}
+qui su lt1
+local mean1=r(mean)
+return scalar mean_1=r(mean)
+if `dim'==2 {
+ qui su lt2
+ local mean2=r(mean)
+ return scalar mean_2=r(mean)
+}
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(29) "Theorical" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',1] _col(42) %8.4f `var_`i''
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+}
+if `dim'==2 {
+ di _col(1) in gr "Covariance" _col(30) in ye %8.4f `matcov'[3,1] _col(42) %8.4f `cov_12'
+ di _col(1) in gr "Correlation" _col(31) in ye %7.4f `corr' _col(43) %7.4f `rho'
+}
+di in gr "{hline 50}"
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/old/simirt35.ado b/Modules/ado/personal/s/old/simirt35.ado
new file mode 100644
index 0000000..66e1ff4
--- /dev/null
+++ b/Modules/ado/personal/s/old/simirt35.ado
@@ -0,0 +1,804 @@
+*! version 3.5 May 16, 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 2013 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string)]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+*set trace on
+if "`covmatrix'"=="" {
+ local nbcov:word count `cov'
+
+ if `dim'==1&`nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ else if `dim'==2&`nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+
+ if `nbcov'==1 {
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ }
+ else if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ tempname covmatrix2
+ if `dim'==1 {
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+ *matrix list `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+*set trace on
+if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+*set trace off
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`pcm'"!="" {
+ local nbmodas=colsof(`pcm')
+ forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+ }
+}
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+if "`pcm'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+ }
+}
+
+if "`covmatrix'"=="" {
+ if `nbcov'==3|`nbcov'==1 {
+ local tmp:word 1 of `cov'
+ matrix `matcov'[1,1]=`tmp'
+ if `nbcov'==3&`dim'==2 {
+ local tmp:word 2 of `cov'
+ matrix `matcov'[2,1]=`tmp'
+ local tmp:word 3 of `cov'
+ matrix `matcov'[3,1]=`tmp'
+ }
+ }
+}
+else if 6==9{
+ matrix `matcov'[1,1]=1
+ if `dim'==2 {
+ matrix `matcov'[2,1]=1
+ matrix `matcov'[3,1]=0
+ }
+}
+else if "`covmatrix'"!="" {
+ matrix `matcov'=`covmatrix'
+}
+if (`nbmu'==`dim') {
+* local tmp:word 1 of `mu'
+* matrix `matmu'[1,1]=`tmp'
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+* if `dim'>1 {
+* local tmp:word 2 of `mu'
+* matrix `matmu'[2,1]=`tmp'
+* }
+}
+if `dim'==2 {
+ local corr=`matcov'[3,1]/sqrt(`matcov'[1,1]*`matcov'[2,1])
+}
+
+/********************************************************************************
+ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+
+if "`draw'"!="" {
+ *set trace on
+ drop _all
+ qui set obs 2001
+ qui gen lt1=_n
+ qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1]
+ label variable lt1 "Latent trait"
+ local dess
+
+
+ if "`rsm1'"==""&"`pcm'"=="" {
+ if "`title'"=="" {
+ local title2="Item Characteristics Curves of the items"
+ }
+ else {
+ local title2="`title'"
+ }
+ forvalues i=1/`dim1' {
+ if "`threshold'"=="" {
+ qui gen `prefix1'`i'=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(1/(1+exp(-`matdisc'[`i',1]*(lt1-`matdiff'[`i',1]))))^(`matacc'[`i',1])
+ }
+ else {
+ qui gen `prefix1'`i'=lt1>`matdiff'[`i',1]
+ }
+ local dess `dess' (line `prefix'`i' lt1)
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(off) ytitle("Probability of a positive response" title"") title("`title2'")
+ }
+ else if "`pcm'"==""{
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tau0=0
+ local tau1=`matdiff'[`i',1]
+ local D "1+exp(lt`d'-`tau1')"
+ forvalues k=2/`=`nbrsm1'+1' {
+ local tau`k'=`tau`=`k'-1''+`matdiff'[`i',1]+`rsm1`k''
+ local D "`D'+exp(`k'*lt1-`tau`k'') "
+ }
+ forvalues k=`=`nbrsm1'+1'(-1)0 {
+ tempname prob`k'
+ qui gen `prob`k''=exp(`k'*lt1-`tau`k'')/(`D')
+ local dess `dess' (line `prob`k'' lt1)
+ label variable `prob`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ }
+ }
+ else if "`pcm'"!=""{
+ forvalues j=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Item `j'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=1/`nbmodas' {
+ local tauj`j'k`k'=`tauj`j'k`=`k'-1''+`matdiff'[`j',`k']
+ local D "`D'+exp(`k'*lt1-`tauj`j'k`k'') "
+ }
+ forvalues k=`=`nbrsm1'+1'(-1)0 {
+ tempname prob`k'
+ qui gen `prob`k''=exp(`k'*lt1-`tauj`j'k`k'')/(`D')
+ local dess `dess' (line `prob`k'' lt1)
+ label variable `prob`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ }
+ }
+}
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `nbobs'
+gen `id'=_n
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+/*mkmat lt1-lt`dim' , matrix(lt)
+matrix Chol=cholesky(corr(`covmatrix'))
+*matrix list lt
+*matrix list Chol
+matrix lt=lt*Chol'
+matrix colnames lt=`names'
+
+*matrix list lt
+drop _all
+qui svmat lt*/
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"==""&"`rsm1'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"==""&"`rsm1'"==""&"`pcm'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+
+*set trace on
+
+local deb1=1
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ *set trace on
+ *local q=`i'-`dim`p''*/
+ qui compress
+ if "`pcm'"=="" {
+ tempname prob`=`nbrsm`d''+2'
+ qui gen `prob`=`nbrsm`d''+2''=0
+ local tau1=`matdiff'[`i',1]
+ local D "1+exp(lt`d'-`tau1')"
+ forvalues k=2/`=`nbrsm`d''+1' {
+ local tau`k'=`tau`=`k'-1''+`matdiff'[`i',1]+`rsm`d'`k''
+ *di "tau`k'=`tau`k''"
+ local D "`D'+exp(`k'*lt`d'-`tau`k'') "
+ }
+ }
+ else {
+ tempname prob`=`nbmodas'+1'
+ qui gen `prob`=`nbmodas'+1''=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(lt`d'-`tau1')"
+ forvalues k=2/`nbmodas' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ *di "tau`k'=`tau`k''"
+ local D "`D'+exp(`k'*lt`d'-`tau`k'') "
+ }
+ }
+ if "`threshold'"==""/*&"`rsm1'"==""*/ {
+ if "`rsm`d''"==""&"`pcm'"=="" {
+ tempname prob1
+ qui gen `prob1'=`prob`=`nbrsm`d''+2''+`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(1/(1+exp(-`matdisc'[`i',1]*(lt`d'-`matdiff'[`i',1]))))^(`matacc'[`i',1])
+ qui compress
+ }
+ else if "`rsm`d''"!=""{
+ forvalues k=`=`nbrsm`d''+1'(-1)1 {
+ tempname prob`k'
+ qui gen `prob`k''=exp(`k'*lt`d'-`tau`k'')/(`D')+`prob`=`k'+1''
+ qui compress
+ }
+ }
+ else if "`pcm'"!="" {
+ forvalues k=`nbmodas'(-1)1 {
+ tempname prob`k'
+ qui gen `prob`k''=exp(`k'*lt`d'-`tau`k'')/(`D')+`prob`=`k'+1''
+ qui compress
+ }
+ }
+ qui gen `prefix`d''`q'=0
+ if "`rsm1'"==""&"`pcm'"=="" {
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `matdiff'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ }
+ else if "`rsm1'"!="" {
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `matdiff'[`i',1]
+ }
+ else if "`pcm'"!="" {
+ forvalues k=1/`nbmodas' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ qui compress
+ if "`pcm'"=="" {
+ forvalues k=1/`=`nbrsm`d''+1' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`k''
+ qui drop `prob`k''
+ qui compress
+ }
+ }
+ else {
+ forvalues k=1/`nbmodas' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`k''
+ qui drop `prob`k''
+ qui compress
+ }
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ if "`pcm'"=="" {
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `matdiff'[`i',1]
+ qui gen `prefix`d''`q'=lt`d'>`matdiff'[`i',1]
+ qui compress
+ forvalues k=1/`=`nbrsm`d''+1' {
+ qui replace `prefix`d''`q'=`k' if lt`d'>=`tau`k''
+ qui compress
+ }
+ }
+ else {
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ forvalues k=1/`nbmodas' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`pcm'[`i',`k']
+ qui compress
+ }
+ }
+ }
+ local q=`q'+1
+ }
+ forvalues k=2/`=`nbrsm`d''+1' {
+ di _col(1) in gr "tau`k'" _col(20) in ye %8.4f `rsm`d'`k''
+ }
+}
+`line'
+di
+*set trace on
+
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+*matrix list `matcov'
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/old/simul2tl2plm.ado b/Modules/ado/personal/s/old/simul2tl2plm.ado
new file mode 100644
index 0000000..0393e40
--- /dev/null
+++ b/Modules/ado/personal/s/old/simul2tl2plm.ado
@@ -0,0 +1,71 @@
+program define simul2tl2plm
+version 7.0
+syntax [, nbobs(integer 2000) dim1(real 7) dim2(real 7) corr(real 0) disc1(real 1) disc2(real 1) sigma1(real 1) sigma2(real 1)]
+
+scalar define hour=real(substr("$S_TIME",1,2))
+scalar define min=real(substr("$S_TIME",4,2))
+scalar define sec=real(substr("$S_TIME",7,2))
+scalar define jour=real(substr("$S_DATE",1,2))
+
+if "$seed2"!="" {
+global seed2=int($seed/100000)}
+else {
+global seed2=0
+}
+global seed=sec*1000000+min*10000+hour*100+jour+$seed2
+
+set seed $seed
+quietly {
+drop _all
+set obs `nbobs'
+gen TL1=invnorm(uniform())*`sigma1'
+gen TL2=invnorm(uniform())*`sigma2'
+replace TL2=`corr'*TL1+sqrt(1-`corr'^2)*TL2
+
+local items=1
+global rep1
+while `items'<=`dim1' {
+local nitems=100+`items'
+gen diff`nitems'=invnorm(`items'/(`dim1'+1))
+gen prob`nitems'=1/(1+exp(-1.7*`disc1'*(TL1-diff`nitems')))
+gen rep`nitems'=0
+replace rep`nitems'=1 if prob`nitems'>=uniform()
+global rep1 $rep1 rep`nitems'
+local items=`items'+1
+}
+
+local items=1
+global rep2
+while `items'<=`dim2' {
+local nitems=200+`items'
+gen diff`nitems'=invnorm(`items'/(`dim2'+1))
+gen prob`nitems'=1/(1+exp(-1.7*`disc2'*(TL2-diff`nitems')))
+gen rep`nitems'=0
+replace rep`nitems'=1 if prob`nitems'>=uniform()
+global rep2 $rep2 rep`nitems'
+local items=`items'+1
+}
+gen ind=_n
+keep ind $rep1 $rep2}
+
+
+quietly{
+reshape long rep,i(ind) j(item)
+
+local items=1
+while `items'<=`dim1' {
+local nitems=100+`items'
+gen item`nitems'=0
+replace item`nitems'=-1 if item==`nitems'
+local items=`items'+1
+}
+local items=1
+while `items'<=`dim2' {
+local nitems=200+`items'
+gen item`nitems'=0
+replace item`nitems'=-1 if item==`nitems'
+local items=`items'+1
+}
+
+}/*fin du quietly*/
+end
diff --git a/Modules/ado/personal/s/sascfa.ado b/Modules/ado/personal/s/sascfa.ado
new file mode 100644
index 0000000..65e426f
--- /dev/null
+++ b/Modules/ado/personal/s/sascfa.ado
@@ -0,0 +1,10 @@
+program define sascfa,eclass
+version 11.0
+syntax anything [if] [in] ,partition(numlist) varname(string) lisrel(string) [batch]
+preserve
+*%macro CFA (dataset= , listeItems= , partition= , varname= , lisrel=);
+
+tosas `if' `in' , pgm(%include 'C:\ado\macros SAS\MACRO cfa.sas';%CFA(dataset=stata,listeItems=`anything', partition=`partition', varname=`varname',lisrel=`lisrel');) `batch'
+
+
+end
diff --git a/Modules/ado/personal/s/senspescore.ado b/Modules/ado/personal/s/senspescore.ado
new file mode 100644
index 0000000..b0b1c62
--- /dev/null
+++ b/Modules/ado/personal/s/senspescore.ado
@@ -0,0 +1,69 @@
+program define senspescore, rclass
+version 8
+syntax varlist(min=1 max=1 numeric) [, Group(varname) Threshold(string) INVerse]
+
+tempfile senspescorefile
+qui save `senspescorefile', replace
+
+qui sort `group'
+tempname p0 p1 n0 n1 q0
+qui count
+local nind=r(N)
+qui gen `n0'=.
+qui gen `n1'=.
+qui gen `p0'=.
+qui gen `p1'=.
+
+local l0=0
+local l1=1
+
+if "`inverse'"=="" {
+ local m0="<"
+ local m1=">"
+}
+else {
+ local m0=">"
+ local m1="<"
+}
+qui count if `group'==`l0'
+local group0=r(N)
+qui count if `group'==`l1'
+local group1=r(N)
+
+
+forvalues i=1/`nind' {
+ qui count if `varlist'`m0'`varlist'[`i']&`group'==`l0'
+ qui replace `n0'=`r(N)' in `i'
+ qui count if `varlist'`m1'`varlist'[`i']&`group'==`l1'
+ qui replace `n1'=`r(N)' in `i'
+ qui replace `p1'=`n`l1''/`group`l1'' in `i'
+ qui replace `p0'=`n`l0''/`group`l0'' in `i'
+}
+tempname diff min
+if "`threshold'"!="" {
+ qui gen `diff'=abs(`varlist'-`threshold')
+ qui sort `diff'
+ qui gen `min'=1 in 1
+}
+sort `varlist'
+
+label variable `n0' "N bien classées groupe `l0'"
+label variable `n1' "N bien classées groupe `l1'"
+label variable `p0' "Specificity"
+label variable `p1' "Sensibility"
+twoway line `n0' `n1' `varlist',name(n,replace) xline(`threshold')
+twoway line `p0' `p1' `varlist',name(p,replace) xline(`threshold')
+qui gen `q0'=1-`p0'
+label variable `q0' "1-Specificity"
+local scatter
+if "`threshold'"!="" {
+ local scatter "(scatter `p1' `q0' if `min'==1)"
+}
+twoway (line `p1' `q0') (line `q0' `q0') `scatter' ,name(roc,replace) legend(off)
+
+
+
+
+use `senspescorefile', clear
+end
+
diff --git a/Modules/ado/personal/s/sf36fr v1.6.ado b/Modules/ado/personal/s/sf36fr v1.6.ado
new file mode 100644
index 0000000..9b94869
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr v1.6.ado
@@ -0,0 +1,585 @@
+*! Version 1.6 23August2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.4 : December 1, 2018 [Jean-Benoit Hardouin] /*correction of a bug on SF12*/
+* Release 1.5 : July 29, 2019 [Jean-Benoit Hardouin] /*radar option*/
+* Release 1.6 : August 23, 2019 [Jean-Benoit Hardouin] /*correction of a bug to save the scores*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013, 2018, 2019 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string) RADar FILESave DIRSave(string)]
+
+*preserve
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Discrepancies" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(4) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(1) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(0) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(1) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(0) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.80130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!=""|"`radar'"!="" {
+ tempname radar
+ qui matrix `radar'=J(12,2,.)
+ if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ }
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ matrix `radar'[`c',1]=`means`i''
+ qui su `scoreref`i''
+ matrix `radar'[`c',2]=r(mean)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ if "`details'"!="" {
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ }
+ local ++c
+ }
+ if "`details'"!="" {
+ di "{hline 80}"
+ }
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+ if "`radar'"!=""&"`v2'"=="" {
+ qui tempfile radarfile
+ qui save `radarfile', replace
+ qui drop _all
+ qui svmat `radar'
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local c=1
+ qui gen name=""
+ foreach i in `listmin' {
+ qui replace name="`i'" in `c'
+ local ++c
+ }
+ qui rename `radar'1 scoreSF36
+ rename `radar'2 scoreSF36ref
+ qui keep in 1/10
+ label variable scoreSF36 "Sample"
+ label variable scoreSF36ref "General French population"
+ if "`filesave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ local saving "saving(`dirsave'//radar, replace) "
+ }
+ qui radar name scoreSF36 scoreSF36ref, note("") title("Comparison of the sample with the general French population") legend(lab(1 "Sample") lab(2 "General French population")) `saving'
+ qui use `radarfile', clear
+ }
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+*restore, preserve
+end
diff --git a/Modules/ado/personal/s/sf36fr v1.7.ado b/Modules/ado/personal/s/sf36fr v1.7.ado
new file mode 100644
index 0000000..8e8e665
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr v1.7.ado
@@ -0,0 +1,588 @@
+*! Version 1.7 29August2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.4 : December 1, 2018 [Jean-Benoit Hardouin] /*correction of a bug on SF12*/
+* Release 1.5 : July 29, 2019 [Jean-Benoit Hardouin] /*radar option*/
+* Release 1.6 : August 23, 2019 [Jean-Benoit Hardouin] /*correction of a bug to save the scores*/
+* Release 1.7 : August 29, 2019 [Jean-Benoit Hardouin] /*improvement of radar*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013, 2018, 2019 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string) RADar FILESave DIRSave(string)]
+
+*preserve
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Discrepancies" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+*list subjid `scoreinc' `inc1'-`inc15' `scoreinc' if `scoreinc'!=0&`scoreinc'!=.
+
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(4) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(1) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(0) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(1) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(0) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.80130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!=""|"`radar'"!="" {
+ tempname radar
+ qui matrix `radar'=J(12,2,.)
+ if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ }
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ matrix `radar'[`c',1]=`means`i''
+ qui su `scoreref`i''
+ matrix `radar'[`c',2]=r(mean)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ if "`details'"!="" {
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ }
+ local ++c
+ }
+ if "`details'"!="" {
+ di "{hline 80}"
+ }
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+ if "`radar'"!=""&"`v2'"=="" {
+ qui tempfile radarfile
+ qui save `radarfile', replace
+ qui drop _all
+ qui svmat `radar'
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local c=1
+ qui gen name=""
+ foreach i in `listmin' {
+ qui replace name="`i'" in `c'
+ local ++c
+ }
+ qui rename `radar'1 scoreSF36
+ rename `radar'2 scoreSF36ref
+ qui keep in 1/10
+ label variable scoreSF36 "Sample"
+ label variable scoreSF36ref "General French population"
+ if "`filesave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ local saving "saving(`dirsave'//radar, replace) "
+ }
+ qui radar name scoreSF36 scoreSF36ref, note("") title("Comparison of the sample with the general French population") legend(lab(1 "Sample") lab(2 "General French population")) `saving' r(0 20 40 60 80 100)
+ qui use `radarfile', clear
+ }
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+*restore, preserve
+end
diff --git a/Modules/ado/personal/s/sf36fr.ado b/Modules/ado/personal/s/sf36fr.ado
new file mode 100644
index 0000000..306b47c
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr.ado
@@ -0,0 +1,589 @@
+*! Version 1.8 13December2023
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.4 : December 1, 2018 [Jean-Benoit Hardouin] /*correction of a bug on SF12*/
+* Release 1.5 : July 29, 2019 [Jean-Benoit Hardouin] /*radar option*/
+* Release 1.6 : August 23, 2019 [Jean-Benoit Hardouin] /*correction of a bug to save the scores*/
+* Release 1.7 : August 29, 2019 [Jean-Benoit Hardouin] /*improvement of radar*/
+* Release 1.8 : December 13, 2023 [Jean-Benoit Hardouin] /*Correction for individuals with exactly 50% of missing data in a scale: they should be imputed (Ware, SF36 manual) but were not imputed before*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013, 2018, 2019, 2023 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string) RADar FILESave DIRSave(string)]
+
+*preserve
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Discrepancies" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+*list subjid `scoreinc' `inc1'-`inc15' `scoreinc' if `scoreinc'!=0&`scoreinc'!=.
+
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(5) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(2) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(1) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(2) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(1) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.80130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!=""|"`radar'"!="" {
+ tempname radar
+ qui matrix `radar'=J(12,2,.)
+ if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ }
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ matrix `radar'[`c',1]=`means`i''
+ qui su `scoreref`i''
+ matrix `radar'[`c',2]=r(mean)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ if "`details'"!="" {
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ }
+ local ++c
+ }
+ if "`details'"!="" {
+ di "{hline 80}"
+ }
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+ if "`radar'"!=""&"`v2'"=="" {
+ qui tempfile radarfile
+ qui save `radarfile', replace
+ qui drop _all
+ qui svmat `radar'
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local c=1
+ qui gen name=""
+ foreach i in `listmin' {
+ qui replace name="`i'" in `c'
+ local ++c
+ }
+ qui rename `radar'1 scoreSF36
+ rename `radar'2 scoreSF36ref
+ qui keep in 1/10
+ label variable scoreSF36 "Sample"
+ label variable scoreSF36ref "General French population"
+ if "`filesave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ local saving "saving(`dirsave'//radar, replace) "
+ }
+ qui radar name scoreSF36 scoreSF36ref, note("") title("Comparison of the sample with the general French population") legend(lab(1 "Sample") lab(2 "General French population")) `saving' r(0 20 40 60 80 100)
+ qui use `radarfile', clear
+ }
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+*restore, preserve
+end
diff --git a/Modules/ado/personal/s/sf36fr.hlp b/Modules/ado/personal/s/sf36fr.hlp
new file mode 100644
index 0000000..a7c8239
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr.hlp
@@ -0,0 +1,60 @@
+{smcl}
+{* 5May2013}{...}
+{hline}
+help for {hi:sf36fr}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Computation of the score of the French SF36 questionnaire}
+
+{p 8 14 2}{cmd:sf36fr} {it:varlist} [{it:if}] [,{cmdab:v2} {cmd:save}({it:prefix}) {cmd:saveref}({it:prefix}) {cmd:saveimp}({it:prefix}) {cmdab:rep:lace} {cmd:age}({it:varname}) {cmdab:sex}({it:varname}) {cmdab:det:ails}]
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:sf36fr} computes the scores of the French versions of the SF36 questionnaire based on the algorithm of the version 1.3. By default, version 1.3 of the questionnaire is assumed.
+For data provided using the version 2 of the SF36 questionnaire, this algorithm is adapted.
+
+{title:Options}
+
+{p 4 8 2}{it:varlist} must contain the name of the 36 variables representing the 36 items of the questionnaire in the same order than in the questionnaire.
+
+{p 4 8 2}{cmd:v2} is required if the version 2 of the SF36 questionnaire is used.
+
+{p 4 8 2}{cmd:save}({it:prefix}) saves the scores in new variables. The names of this variable are {it:prefix} followed by the names of the dimensions (PF RP BP GH VT SF RE MH PCS MCS).
+
+{p 4 8 2}{cmd:saveref}({it:prefix}) saves the scores of reference in new variables. The names of this variable are {it:prefix} followed by the names of the dimensions (PF RP BP GH VT SF RE MH PCS MCS).
+
+{p 4 8 2}{cmd:saveimp}({it:prefix}) saves the imputed values of each items in variables using the string as prefix followed the name of each items.
+
+{p 4 8 2}{cmdab:rep:lace} allows replacing the variables defined with the {cmd:save} and {cmd:saveref} options if required.
+
+{p 4 8 2}{cmd:age}({it:varname}) and {cmd:sex}({it:varname}) define the age and sex of the individuals in order to compute more precisely the scores of reference.
+
+{p 4 8 2}{cmdab:det:ails} displays tables of incoherencs and comparison between computed scores and scores of reference.
+
+
+{title:Example}
+
+ {cmd:. sf36fr sf36_1 - sf36_11d}
+
+ {cmd:. sf36fr sf36_1 - sf36_11d, v2 save(score) details replace}
+
+ {cmd:. sf36fr sf36_1 - sf36_11d, v2 save(score) details saveref(scoreref) age(age) sex(sexe)}
+
+
+{title:Reference}
+
+{p 4 8 2}{cmd:Leplège A, Ecosse E, Pouchot J, Coste J, Perneger T} (2001). Le questionnaire MOS-SF36 - Manuel de l'utilisateur et guide d'interprétation des scores. Estem: Paris.
+
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Biostatistics, Clinical Research and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
+
diff --git a/Modules/ado/personal/s/sf36fr.zip b/Modules/ado/personal/s/sf36fr.zip
new file mode 100644
index 0000000..3b360b8
Binary files /dev/null and b/Modules/ado/personal/s/sf36fr.zip differ
diff --git a/Modules/ado/personal/s/sf36fr1.4.ado b/Modules/ado/personal/s/sf36fr1.4.ado
new file mode 100644
index 0000000..03a7f2b
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr1.4.ado
@@ -0,0 +1,550 @@
+*! Version 1.4 1 December 2018
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.4 : December 1, 2018 [Jean-Benoit Hardouin] /*correction of a bug on SF12*/
+*
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+*
+* Faire sauvegarde des items imputés
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string)]
+
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Incoherences" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(4) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(1) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(0) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(1) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(0) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.80130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ local ++c
+ }
+ di "{hline 80}"
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+end
diff --git a/Modules/ado/personal/s/sf36fr1.5.ado b/Modules/ado/personal/s/sf36fr1.5.ado
new file mode 100644
index 0000000..09a64ed
--- /dev/null
+++ b/Modules/ado/personal/s/sf36fr1.5.ado
@@ -0,0 +1,585 @@
+*! Version 1.5 29July2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+*
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.4 : December 1, 2018 [Jean-Benoit Hardouin] /*correction of a bug on SF12*/
+* Release 1.5 : July 29, 2019 [Jean-Benoit Hardouin] /*radar option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013, 2018, 2019 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string) RADar FILESave DIRSave(string)]
+
+preserve
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Incoherences" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(4) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(1) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(0) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(1) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(0) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.80130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!=""|"`radar'"!="" {
+ tempname radar
+ qui matrix `radar'=J(12,2,.)
+ if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ }
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ matrix `radar'[`c',1]=`means`i''
+ qui su `scoreref`i''
+ matrix `radar'[`c',2]=r(mean)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ if "`details'"!="" {
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ }
+ local ++c
+ }
+ if "`details'"!="" {
+ di "{hline 80}"
+ }
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+ if "`radar'"!=""&"`v2'"=="" {
+ qui tempfile radarfile
+ qui save `radarfile', replace
+ qui drop _all
+ qui svmat `radar'
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local c=1
+ qui gen name=""
+ foreach i in `listmin' {
+ qui replace name="`i'" in `c'
+ local ++c
+ }
+ qui rename `radar'1 scoreSF36
+ rename `radar'2 scoreSF36ref
+ qui keep in 1/10
+ label variable scoreSF36 "Sample"
+ label variable scoreSF36ref "General French population"
+ if "`filesave'"!="" {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ local saving "saving(`dirsave'//radar, replace) "
+ }
+ qui radar name scoreSF36 scoreSF36ref, note("") title("Comparison of the sample with the general French population") legend(lab(1 "Sample") lab(2 "General French population")) `saving'
+ qui use `radarfile', clear
+ }
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+restore, preserve
+end
diff --git a/Modules/ado/personal/s/sf36frv13.ado b/Modules/ado/personal/s/sf36frv13.ado
new file mode 100644
index 0000000..fa497ef
--- /dev/null
+++ b/Modules/ado/personal/s/sf36frv13.ado
@@ -0,0 +1,549 @@
+*! Version 1.3 24 May 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Stata program : sf36fr
+* computes score of the French SF36 questionnnaire
+* Release 1 : May 2, 2013 [Jean-benoit Hardouin]
+* Release 1.1 : May 14, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+* Release 1.2 : May 21, 2013 [Jean-Benoit Hardouin] /*saveimp option*/
+* Release 1.3 : May 24, 2013 [Jean-Benoit Hardouin] /*correction of a bug on BP*/
+*
+*
+* Historic :
+* Version 1 (May 2, 2013) [Jean-Benoit Hardouin]
+*
+* Faire sauvegarde des items imputés
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2013 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 sf36fr , rclass
+version 8.2
+syntax varlist(min=36 max=36 numeric) [,v2 save(string) REPlace age(varname) SEXe(varname) saveref(string) DETails saveimp(string)]
+
+local nbitems : word count `varlist'
+if `nbitems'!=36 {
+ di in red "There is `nbitems' items defined instead of 36"
+}
+
+tokenize `varlist'
+local varlistsav `varlist'
+local sf gh1 ht pf1 pf2 pf3 pf4 pf5 pf6 pf7 pf8 pf9 pf10 rp1 rp2 rp3 rp4 re1 re2 re3 sf1 bp1 bp2 vt1 mh1 mh2 mh3 vt2 mh4 vt3 mh5 vt4 sf2 gh2 gh3 gh4 gh5
+local sf2
+local varlist2
+forvalues i=1/36 {
+ local j:word `i' of `sf'
+ tempname `j'
+ *di " qui gen `j'=``i''"
+ qui gen ``j''=``i''
+ local varlist2 "`varlist2' ``j''"
+}
+local varlist "`varlist2'"
+tokenize `varlist'
+*di "`varlist'"
+
+
+if "`v2'"=="" {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 5 6 5 6 6 6 6 6 6 6 6 6 5 5 5 5 5
+}
+else {
+ local modamax 5 5 3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
+}
+forvalues i=1/36 {
+ local mod`i':word `i' of `modamax'
+}
+local error=0
+local inf
+local sup
+local c=1
+foreach i of varlist `varlist' {
+ qui count if `i'<1
+ if `r(N)'>0 {
+ local error=1
+ local inf "`inf' `i'"
+ }
+ local tmp: word `c' of `modamax'
+ qui count if `i'>`c'
+ if `r(N)'>0 {
+ local error=1
+ local inf "`sup' `i'"
+ }
+ local ++c
+}
+forvalues i=1/15 {
+ tempname inc`i'
+}
+local liste1 11 12 11 12 11 12 11 12 30 24 27 23 1 20 21
+local liste2 3 3 4 4 6 6 9 9 25 26 29 31 36 32 22
+*tab `11' `3'
+qui gen `inc1'=`11'==1&`3'>1 if `11'!=.&`3'!=.
+* tab `inc`i''
+qui gen `inc2'=`12'==1&`3'>1 if `12'!=.&`3'!=.
+qui gen `inc3'=`11'==1&`4'>1 if `11'!=.&`4'!=.
+qui gen `inc4'=`12'==1&`4'>1 if `12'!=.&`4'!=.
+qui gen `inc5'=`11'==1&`6'>1 if `11'!=.&`6'!=.
+qui gen `inc6'=`12'==1&`6'>1 if `12'!=.&`6'!=.
+qui gen `inc7'=`11'==1&`9'>1 if `11'!=.&`9'!=.
+qui gen `inc8'=`12'==1&`9'>1 if `12'!=.&`9'!=.
+qui gen `inc9'=(`30'==1&`25'==1)|(`30'==`mod30'&`25'==`mod25') if `30'!=.&`25'!=.
+qui gen `inc10'=(`24'==1&`26'==1)|(`24'==`mod24'&`26'==`mod26') if `24'!=.&`26'!=.
+qui gen `inc11'=(`27'==1&`29'==1)|(`27'==`mod27'&`29'==`mod29') if `27'!=.&`29'!=.
+qui gen `inc12'=(`23'==1&`31'==1)|(`23'==`mod23'&`31'==`mod31') if `23'!=.&`31'!=.
+qui gen `inc13'=(`1'==1&`36'==`mod36')|(`1'==`mod1'&`36'==1) if `1'!=.&`36'!=.
+qui gen `inc14'=(`20'==1&`32'==1)|(`20'==`mod20'&`32'==`mod32') if `20'!=.&`32'!=.
+qui gen `inc15'=(`21'==1&`22'==`mod22')|(`21'==`mod21'&`22'==1) if `21'!=.&`22'!=.
+tempname scoreinc
+genscore `inc1'-`inc15',score(`scoreinc')
+if "`details'" !="" {
+ di "{hline 80}"
+ di in gr "Incoherences" _col(20) "item 1" _col(40) "item 2" _col(60) "# individuals"
+ di "{hline 80}"
+ *di "varlist:`varlistsav'"
+ forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ local ni1:word `i1' of `varlistsav'
+ local ni2:word `i2' of `varlistsav'
+ qui count if `inc`i''==1
+
+ di in gr "`i'" in ye _col(20) abbrev("`ni1'",19) _col(40) abbrev("`ni2'",19) %6.0f _col(67) `r(N)'
+ }
+ di "{hline 80}"
+}
+
+forvalues i=1/15 {
+ local i1:word `i' of `liste1'
+ local i2:word `i' of `liste2'
+ qui replace ``i1''=. if `inc`i''==1
+ qui replace ``i2''=. if `inc`i''==1
+}
+
+tempname imp scorepf scorerp scorebp scoregh scorevt scoresf scorere scoremh
+
+ /*PF*/
+ imputeitems `3' `4' `5' `6' `7' `8' `9' `10' `11' `12',max(4) noround prefix(`imp')
+ genscore `imp'`3' `imp'`4' `imp'`5' `imp'`6' `imp'`7' `imp'`8' `imp'`9' `imp'`10' `imp'`11' `imp'`12',score(`scorepf')
+ qui replace `scorepf'=(`scorepf'-10)/20*100
+ /*RP*/
+ imputeitems `13' `14' `15' `16',max(1) noround prefix(`imp')
+ genscore `imp'`13' `imp'`14' `imp'`15' `imp'`16',score(`scorerp')
+ qui replace `scorerp'=(`scorerp'-4)/4*100
+ /*BP*/
+ tempvar jb
+ qui gen `jb'=.
+ qui replace `jb'=6 if `21'==1&`22'==1
+ qui replace `jb'=5 if `21'>=2&`21'<=6&`22'==1
+ qui replace `jb'=4 if `22'==2&`21'!=.
+ qui replace `jb'=3 if `22'==3&`21'!=.
+ qui replace `jb'=2 if `22'==4&`21'!=.
+ qui replace `jb'=1 if `22'==5&`21'!=.
+ qui replace `jb'=6 if `22'==1&`21'==.
+ qui replace `jb'=4.75 if `22'==2&`21'==.
+ qui replace `jb'=3.5 if `22'==3&`21'==.
+ qui replace `jb'=2.25 if `22'==4&`21'==.
+ qui replace `jb'=1 if `22'==5&`21'==.
+ qui replace `22'=`jb'
+ if "`v2'"=="" {
+ qui recode `21' 1=6 2=5.4 3=4.2 4=3.1 5=2.2 6=1
+ }
+ else {
+ qui recode `21' 1=6 2=4.8 3=2.65 4=1
+ }
+ imputeitems `21' `22',max(0) noround prefix(`imp')
+* replace `imp'`21'=`21'
+* replace `imp'`22'=`22'
+ qui genscore `imp'`21' `imp'`22',score(`scorebp')
+* list sf36_7q_intensite_douleurs sf36_8q_douleurs_physiques `21' `22' `imp'`21' `imp'`22' `scorebp'
+ qui replace `scorebp'=(`scorebp'-2)/10*100
+*tab `scorebp'
+ /*GH*/
+ qui recode `1' 1=5 2=4.4 3=3.4 4=2 5=1
+ qui recode `34' 1=5 2=4 3=3 4=2 5=1
+ qui recode `36' 1=5 2=4 3=3 4=2 5=1
+ imputeitems `1' `33' `34' `35' `36',max(2) noround prefix(`imp')
+ genscore `imp'`1' `imp'`33' `imp'`34' `imp'`35' `imp'`36',score(`scoregh')
+ qui replace `scoregh'=(`scoregh'-5)/20*100
+ /*VT*/
+ if "`v2'"=="" {
+ qui recode `23' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `27' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `23' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `27' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `29' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `31' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `23' `27' `29' `31',max(1) noround prefix(`imp')
+ genscore `imp'`23' `imp'`27' `imp'`29' `imp'`31',score(`scorevt')
+ qui replace `scorevt'=(`scorevt'-4)/20*100
+ /*SF*/
+ if "`v2'"=="" {
+ qui recode `20' 1=5 2=4 3=3 4=2 5=1
+ }
+ else {
+ qui recode `20' 1=5 2=4 3=2.5 4=1
+ }
+ imputeitems `20' `32',max(0) noround prefix(`imp')
+ genscore `imp'`20' `imp'`32',score(`scoresf')
+ qui replace `scoresf'=(`scoresf'-2)/8*100
+ /*RE*/
+ imputeitems `17' `18' `19',max(1) noround prefix(`imp')
+ genscore `imp'`17' `imp'`18' `imp'`19',score(`scorere')
+ qui replace `scorere'=(`scorere'-3)/3*100
+ /*MH*/
+ if "`v2'"=="" {
+ qui recode `26' 1=6 2=5 3=4 4=3 5=2 6=1
+ qui recode `30' 1=6 2=5 3=4 4=3 5=2 6=1
+ }
+ else {
+ qui recode `26' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `30' 1=6 2=4.5 3=3.5 4=2 5=1
+ qui recode `24' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `25' 1=1 2=2 3=3.5 4=4.5 5=6
+ qui recode `28' 1=1 2=2 3=3.5 4=4.5 5=6
+ }
+ imputeitems `24' `25' `26' `28' `30',max(2) noround prefix(`imp')
+ genscore `imp'`24' `imp'`25' `imp'`26' `imp'`28' `imp'`30',score(`scoremh')
+ qui replace `scoremh'=(`scoremh'-5)/25*100
+ tempname scorepfz scorerpz scorebpz scoreghz scorevtz scoresfz scorerez scoremhz scorepcs scoremcs
+
+ /*scores composites*/
+ qui gen `scorepfz'=(`scorepf'-84.52404)/22.89490
+ qui gen `scorerpz'=(`scorerp'-81.19907)/33.79729
+ qui gen `scorebpz'=(`scorebp'-75.49196)/23.55879
+ qui gen `scoreghz'=(`scoregh'-72.21316)/20.16964
+ qui gen `scorevtz'=(`scorevt'-61.05453)/20.86942
+ qui gen `scoresfz'=(`scoresf'-83.59753)/22.37649
+ qui gen `scorerez'=(`scorere'-81.29467)/33.02717
+ qui gen `scoremhz'=(`scoremh'-74.84212)/18.01189
+ qui gen `scorepcs'=(`scorepfz'*0.42402+`scorerpz'*0.35119+`scorebpz'*0.31754+`scoreghz'*0.24954+`scorevtz'*0.02877-`scoresfz'*0.0753-`scorerez'*0.19206-`scoremhz'*0.22069)*10+50
+ qui gen `scoremcs'=(-`scorepfz'*0.22999-`scorerpz'*0.12329-`scorebpz'*0.09731-`scoreghz'*0.01571+`scorevtz'*0.23534+`scoresfz'*0.26876+`scorerez'*0.43407+`scoremhz'*0.48581)*10+50
+
+
+/*scores composites SF12*/
+tempname scoresf12p sf12p_1 sf12p_2a sf12p_2b sf12p_3a sf12p_3b sf12p_4a sf12p_4b sf12p_5 sf12p_6 sf12p_7a sf12p_7b sf12p_7c
+tempname scoresf12m sf12m_1 sf12m_2a sf12m_2b sf12m_3a sf12m_3b sf12m_4a sf12m_4b sf12m_5 sf12m_6 sf12m_7a sf12m_7b sf12m_7c
+ qui gen `sf12p_1'=`1'
+ qui gen `sf12p_2a'=`4'
+ qui gen `sf12p_2b'=`6'
+ qui gen `sf12p_3a'=`14'
+ qui gen `sf12p_3b'=`15'
+ qui gen `sf12p_4a'=`18'
+ qui gen `sf12p_4b'=`19'
+ qui gen `sf12p_5'=`20'
+ qui gen `sf12p_6'=`32'
+ qui gen `sf12p_7a'=`26'
+ qui gen `sf12p_7b'=`27'
+ qui gen `sf12p_7c'=`28'
+ qui gen `sf12m_1'=`1'
+ qui gen `sf12m_2a'=`4'
+ qui gen `sf12m_2b'=`6'
+ qui gen `sf12m_3a'=`14'
+ qui gen `sf12m_3b'=`15'
+ qui gen `sf12m_4a'=`18'
+ qui gen `sf12m_4b'=`19'
+ qui gen `sf12m_5'=`20'
+ qui gen `sf12m_6'=`32'
+ qui gen `sf12m_7a'=`26'
+ qui gen `sf12m_7b'=`27'
+ qui gen `sf12m_7c'=`28'
+ qui recode `sf12p_1' 5=0 4.4=-1.31872 3.4=-3.02396 2=-5.56461 1=-8.37399
+ qui recode `sf12m_1' 5=0 4.4=-0.06064 3.4=0.03482 2=-0.16891 1=-1.71175
+ qui recode `sf12p_2a' 1=-7.23216 2=-3.45555 3=0
+ qui recode `sf12m_2a' 1=3.93115 2=1.86840 3=0
+ qui recode `sf12p_2b' 1=-6.24397 2=-2.73557 3=0
+ qui recode `sf12m_2b' 1=2.68282 2=1.43103 3=0
+ qui recode `sf12p_3a' 1=-4.61617 2=0
+ qui recode `sf12m_3a' 1=1.44060 2=0
+ qui recode `sf12p_3b' 1=-5.51747 2=0
+ qui recode `sf12m_3b' 1=1.66968 2=0
+ qui recode `sf12p_4a' 1=3.04365 2=0
+ qui recode `sf12m_4a' 1=-6.82672 2=0
+ qui recode `sf12p_4b' 1=2.32091 2=0
+ qui recode `sf12m_4b' 1=-5.69921 2=0
+ qui recode `sf12p_6' 1=-0.33682 2=-0.94342 3=-0.18043 4=-0.11038 5=0
+ qui recode `sf12m_6' 1=-6.29724 2=-8.26066 3=-5.63286 4=-3.13896 5=0
+ if "`v2'"=="" {
+ qui recode `sf12p_5' 5=0 4=-3.83130 3=-6.50522 2=-8.38063 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 3=1.49384 2=1.76691 1=1.48619
+ qui recode `sf12p_7a' 6=0 5=0.66514 4=1.36689 3=2.37241 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 5=-1.94949 4=-4.09842 3=-6.31121 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 5=-0.42251 4=-1.14387 3=-1.61850 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 5=-0.92057 4=-1.65178 3=-3.29805 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3=2.34247 4=1.28044 5=0.41188 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3=-8.09914 4=-4.59055 5=-1.95934 6=0
+ }
+ else {
+ qui recode `sf12p_5' 5=0 4=-3.83130 2.5=-7.442925 1=-11.25544
+ qui recode `sf12m_5' 5=0 4=0.90384 2.5=1.630375 1=1.48619
+ qui recode `sf12p_7a' 6=0 4.5=1.016015 3.5=1.86965 2=2.90426 1=3.46638
+ qui recode `sf12m_7a' 6=0 4.5=-3.023955 3.5=-5.204815 2=-7.92717 1=-10.19085
+ qui recode `sf12p_7b' 6=0 4.5=-0.78319 3.5=-1.381185 2=-2.02168 1=-2.44706
+ qui recode `sf12m_7b' 6=0 4.5=-1.286175 3.5=-2.474915 2=-4.88962 1=-6.02409
+ qui recode `sf12p_7c' 1=4.61446 2=3.41593 3.5=1.811455 4.5=0.84616 6=0
+ qui recode `sf12m_7c' 1=-16.15395 2=-10.77911 3.5=-6.344845 4.5=-3.274945 6=0
+ }
+ qui gen `scoresf12p'=`sf12p_1'+`sf12p_2a'+`sf12p_2b'+`sf12p_3a'+`sf12p_3b'+`sf12p_4a'+`sf12p_4b'+`sf12p_5'+`sf12p_6'+`sf12p_7a'+`sf12p_7b'+`sf12p_7c'+56.57706
+ qui gen `scoresf12m'=`sf12m_1'+`sf12m_2a'+`sf12m_2b'+`sf12m_3a'+`sf12m_3b'+`sf12m_4a'+`sf12m_4b'+`sf12m_5'+`sf12m_6'+`sf12m_7a'+`sf12m_7b'+`sf12m_7c'+60.75781
+
+if "`save'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `save'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `save'`i'
+ if _rc==0 {
+ qui replace `save'`i'=`score`i''
+ }
+ else {
+ qui gen `save'`i'=`score`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+tempname scoreref1 scoreref0 scoreref01 scoreref scorerefv1 scorerefv0 scorerefv01 scorerefv
+matrix `scoreref1'=(96.65,95.80,86.82,82.36,67.86,89.76,93.14,72.85\95.75,91.16,83.60,76.07,64.50,86.50,90.64,72.08\94.41,90.76,81.03,73.13,64.32,86.37,89.07,71.01\92.27,88.64,79.02,72.27,66.06,86.69,90.00,71.53\82.32,79.81,70.21,65.97,60.19,83.33,83.00,71.10\76.58,74.74,67.10,62.37,58.21,79.74,80.04,71.16\67.16,61.28,63.99,58.61,53.93,76.16,66.67,70.24)
+matrix `scoreref0'=(94.92,89.54,79.37,71.81,60.32,79.65,81.65,64.92\92.42,85.98,80.19,75.10,60.57,82.83,86.13,68.18\91.04,88.87,78.27,74.64,61.94,84.14,85.48,67.59\86.23,85.54,71.97,69.14,58.90,79.80,83.42,64.84\77.88,77.85,66.23,65.10,58.18,78.29,77.61,66.17\71.60,68.74,62.40,61.23,55.08,76.47,73.24,65.45\58.20,52.46,59.68,59.73,47.94,71.68,62.21,60.63)
+matrix `scoreref01'=(95.65,92.18,82.51,76.26,63.52,83.93,86.47,68.29\93.93,88.34,81.75,75.54,62.35,84.51,88.19,69.94\92.71,89.80,79.63,73.89,63.12,85.24,87.26,69.28\89.25,87.09,75.50,70.70,62.48,83.24,86.71,68.19\79.99,78.78,68.12,65.51,59.14,80.69,80.19,68.52\73.69,71.24,64.37,61.71,56.39,77.84,76.05,67.84\62.40,56.67,61.72,59.20,50.86,73.80,64.38,65.29)
+matrix `scoreref'=(84.45,81.21,73.39,69.13,59.96,81.55,82.13,68.47\87.07,83.86,75.98,70.07,62.23,84.08,85.41,71.42\82.22,78.96,71.18,68.33,58.03,79.41,79.34,65.96)
+matrix `scorerefv1'=(11.78,15.33,17.21,13.93,14.16,14.43,20.73,15.28\9.64,21.30,19.63,15.89,16.72,19.05,24.18,15.83\11.08,23.63,21.00,16.20,16.65,18.97,26.12,16.70\14.92,26.35,22.09,17.41,16.24,17.01,23.15,16.23\20.48,32.67,22.24,17.93,16.89,20.35,32.04,17.40\22.78,36.05,24.06,19.08,18.03,21.94,33.89,16.60\27.44,40.86,24.38,17.61,18.86,24.08,41.43,20.03)
+matrix `scorerefv0'=(9.10,21.65,21.66,17.69,18.10,22.35,29.58,17.32\14.19,28.28,21.28,16.66,18.28,20.57,28.19,18.06\14.81,25.19,21.25,17.64,18.55,20.97,29.37,17.92\19.11,29.40,23.90,18.60,17.84,21.44,31.24,16.66\21.49,33.02,24.10,18.78,18.22,23.46,34.89,18.03\23.42,38.17,23.94,17.67,17.59,22.46,37.41,18.21\25.70,39.18,23.40,18.08,17.98,24.06,39.97,18.98)
+matrix `scorerefv01'=(10.33,19.46,20.21,17.00,16.94,20.00,26.80,16.83\12.44,25.45,20.60,16.31,17.69,19.96,16.51,17.18\13.19,24.43,21.15,16.95,17.66,20.02,27.85,17.40\17.39,27.92,23.25,18.06,17.41,19.64,27.65,16.76\21.11,32.83,23.29,18.37,17.61,22.16,33.63,17.88\23.27,37.40,24.09,18.28,17.83,22.29,36.13,17.77\26.85,40.16,23.92,17.83,18.62,24.13,40.67,20.04)
+matrix `scorerefv'=(21.19,32.20,23.73,18.57,18.05,21.41,32.15,17.62\19.85,30.48,23.03,18.39,17.36,20.08,29.89,16.70\22.02,33.43,24.10,18.69,18.40,22.26,33.71,17.99)
+
+tempname scorerefpf scorerefrp scorerefbp scorerefgh scorerefvt scorerefsf scorerefre scorerefmh
+tempname scorerefpfv scorerefrpv scorerefbpv scorerefghv scorerefvtv scorerefsfv scorerefrev scorerefmhv
+if "`age'"!=""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref0'[1,`c'] if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref0'[2,`c'] if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref0'[3,`c'] if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref0'[4,`c'] if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref0'[5,`c'] if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref0'[6,`c'] if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref0'[7,`c'] if `sexe'==0&`age'>=75
+ qui replace `scoreref`i''=`scoreref1'[1,`c'] if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref1'[2,`c'] if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref1'[3,`c'] if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref1'[4,`c'] if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref1'[5,`c'] if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref1'[6,`c'] if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref1'[7,`c'] if `sexe'==1&`age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv0'[1,`c'])^2 if `sexe'==0&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv0'[2,`c'])^2 if `sexe'==0&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv0'[3,`c'])^2 if `sexe'==0&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv0'[4,`c'])^2 if `sexe'==0&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv0'[5,`c'])^2 if `sexe'==0&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv0'[6,`c'])^2 if `sexe'==0&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv0'[7,`c'])^2 if `sexe'==0&`age'>=75
+ qui replace `scoreref`i'v'=(`scorerefv1'[1,`c'])^2 if `sexe'==1&`age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv1'[2,`c'])^2 if `sexe'==1&`age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv1'[3,`c'])^2 if `sexe'==1&`age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv1'[4,`c'])^2 if `sexe'==1&`age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv1'[5,`c'])^2 if `sexe'==1&`age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv1'[6,`c'])^2 if `sexe'==1&`age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv1'[7,`c'])^2 if `sexe'==1&`age'>=75
+ local ++c
+ }
+}
+else if "`age'"!=""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref01'[1,`c'] if `age'>=18&`age'<25
+ qui replace `scoreref`i''=`scoreref01'[2,`c'] if `age'>=25&`age'<35
+ qui replace `scoreref`i''=`scoreref01'[3,`c'] if `age'>=35&`age'<45
+ qui replace `scoreref`i''=`scoreref01'[4,`c'] if `age'>=45&`age'<55
+ qui replace `scoreref`i''=`scoreref01'[5,`c'] if `age'>=55&`age'<65
+ qui replace `scoreref`i''=`scoreref01'[6,`c'] if `age'>=65&`age'<75
+ qui replace `scoreref`i''=`scoreref01'[7,`c'] if `age'>=75
+ qui gen `scoreref`i'v'=(`scorerefv01'[1,`c'])^2 if `age'>=18&`age'<25
+ qui replace `scoreref`i'v'=(`scorerefv01'[2,`c'])^2 if `age'>=25&`age'<35
+ qui replace `scoreref`i'v'=(`scorerefv01'[3,`c'])^2 if `age'>=35&`age'<45
+ qui replace `scoreref`i'v'=(`scorerefv01'[4,`c'])^2 if `age'>=45&`age'<55
+ qui replace `scoreref`i'v'=(`scorerefv01'[5,`c'])^2 if `age'>=55&`age'<65
+ qui replace `scoreref`i'v'=(`scorerefv01'[6,`c'])^2 if `age'>=65&`age'<75
+ qui replace `scoreref`i'v'=(`scorerefv01'[7,`c'])^2 if `age'>=75
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"!="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ qui gen `scoreref`i''=`scoreref'[2,`c'] if `sexe'==1
+ qui replace `scoreref`i''=`scoreref'[3,`c'] if `sexe'==0
+ qui gen `scoreref`i'v'=(`scorerefv'[2,`c'])^2 if `sexe'==1
+ qui replace `scoreref`i'v'=(`scorerefv'[3,`c'])^2 if `sexe'==0
+ local ++c
+ }
+}
+else if "`age'"==""&"`sexe'"=="" {
+ local c=1
+ foreach i in pf rp bp gh vt sf re mh {
+ gen `scoreref`i''=`scoreref'[1,`c']
+ gen `scoreref`i'v'=(`scorerefv'[1,`c'])^2
+ local ++c
+ }
+}
+tempname scorerefpfz scorerefrpz scorerefbpz scorerefghz scorerefvtz scorerefsfz scorerefrez scorerefmhz scorerefpcs scorerefmcs
+tempname scorerefpfvz scorerefrpvz scorerefbpvz scorerefghvz scorerefvtvz scorerefsfvz scorerefrevz scorerefmhvz scorerefpcsv scorerefmcsv
+
+qui gen `scorerefpfz'=(`scorerefpf'-84.52404)/22.89490
+qui gen `scorerefrpz'=(`scorerefrp'-81.19907)/33.79729
+qui gen `scorerefbpz'=(`scorerefbp'-75.49196)/23.55879
+qui gen `scorerefghz'=(`scorerefgh'-72.21316)/20.16964
+qui gen `scorerefvtz'=(`scorerefvt'-61.05453)/20.86942
+qui gen `scorerefsfz'=(`scorerefsf'-83.59753)/22.37649
+qui gen `scorerefrez'=(`scorerefre'-81.29467)/33.02717
+qui gen `scorerefmhz'=(`scorerefmh'-74.84212)/18.01189
+qui gen `scorerefpcs'=(`scorerefpfz'*0.42402+`scorerefrpz'*0.35119+`scorerefbpz'*0.31754+`scorerefghz'*0.24954+`scorerefvtz'*0.02877-`scorerefsfz'*0.0753-`scorerefrez'*0.19206-`scorerefmhz'*0.22069)*10+50
+qui gen `scorerefmcs'=(-`scorerefpfz'*0.22999-`scorerefrpz'*0.12329-`scorerefbpz'*0.09731-`scorerefghz'*0.01571+`scorerefvtz'*0.23534+`scorerefsfz'*0.26876+`scorerefrez'*0.43407+`scorerefmhz'*0.48581)*10+50
+
+qui gen `scorerefpfvz'=(`scorerefpfv')/22.89490^2
+qui gen `scorerefrpvz'=(`scorerefrpv')/33.79729^2
+qui gen `scorerefbpvz'=(`scorerefbpv')/23.55879^2
+qui gen `scorerefghvz'=(`scorerefghv')/20.16964^2
+qui gen `scorerefvtvz'=(`scorerefvtv')/20.86942^2
+qui gen `scorerefsfvz'=(`scorerefsfv')/22.37649^2
+qui gen `scorerefrevz'=(`scorerefrev')/33.02717^2
+qui gen `scorerefmhvz'=(`scorerefmhv')/18.01189^2
+qui gen `scorerefpcsv'=(`scorerefpfvz'*0.42402^2+`scorerefrpvz'*0.35119^2+`scorerefbpvz'*0.31754^2+`scorerefghvz'*0.24954^2+`scorerefvtvz'*0.02877^2-`scorerefsfvz'*0.0753^2-`scorerefrevz'*0.19206^2-`scorerefmhvz'*0.22069^2)*10^2
+qui gen `scorerefmcsv'=(-`scorerefpfvz'*0.22999^2-`scorerefrpvz'*0.12329^2-`scorerefbpvz'*0.09731^2-`scorerefghvz'*0.01571^2+`scorerefvtvz'*0.23534^2+`scorerefsfvz'*0.26876^2+`scorerefrevz'*0.43407^2+`scorerefmhvz'*0.48581^2)*10^2
+
+
+
+
+
+if "`saveref'"!="" {
+ local listmin pf rp bp gh vt sf re mh pcs mcs
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS
+ local error=0
+ local list
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0&"`replace'"=="" {
+ local ++error
+ local list "`list' `saveref'`j'"
+ }
+ local ++c
+ }
+ local c=1
+ if `error'==0 {
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ capture confirm variable `saveref'`i'
+ if _rc==0 {
+ qui replace `saveref'`i'=`scoreref`i''
+ }
+ else {
+ qui gen `saveref'`i'=`scoreref`i''
+ }
+ local ++c
+ }
+ }
+ else {
+ di in red "The variable(s) `list' already exist(s)"
+ }
+}
+
+if "`details'"!="" {
+ di "{hline 80}"
+ di in gr _col(12) "Sample" _col(51) "Reference"
+ di in gr "Dimension" _col(16) "N" _col(21) "Mean" _col(29) "s.d." _col(40) "Min-Max" _col(52) "Mean" _col(60) "s.d." _col(72) "p"
+ di "{hline 80}"
+ local listmin pf rp bp gh vt sf re mh pcs mcs sf12p sf12m
+ local listmaj PF RP BP GH VT SF RE MH PCS MCS SF12P SF12M
+ local c=1
+ foreach i in `listmin' {
+ local j:word `c' of `listmaj'
+ qui su `score`i''
+ local means`i'=r(mean)
+ local sds`i'=r(sd)
+ local mins`i'=r(min)
+ local maxs`i'=r(max)
+ local n`i'=r(N)
+ if "`i'"!="sf12p"&"`i'"!="sf12m" {
+ qui su `scoreref`i'' if `score`i''!=.
+ local meanr`i'=r(mean)
+ local sdr`i'=r(sd)
+ local vr`i'=(`sdr`i'')^2
+ qui su `scoreref`i'v' if `score`i''!=.
+ local meanvr`i'=r(mean)
+ local sdr`i'=sqrt(`vr`i''+`meanvr`i'')
+ *local minr`i'=r(min)
+ *local maxr`i'=r(max)
+ qui ttest `score`i''=`meanr`i''
+ local p`i'=r(p)
+ }
+ di in gr "`j'" in ye _col(12) %5.0f `n`i'' _col(20) %5.2f `means`i'' _col(28) %5.2f `sds`i'' _col(34) %6.2f `mins`i'' "-" %6.2f `maxs`i'' _col(51) %5.2f `meanr`i'' _col(59) %5.2f `sdr`i'' _col(67) %6.4f `p`i''
+ local ++c
+ }
+ di "{hline 80}"
+ *corr `scorepcs' `scoremcs' `scoresf12p' `scoresf12m'
+ *scatter `scorepcs' `scoresf12p' ,name(p)
+ *scatter `scoremcs' `scoresf12m' ,name(m)
+ *su `scoresf12p' `sf12p_1' `sf12p_2a' `sf12p_2b' `sf12p_3a' `sf12p_3b' `sf12p_4a' `sf12p_4b' `sf12p_5' `sf12p_6' `sf12p_7a' `sf12p_7b' `sf12p_7c'
+ *su `scoresf12m' `sf12m_1' `sf12m_2a' `sf12m_2b' `sf12m_3a' `sf12m_3b' `sf12m_4a' `sf12m_4b' `sf12m_5' `sf12m_6' `sf12m_7a' `sf12m_7b' `sf12m_7c'
+
+}
+if "`saveimp'"!="" {
+*su
+ foreach i of numlist 1 3/36 {
+ local j:word `i' of `varlistsav'
+ *di "gen `saveimp'`j'=`imp'``i''"
+ capture confirm variable `saveimp'`j'
+ if _rc==0&"`replace'"=="" {
+ di in ye "The variable `saveimp'`j' already exists and cannot be replaced."
+ }
+ else if _rc==0&"`replace'"!="" {
+ qui replace `saveimp'`j'=`imp'``i''
+ }
+ else {
+ qui gen `saveimp'`j'=`imp'``i''
+ }
+ }
+}
+end
diff --git a/Modules/ado/personal/s/simirt - Copie.ado b/Modules/ado/personal/s/simirt - Copie.ado
new file mode 100644
index 0000000..225fed2
--- /dev/null
+++ b/Modules/ado/personal/s/simirt - Copie.ado
@@ -0,0 +1,762 @@
+*! version 4.3 August 29, 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+* Version 4.2 : June 19, 2018 (Jean-Benoit Hardouin) /*correction of a small bug with rsm2 option*/
+* Version 4.3 : August 29, 2019 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 20130 2018, 2019 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ capture use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt v4.1.ado b/Modules/ado/personal/s/simirt v4.1.ado
new file mode 100644
index 0000000..8c6c858
--- /dev/null
+++ b/Modules/ado/personal/s/simirt v4.1.ado
@@ -0,0 +1,760 @@
+*! version 4.1 December 17, 2013
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 2013 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`dim1'+1/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`modamax'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt v4.2.ado b/Modules/ado/personal/s/simirt v4.2.ado
new file mode 100644
index 0000000..4fd035b
--- /dev/null
+++ b/Modules/ado/personal/s/simirt v4.2.ado
@@ -0,0 +1,761 @@
+*! version 4.2 June 19, 2018
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+* Version 4.2 : June 19, 2018 (Jean-Benoit Hardouin) /*correction of a small bug with rsm2 option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 2013 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt v4.3.ado b/Modules/ado/personal/s/simirt v4.3.ado
new file mode 100644
index 0000000..225fed2
--- /dev/null
+++ b/Modules/ado/personal/s/simirt v4.3.ado
@@ -0,0 +1,762 @@
+*! version 4.3 August 29, 2019
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+* Version 4.2 : June 19, 2018 (Jean-Benoit Hardouin) /*correction of a small bug with rsm2 option*/
+* Version 4.3 : August 29, 2019 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 20130 2018, 2019 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ capture use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt v4.4.ado b/Modules/ado/personal/s/simirt v4.4.ado
new file mode 100644
index 0000000..c2ed779
--- /dev/null
+++ b/Modules/ado/personal/s/simirt v4.4.ado
@@ -0,0 +1,764 @@
+*! version 4.4 March 21, 2022
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+* Version 4.2 : June 19, 2018 (Jean-Benoit Hardouin) /*correction of a small bug with rsm2 option*/
+* Version 4.3 : August 29, 2019 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+* Version 4.4 : March 21, 2022 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 20130 2018, 2019, 2022 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ keep id lt* item*
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ capture use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt.ado b/Modules/ado/personal/s/simirt.ado
new file mode 100644
index 0000000..613e300
--- /dev/null
+++ b/Modules/ado/personal/s/simirt.ado
@@ -0,0 +1,801 @@
+*! version 4.5 March 21, 2022
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* Simirt: Simulation of dichotomous or polytomous data following an IRT model (Rasch model,
+* OPLM, Birnbaum model, 3-PLM, 4-PLM, 5-PAM, RSM,PCM)
+*
+* Version 1 : May 9, 2005 (Jean-Benoit Hardouin)
+* Version 1.1 : December 8, 2005 (Jean-Benoit Hardouin) /*group and deltagroup options*/
+* Version 2 : January 20, 2006 (Jean-Benoit Hardouin) /*Rating Scale model*/
+* Version 2.1 : Februar 2, 2006 (Jean-Benoit Hardouin) /*Threshold variables*/
+* Version 2.2 : Februar 8, 2006 (Jean-Benoit Hardouin) /*Correction of an error with the RSM model*/
+* Version 2.3 : October 22, 2006 (Jean-Benoit Hardouin) /*The "real" rating scale model*/
+* Version 2.4 : July 7, 2008 (Jean-Benoit Hardouin) /*Title for the graphs*/
+* Version 3 : October 14, 2008 (Jean-Benoit Hardouin) /*3 dimensions + correction for the mu vector*/
+* Version 3.1 : December 11, 2008 (Jean-Benoit Hardouin) /*remove an useless output*/
+* Version 3.2 : November 26, 2009 (Jean-Benoit Hardouin) /*covmatrix option*/
+* Version 3.3 : October 25, 2011 (Jean-Benoit Hardouin) /*pcm option*/
+* Version 3.4 : May 7, 2013 (Jean-Benoit Hardouin) /*Minor corrections, norandom option*/
+* Version 3.5 : May 16, 2013 (Jean-Benoit Hardouin) /*Minor corrections*/
+* Version 4 : December 11, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*GPCM + genp, genicc, icc options*/
+* Version 4.1 : December 17, 2013 (Jean-Benoit Hardouin, Myriam Blanchin) /*drawall option*/
+* Version 4.2 : June 19, 2018 (Jean-Benoit Hardouin) /*correction of a small bug with rsm2 option*/
+* Version 4.3 : August 29, 2019 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+* Version 4.4 : March 21, 2022 (Jean-Benoit Hardouin) /*correction of a small bug with store option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences (UPRES EA 4275 SPHERE)
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+*
+* Copyright 2005-2006, 2008-2009, 2011, 20130 2018, 2019, 2022 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 simirt , rclass
+version 8.0
+syntax [, NBObs(integer 2000) Dim(string) MU(string) COV(string) COVMatrix(string) DISc(string) DIFf(string) PMIN(string) PMAX(string) ACC(string) clear STOre(string) REPlace PREFix(string) DRAW drawall ICC GRoup(real 0) noRANDom DELtagroup(real 0) rsm1(string) rsm2(string) THReshold TITle(string) PCM(string) id(string) GENProba GENIcc]
+
+
+/********************************************************************************
+TESTS
+********************************************************************************/
+
+
+if `group'<0|`group'>1 {
+ di in red "{p}The {hi:group} option defines a probability. The values defined by this option must be greater (or equal) to 0 and lesser (or equal) to 1.{p_end}"
+ error 198
+ exit
+}
+
+if "`clear'"==""&"`store'"=="" {
+ di in red "You must use at least one of these two options: clear and/or store."
+ error 198
+ exit
+}
+
+if "`dim'"!="" {
+ local nbdim:word count `dim'
+ if `nbdim'>2&"`covmatrix'"=="" {
+ di in red "You can simulate data with one or two dimensions, and you have indicated `nbdim' dimensions in the {hi:dim} option. Please correct it."
+ error 198
+ exit
+ }
+ if "`covmatrix'"!="" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbdim'!=`nbrowcovm' {
+ di in red "{p 0 0 0}You define `nbdim' dimension(s) with the {cmd:dim} option and `nbrowcovm' dimension(s) with the {cmd:covmatrix} option. Please correct that."
+ error 198
+ exit
+ }
+ }
+ local nbitems=0
+ forvalues d=1/`nbdim' {
+ local dim`d':word `d' of `dim'
+ local nbitems=`nbitems'+`dim`d''
+ }
+ local dim=`nbdim'
+
+ if "`diff'"!="" {
+ local nbdiff:word count `diff'
+ local tmp:word 1 of `diff'
+ if "`tmp'"=="gauss"|"`tmp'"=="uniform" {
+ local typediff values
+ }
+ else if `nbdiff'!=`nbitems' {
+ di in red "You have indicated a number of difficulty parameters ({hi:diff} option) different of the number of items to simulate ({hi:dim} option). Please correct these options."
+ error 198
+ exit
+ }
+ }
+ else if "`diff'"=="" {
+ local diff gauss
+ forvalues d=1/`dim' {
+ local diff `diff' 0 1
+ }
+ local typediff gauss
+ local nbdiff:word count `diff'
+ }
+}
+else if "`dim'"==""{
+ if "`diff'"==""&"`pcm'"=="" {
+ di in red "{p 0 0 0}You must indicate the number of items to simulate with the {hi:dim}, the {hi:pcm} or the {hi:diff} option(s)."
+ error 198
+ exit
+ }
+ else if "`covmatrix'"!= "" {
+ local nbrowcovm=rowsof(`covmatrix')
+ if `nbrowcovm'>1 {
+ di in red "{p 0 0 0}You have define `nbrowcovm' dimensions with the {hi:covmatrix} option, but you do not affect each item to a specific dimension using the {hi:dim} option. Please define the {hi:dim} option."
+ error 198
+ exit
+ }
+ }
+ else if "`pcm'"!="" {
+ local nbitems=rowsof(`pcm')
+ local dim=1
+ local dim1=`nbitems'
+ }
+ else {
+ local nbdiff:word count `diff'
+ local nbitems=`nbdiff'
+ local dim=1
+ local dim1=`nbitems'
+ }
+}
+
+if (`group'!=0|`deltagroup'!=0)&`dim'!=1 {
+ di in red "The {hi:group} and the {hi:deltagroup} options are available only with unidimensional simulated data."
+ error 198
+ exit
+}
+
+if "`prefix'"=="" {
+ local prefix item
+}
+
+local nbprefix:word count `prefix'
+if `nbprefix'!=`dim'&`nbprefix'!=1 {
+ di in red "{p 0 0 0}The {hi:prefix} option is incorrect because the number of defined prefixes (`nbprefix') is different of the number of dimensions (`dim'). Please correct it."
+ error 198
+ exit
+}
+if `nbprefix'==`dim' {
+ forvalues d=1/`dim' {
+ local prefix`d':word `d' of `prefix'
+ }
+}
+else {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ local prefix`d' `prefix'`tmp'
+ }
+}
+if "`covmatrix'"=="" {
+ tempname covmatrix2
+ local nbcov:word count `cov'
+
+ if `dim'==1 {
+ if "`cov'"=="" {
+ local cov=1
+ }
+ if `nbcov'>1 {
+ di in red "You simulate one dimension. You must indicate only the variance of the simulated latent trait in the {hi:cov} option."
+ error 198
+ exit
+ }
+ if `cov'<0 {
+ di in red "The variance of your latent trait can not be negative. Please correct your {hi:cov} option."
+ error 198
+ }
+ matrix `covmatrix2'=(`cov')
+ }
+ else if `dim'==2 {
+ if `nbcov'!=3&`nbcov'>0 {
+ di in red "You simulate two dimensions. You must indicate exactly 3 values in the {hi:cov} option (Variance of the first simulated latent trait, Variance of the second simulated latent trait, Covariance between the two simulated latent traits)."
+ error 198
+ exit
+ }
+ else if `nbcov'==0 {
+ if `dim'==1 {
+ local cov "1"
+ }
+ else if `dim'==2 {
+ local cov "1 1 0"
+ }
+ local nbcov:word count `cov'
+ }
+ if `nbcov'==3 {
+ local cov1:word 1 of `cov'
+ local cov2:word 2 of `cov'
+ local cov3:word 3 of `cov'
+ local rho=`cov3'/sqrt(`cov1'*`cov2')
+ if `cov1'<0|`cov2'<0|`rho'<-1|`rho'>1 {
+ di in red "Your covariance matrix defined by the {hi:cov} option is not correct. Please correct it."
+ error 198
+ exit
+ }
+ }
+ matrix `covmatrix2'=(`cov1' , `cov3' \ `cov3' , `cov2')
+ }
+ local covmatrix `covmatrix2'
+}
+
+local nbmu:word count `mu'
+if `nbmu'!=`dim'&`nbmu'!=0 {
+ di in red "You must indicate as many values in the {hi:mu} option as the number of dimension(s) (`dim')"
+ error 198
+ exit
+}
+local nbdisc:word count `disc'
+if `nbdisc'!=`nbitems'&`nbdisc'!=0 {
+ di in red "You must indicate as many values in the {hi:disc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmin:word count `pmin'
+if `nbpmin'!=`nbitems'&`nbpmin'!=0 {
+ di in red "You must indicate as many values in the {hi:pmin} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbpmax:word count `pmax'
+if `nbpmax'!=`nbitems'&`nbpmax'!=0 {
+ di in red "You must indicate as many values in the {hi:pmax} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+local nbacc:word count `acc'
+if `nbacc'!=`nbitems'&`nbacc'!=0 {
+ di in red "You must indicate as many values in the {hi:acc} option as items defined by the {hi:dim} and the {hi:diff} options (`nbitems')"
+ error 198
+ exit
+}
+
+if ("`threshold'"!="")&("`disc'"!=""|"`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:threshold} option, you cannot define the {hi:disc}, {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:rsm1} and/or {hi:rsm2} option(s), you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`pcm'"!="")&("`pmin'"!=""|"`pmax'"!=""|"`acc'"!="") {
+ di in red "If you use the {hi:pcm} option, you cannot define the {hi:pmin}, {hi:pmax} or {hi:acc} options"
+ error 198
+ exit
+}
+if ("`rsm1'"!=""|"`rsm2'"!="")&("`pcm'"!="") {
+ di in red "You cannot use in the same time the {hi:rsm1} and/or {hi:rsm2} options with the {hi:pcm} option"
+ error 198
+ exit
+}
+if "`rsm2'"!=""&`dim'==1 {
+ di in red "You cannot define the {hi:rsm2} option if you simulate only one dimension"
+ error 198
+ exit
+}
+if "`id'"=="" {
+ local id="id"
+}
+
+preserve
+
+tempfile saveraschbin
+capture qui save `saveraschbin'
+
+
+
+
+/********************************************************************************
+PARAMETERS
+********************************************************************************/
+
+
+local hour=real(substr("$S_TIME",1,2))
+local min=real(substr("$S_TIME",4,2))
+local sec=real(substr("$S_TIME",7,2))
+local jour=real(substr("$S_DATE",1,2))
+
+
+
+
+if "$seed"!="" {
+ global seed2=int($seed)
+}
+else {
+ global seed2=0
+}
+global seed=$seed2+256484+`sec'*1000000+`min'*10000+`hour'*100+`jour'
+while $seed>2^31-1 {
+ global seed=int($seed/231)
+}
+qui set seed $seed
+
+if "`typediff'"=="uniform" {
+ if `nbdiff'==`=`dim'*2+1' {
+ local min`d':word `=(`d'-1)*2+2' of `diff'
+ local max`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ else if `nbdiff'==1 {
+ local min`d'=-2
+ local max`d'=2
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local diff `diff' `=`min`d''+(`max`d''-`min`d'')*`i'/(`dim`d''+1)'
+ }
+ }
+}
+else if "`typediff'"=="gauss" {
+ if `nbdiff'==`=`dim'*2+1' {
+ forvalues d=1/`dim' {
+ local mean`d':word `=(`d'-1)*2+2' of `diff'
+ local var`d':word `=(`d'-1)*2+3' of `diff'
+ }
+ }
+ else if `nbdiff'==1 {
+ forvalues d=1/`dim' {
+ local mean`d'=0
+ local var`d'=1
+ }
+ }
+ else {
+ di in red "Your {hi:diff} option is uncorrect. Please correct it."
+ error 198
+ exit
+ }
+ local diff
+ forvalues d=1/`dim' {
+ forvalues i=1/`dim`d'' {
+ local tmp=invnorm(`i'/(`dim`d''+1))*sqrt(`var`d'')+`mean`d''
+ local diff `diff' `tmp'
+ }
+ }
+}
+
+forvalues d=1/`dim' {
+ if "`rsm`d''"!="" {
+ local nbrsm`d':word count `rsm`d''
+ forvalues i=2/`=`nbrsm`d''+1' {
+ local rsm`d'`i':word `=`i'-1' of `rsm`d''
+ if "`threshold'"!=""&`rsm`d'`i''<0 {
+ di in red "With the {hi:threshold} option, the numbers defined in the {hi:rsm1} and {hi:rsm2} options must be positive."
+ error 198
+ exit
+ }
+ }
+ }
+}
+if "`diff'"!=""&"`pcm'"=="" {
+ tempname pcm
+ qui matrix `pcm'=J(`nbitems',1,.)
+ forvalues j=1/`nbitems' {
+ local tmp:word `j' of `diff'
+ qui matrix `pcm'[`j',1]=`tmp'
+ }
+}
+
+
+tempname matmu matcov matdiff matdisc matpmin matpmax matacc
+matrix define `matdiff'=J(`nbitems',1,0)
+matrix define `matdisc'=J(`nbitems',1,0)
+matrix define `matpmin'=J(`nbitems',1,0)
+matrix define `matpmax'=J(`nbitems',1,0)
+matrix define `matacc'=J(`nbitems',1,0)
+matrix define `matmu'=J(`dim',1,0)
+matrix define `matcov'=J(`=(`dim'+1)*`dim'/2',1,0)
+
+forvalues i=1/`nbitems'{
+ if `nbdisc'!=0 {
+ local tmp:word `i' of `disc'
+ matrix `matdisc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matdisc'[`i',1]=1
+ }
+}
+
+if "`pcm'"==""|"`rsm1'"!="" {
+ tempname pcm
+ if "`rsm1'"=="" {
+ forvalues i=1/`nbitems' {
+ local tmp:word `i' of `diff'
+ matrix `matdiff'[`i',1]=`tmp'
+ }
+ matrix `pcm'=`matdiff'
+ }
+ else {
+ local moda1:word count `rsm1'
+ local moda2:word count `rsm2'
+ local nbmodas=max(`=`moda1'+1',`=`moda2'+1')
+ matrix `pcm'=J(`nbitems',`nbmodas',.)
+ forvalues i=1/`dim1' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm1'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ if "`rsm2'"!="" {
+ forvalues i=`=`dim1'+1'/`=`dim1'+`dim2'' {
+ local tmp:word `i' of `diff'
+ matrix `pcm'[`i',1]=`tmp'
+ forvalues j=1/`=`nbmodas'-1' {
+ local tmp:word `j' of `rsm2'
+ matrix `pcm'[`i',`=1+`j'']=`pcm'[`i',1]+`tmp'
+ }
+ }
+ }
+ }
+}
+local nbmodas=colsof(`pcm')
+forvalues j=1/`nbitems' {
+ local pcmpj`j'k0=-999999999999999
+ forvalues k=1/`nbmodas' {
+ local pcmpj`j'k`k'=`pcm'[`j',`k']
+ if `pcmpj`j'k`k''!=. {
+ local nbmodas`j'=`k'
+ }
+ local tmp=`k'-1
+ if "`threshold'"!=""&`pcmpj`j'k`k''<`pcmpj`j'k`tmp'' {
+ di in red "With the {hi:threshold} option, the difficulties of a given item must increase."
+ error 198
+ exit
+ }
+ }
+}
+
+
+forvalues i=1/`nbitems' {
+ if `nbpmin'!=0 {
+ local tmp:word `i' of `pmin'
+ matrix `matpmin'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmin'[`i',1]=0
+ }
+ if `nbpmax'!=0 {
+ local tmp:word `i' of `pmax'
+ matrix `matpmax'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matpmax'[`i',1]=1
+ }
+ if `nbacc'!=0 {
+ local tmp:word `i' of `acc'
+ matrix `matacc'[`i',1]=`tmp'
+ }
+ else {
+ matrix `matacc'[`i',1]=1
+ }
+}
+
+if "`covmatrix'"=="" {
+ tempname covmatrix
+ if `nbcov'==1 {
+ matrix `covmatrix'=(`cov')
+ }
+ if `nbcov'==3 {
+ local tmp1:word 1 of `cov'
+ local tmp2:word 2 of `cov'
+ local tmp12:word 3 of `cov'
+ matrix `covmatrix'=(`tmp1',`tmp12'\`tmp12',`tmp2')
+ }
+}
+matrix `matcov'=`covmatrix'
+if (`nbmu'==`dim') {
+ forvalues d=1/`dim' {
+ local tmp:word `d' of `mu'
+ matrix `matmu'[`d',1]=`tmp'
+ }
+}
+if `dim'==2 {
+ local corr=`covmatrix'[1,2]/sqrt(`covmatrix'[1,1]*`covmatrix'[2,2])
+}
+
+
+
+/********************************************************************************
+SIMULATION
+********************************************************************************/
+
+
+drop _all
+qui set obs `=`nbobs'+2001'
+qui gen `id'=_n
+tempname graphobs
+qui gen `graphobs'=`id'>`nbobs'
+local names
+forvalues d=1/`dim' {
+ qui gen x`d'=invnorm(uniform())
+ qui compress
+ local names `names' lt`d'
+}
+
+matrix Chol=cholesky(corr(`covmatrix'))
+forvalues d=1/`dim' {
+ qui gen lt`d'=0
+ forvalues i=1/`d' {
+ qui replace lt`d'=lt`d'+Chol[`d',`i']*x`i'
+ }
+ qui compress
+}
+qui drop x*
+forvalues d=1/`dim' {
+ qui replace lt`d'=lt`d'*sqrt(`covmatrix'[`d',`d'])+`matmu'[`d',1]
+ qui compress
+}
+qui replace lt1=_n-`nbobs' if `graphobs'
+qui replace lt1=(lt1-1001)/1000*4*sqrt(`covmatrix'[1,1])+`matmu'[1,1] if `graphobs'
+
+if `dim'==1&`group'!=0 {
+ if "`random'"=="" {
+ qui gen group=uniform()<`group'
+ }
+ else {
+ qui gen group=`id'<=`group'*`nbobs'
+ }
+ qui replace lt1=lt1+`deltagroup'*(1-`group') if group==1
+ qui replace lt1=lt1-`deltagroup'*`group' if group==0
+ qui compress
+}
+
+di in gr "Number of individuals: " in ye `nbobs'
+di
+
+if "`threshold'"=="" {
+ local line di in gr "{hline 75}"
+}
+else {
+ local line di in gr "{hline 27}"
+}
+
+if "`threshold'"=="" {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty" _col(34) "Discr." _col(45) "Pmin" _col(58) "Pmax" _col(73) "Acc"
+}
+else {
+ `line'
+ di _col(1) in gr "Items" _col(18) "Difficulty"
+}
+local dim0=0
+local deb1=1
+local fin0=0
+local fin1=`dim1'
+
+forvalues d=1/`dim' { /* FOREACH DIMENSION*/
+ local deb`d'=`fin`=`d'-1''+1
+ local fin`d'=`deb`d''+`dim`d''-1
+ `line'
+ local p=`d'-1
+ local q=1
+ forvalues i=`deb`d''/`fin`d'' { /*FOREACH ITEM*/
+ qui compress
+ tempname prob`i'_`=`nbmodas`i''+1' est`i'
+ qui gen `prob`i'_`=`nbmodas`i''+1''=0
+ qui gen `est`i''=.
+ local tau0=0
+ local tau1=`pcm'[`i',1]
+ local D "1+exp(`matdisc'[`i',1]*(lt`d'-`tau1'))"
+ forvalues k=2/`nbmodas`i'' {
+ local tau`k'=`tau`=`k'-1''+`pcm'[`i',`k']
+ local D "`D'+exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k'')) "
+ }
+ if "`threshold'"=="" {
+ tempname icc`i'
+ qui gen `icc`i''=0
+ tempname proba`i'_0 best`i'_0
+ gen `proba`i'_0'=1
+ forvalues k=`nbmodas`i''(-1)1 {
+ tempname prob`i'_`k' proba`i'_`k' best`i'_`k'
+ qui gen `proba`i'_`k''=`matpmin'[`i',1]+(`matpmax'[`i',1]-`matpmin'[`i',1])*(exp(`matdisc'[`i',1]*(`k'*lt`d'-`tau`k''))/(`D'))^`matacc'[`i',1]
+ qui replace `proba`i'_0'=`proba`i'_0'-`proba`i'_`k''
+ qui gen `prob`i'_`k''=`proba`i'_`k''+`prob`i'_`=`k'+1''
+
+ /************AJOUT 13/7/22**********/
+ qui gen `best`i'_`k''=`proba`i'_`k''*normalden(lt`d',`matmu'[1,1],sqrt(`covmatrix'[1,1]))
+ qui su `best`i'_`k''
+ qui su lt`d' if round(`best`i'_`k'',0.001)==round(`r(max)',0.001)
+ local bestloc`i'_`k'=r(mean)
+ di "Best location for item `i' category `k' : `bestloc`i'_`k''"
+ *qui replace `est`i''=`bestloc_`k'' if ``i''==`k'
+ /************FIN AJOUT 13/7/22**********/
+
+ qui replace `icc`i''=`icc`i''+`k'*`proba`i'_`k''
+ qui compress
+ if "`genproba'"!="" {
+ qui gen proba`i'_`k'=`prob`i'_`k''-`prob`i'_`=`k'+1''
+ }
+ }
+ /************AJOUT 13/7/22**********/
+ qui gen `best`i'_0'=`proba`i'_0'*normalden(lt`d',`matmu'[1,1],sqrt(`covmatrix'[1,1]))
+ qui su `best`i'_0'
+ qui su lt`d' if round(`best`i'_0',0.001)==round(`r(max)',0.001)
+ local bestloc`i'_0=r(mean)
+ di "Best location for item `i' category 0 : `bestloc_0'"
+ *qui replace `est`i''=`bestloc_0' if `i'==0
+ *corr `est`i'' lt1
+ /************FIN AJOUT 13/7/22**********/
+ if "`genicc'"!="" {
+ qui gen icc`i'=`icc`i''
+ }
+ qui gen `prefix`d''`q'=0
+ di _col(1) in gr "`prefix`d''`q'" _col(20) in ye %8.4f `pcm'[`i',1] _col(32) %8.4f `matdisc'[`i',1] _col(44) %6.4f `matpmin'[`i',1] _col(56) %6.4f `matpmax'[`i',1] _col(68) %8.4f `matacc'[`i',1]
+ forvalues k=2/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ }
+ tempname uni
+ qui gen `uni'=uniform()
+ forvalues k=1/`nbmodas`i'' {
+ qui replace `prefix`d''`q'=`k' if `uni'<=`prob`i'_`k''
+ qui compress
+ }
+ forvalues k=0/`nbmodas`i'' {
+ qui replace `est`i''=`bestloc`i'_`k'' if `prefix`d''`q'==`k'
+ }
+ su lt1 `est`i''
+ corr lt1 `est`i''
+ }
+ else { /*if "`threshold'"!=""*/
+ qui gen `prefix`d''`q'=lt`d'>`pcm'[`i',1]
+ local tmp=0
+ forvalues k=1/`nbmodas`i'' {
+ di _col(1) in gr "`prefix`d''`q'_`k'" _col(20) in ye %8.4f `pcm'[`i',`k']
+ local tmp=`tmp'+`pcm'[`i',`k']
+ qui replace `prefix`d''`q'=`k' if lt`d'>`tmp'
+ qui compress
+ }
+ }
+ local q=`q'+1
+ }
+}
+`line'
+di
+
+
+/********************************************************************************
+CATEGORIES PROBABILITY CURVES and ITEMS CHARACTERISTIC CURVES
+********************************************************************************/
+
+set tracedepth 1
+if "`draw'"!=""|"`icc'"!=""|"`drawall'"!="" {
+ label variable lt1 "Latent trait"
+ local dess
+ /************AJOUT 13/7/22**********/
+ local dessbest
+ /************FIN AJOUT 13/7/22**********/
+ sort lt1
+
+ if "`draw'"!=""|"`drawall'"!="" {
+ local alldess
+ forvalues i=1/`dim1' {
+ if "`title'"=="" {
+ local title2="Category Probability Curves of the Item `i'"
+ }
+ else {
+ local title2="`title'"
+ }
+ local dess
+ /************AJOUT 13/7/22**********/
+ local dessbest
+ /************FIN AJOUT 13/7/22**********/
+ local tauj`j'k0=0
+ forvalues k=`nbmodas`i''(-1)0 {
+ local dess `dess' (line `proba`i'_`k'' lt1)
+ /************AJOUT 13/7/22**********/
+ local dessbest `dessbest' (line `best`i'_`k'' lt1)
+ /************FIN AJOUT 13/7/22**********/
+ label variable `proba`i'_`k'' "`k'"
+ }
+ graph twoway `dess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(item`i',replace)
+ local alldess `alldess' `dess'
+ /************AJOUT 13/7/22**********/
+ graph twoway `dessbest' , ylabel(0(.25)1) legend(on) ytitle("Likelihood of latent trait as a fonction of the responses") title("`title2'") name(item`i',replace)
+ /************FIN AJOUT 13/7/22**********/
+ }
+ if "`drawall'"!="" {
+ graph twoway `alldess' , ylabel(0(.25)1) legend(on) ytitle("Probability of response to each modality") title("`title2'") name(all,replace)
+ }
+ }
+ if "`icc'"!="" {
+ local hicc
+ forvalues i=1/`dim1' {
+ if "`titleicc'"=="" {
+ local title3="Item Characteristic Curve of the Item `i'"
+ }
+ else {
+ local title3="`title'"
+ }
+ graph twoway (line `icc`i'' lt1) if `graphobs', ylabel(0(1)`nbmodas') legend(off) ytitle("Expected response") title("`title3'") name(iccitem`i',replace)
+ local hicc `hicc' (line `icc`i'' lt1)
+ label variable `icc`i'' "Item `i'"
+ }
+ graph twoway `hicc' if `graphobs', ylabel(0(1)`nbmodas') legend(on) ytitle("Expected response") title("Item Characteristic Curves") name(icc,replace)
+ }
+}
+qui drop if `graphobs'
+
+
+/********************************************************************************
+DISPLAYING
+********************************************************************************/
+
+forvalues d=1/`dim' {
+ qui su lt`d'
+ local var_`d'=r(Var)
+ local mean_`d'=r(mean)
+ forvalues l=`=`d'+1'/`dim' {
+ qui corr lt`d' lt`l' ,cov
+ local cov_`d'_`l'=r(cov_12)
+ return scalar cov_`d'_`l'=`cov_`d'_`l''
+ }
+ return scalar mean_`d'=`mean_`d''
+ return scalar var_`d'=`var_`d''
+}
+forvalues d=1/`dim' {
+ forvalues l=`=`d'+1'/`dim' {
+ local corr_`d'_`l'=`cov_`d'_`l''/sqrt(`var_`d''*`var_`l'')
+ return scalar corr_`d'_`l'=`corr_`d'_`l''
+ }
+}
+
+
+if `dim'==1&`group'!=0 {
+ qui su lt1 if group==0
+ local mean_0=r(mean)
+ qui su lt1 if group==1
+ local mean_1=r(mean)
+ local delta=`mean_1'-`mean_0'
+}
+
+return scalar nbobs=`nbobs'
+tempname matcorr
+matrix `matcorr'=corr(`matcov')
+
+di in gr "{hline 50}"
+di _col(1) in gr "Latent trait" _c
+if `dim'==2 {
+ di in gr "s"_c
+}
+di in gr _col(30) "Expected" _col(42) "Observed"
+di in gr "{hline 50}"
+forvalues i=1/`dim' {
+ di _col(1) in gr "Mean(lt`i')" _col(30) in ye %8.4f `matmu'[`i',1] _col(42) %8.4f `mean_`i''
+ di _col(1) in gr "Variance(lt`i')" _col(30) in ye %8.4f `matcov'[`i',`i'] _col(42) %8.4f `var_`i''
+ forvalues d=`=`i'+1'/`dim' {
+ di _col(1) in gr "Covariance `i'_`d'" _col(30) in ye %8.4f `matcov'[`i',`d'] _col(42) %8.4f `cov_`i'_`d''
+ di _col(1) in gr "Correlation `i'_`d'" _col(31) in ye %7.4f `matcorr'[`i',`d'] _col(43) %7.4f `corr_`i'_`d''
+ }
+ di in gr "{hline 50}"
+}
+if `dim'==1&`group'!=0 {
+ di _col(1) in gr "Mean(lt1) group 0" _col(30) in ye %8.4f `matmu'[1,1]-`deltagroup'*`group' _col(42) %8.4f `mean_0'
+ di _col(1) in gr "Mean(lt1) group 1" _col(30) in ye %8.4f `matmu'[1,1]+`deltagroup'*(1-`group') _col(42) %8.4f `mean_1'
+ qui count if group==1
+ local prop=r(N)/`nbobs'
+ di _col(1) in gr "Proportion group 1" _col(30) in ye %8.4f `group' _col(42) %8.4f `prop'
+ di in gr "{hline 50}"
+}
+
+/********************************************************************************
+CLEAR AND/OR STORE
+********************************************************************************/
+qui compress
+
+if "`clear'"!="" {
+ restore, not
+ preserve
+}
+if "`store'"!="" {
+ keep id lt* item*
+ save "`store'",`replace'
+}
+if "`clear'"=="" {
+ capture use "`saveraschbin'",replace
+}
+end
diff --git a/Modules/ado/personal/s/simirt.hlp b/Modules/ado/personal/s/simirt.hlp
new file mode 100644
index 0000000..791e381
--- /dev/null
+++ b/Modules/ado/personal/s/simirt.hlp
@@ -0,0 +1,185 @@
+{smcl}
+{* 7May2013}{...}
+{hline}
+help for {hi:simirt}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Simulation of IRT models}
+
+{p 8 14 2}{cmd:simirt} [, {cmdab:nbo:bs}({it:#})
+{cmdab:d:im}({it:# [#] [#]...}) {cmdab:mu}({it:# [#] [#]...}) {cmdab:cov}({it:# [# #]}) {cmdab:covm:atrix}({it:matrix})
+{cmdab:dif:f}({it:list_of_values_or_expression}) {cmdab:pcm}({it:matrix}) {cmdab:dis:c}({it:list_of_values})
+{cmdab:pmin}({it:list_of_values}) {cmdab:pmax}({it:list_of_values})
+{cmdab:acc}({it:list_of_values})
+{cmdab:rsm1}({it:list_of_values})
+{cmdab:rsm2}({it:list_of_values})
+{cmdab:thr:eshold}
+{cmdab:clear} {cmdab:sto:re}({it:filename}) {cmdab:id}({it:newvarname})
+{cmdab:rep:lace} {cmdab:pref:ix}({it:string}) {cmdab:draw} {cmdab:tit:le}({it:string})
+{cmdab:gr:oup}({it:#}) {cmdab:norand:om} {cmdab:del:tagroup}({it:#})])
+
+{title:Description}
+
+{p 4 8 2}{cmd:simirt} allows creating a new dataset of responses
+to items simulated by an unidimensional IRT model. The model can be
+dichotomous (Rasch, OPLM, Birnbaum, 3PLM, 4PLM, 5PAM) or polytomous (Rating
+Scale Model-RSM). It is possible to simulate two sets of items linked, for
+each of them, to a specific latent trait (who can be correlated).
+
+{title:Options}
+
+{p 4 8 2}{cmd:nbobs}({it:#}) specifies the number of individuals to simulate.
+By default, 2000 individuals are simulated.
+
+{p 4 8 2}{cmd:dim}({it:# [#] [#]...}) specifies the number of items linked to the first
+latent trait (and optionally to the second one and so on). If this option is not defined,
+the {cmd:simirt} command simulates only one latent trait with a number of items
+equal to the number of values defined in the {cmd:diff} or in the {cmd:pcm} option (at least one of
+these three options must be defined).
+
+{p 4 8 2}{cmd:mu}({it:# [#]}) specifies the mean(s) of each simulated latent
+trait(s).
+
+{p 4 8 2}{cmd:cov}({it:# [# #]}) defines the covariance matrix of the latent
+trait(s). If there is only one latent, {cmd:cov} is composed of the variance of
+this one, else, {cmd:cov} is composed of the variance of the first latent,
+followed by the variance of the second latent trait, and of the covariance.
+
+{p 4 8 2}{cmd:covmatrix}({it:matrix}) directly defines the covariance matrix of the latent
+trait(s). This option is required instead of the {cmd:cov} option as soon as the number
+of dimensions is greater than 2 (but this option could be used for one or two dimensions).
+
+{p 4 8 2}{cmd:diff}({it:list_of_values_or_expression}) defines the values of the
+difficulty parameters as a list of values (with a number of elements equal to
+the total number of items), or as an expression like {it: uniform #A #B} (to
+define these parameters as uniformly distributed in {it:]#A;#B[)}, or like
+{it:gauss #M #V} (to define these parameters as the percentiles of the gaussian
+distribution with mean {it:#M} and variance {it:#V}). If there is two latent
+traits, the expressions are defined as {it:uniform #A1 #B1 #A2 #B2} and
+{it: gauss #M1 #V1 #M2 #V2}. If this option is not defined (but the {cmd:dim}
+option is), these parameters are defined among a standardized gaussian
+distribution.
+
+{p 4 8 2}{cmd:pcm}({it:matrix}) defines a matrix containing as many rows as items and
+a column for each positive answer categorie. Elements of this matrix represents the
+difficulty parameters of the items in a Partial Credit Model.
+
+{p 4 8 2}{cmd:disc}({it:list_of_values}) defines the discriminating values of
+the items (by default, these parameters are fixed to 1) [only for dichotomous items].
+
+{p 4 8 2}{cmd:pmin}({it:list_of_values}) defines the minimal probability of
+positive responses for each item (by default, these parameters are fixed to 0)
+[only for dichotomous items].
+
+{p 4 8 2}{cmd:pmax}({it:list_of_values}) defines the maximal probability of
+positive responses for each item (by default, these parameters are fixed to 1)
+[only for dichotomous items].
+
+{p 4 8 2}{cmd:acc}({it:list_of_values}) defines the accelerating parameters
+for each item (by default, these parameters are fixed to 1) [only for dichotomous items].
+
+{p 4 8 2}{cmd:rsm1}({it:list_of_values}) and {cmd:rsm2}({it:list_of_values}) defines
+the tau parameters corresponding to the difficulty parameters of the positive answer
+categorie for each item in a Rating Scale Model for the first scale ({cmd:rsm1}) or
+for the second scale ({cmd:rsm2}).
+
+{p 4 8 2}{cmd:threshold} simulates the responses of each individuals directly from the latent trait.
+In a dichotomous model ({cmd:disc}, {cmd:pmin}, {cmd:pmax} and {cmd:acc} options are not allowed), the response
+1 if given as soon the latent trait of the individual is greater than the difficulty parameter of the item (defined with the {cmd:diff} option).
+In a polytomous model , an answer is given when the latent trait of the individual is greater than the
+ difficulties corresponding to this answer.
+
+{p 4 8 2}{cmd:clear} does not restore the initial dataset at the end of the
+command (at least one of the {cmd:clear} and {cmd:store} options must be defined).
+
+{p 4 8 2}{cmd:id}({it:newvarname}) defines the name of the identifiant variable (id by default).
+
+{p 4 8 2}{cmd:store}({it:filename}) defines the file where the new dataset will
+be stored (at least one of the {cmd:clear} and {cmd:store} options must be
+defined).
+
+{p 4 8 2}{cmd:replace}, associated to {cmd:store}, allows replacing the file
+defined by {cmd:store}, if it already exist.
+
+{p 4 8 2}{cmd:prefix}({it:string [string]}]) allows defining the prefix to use
+for the names of the items. The {it:string} cannot contain space(s). By default,
+the used prefix is "item" in the unidimensional case, and "itemA" and "itemB"
+in the bidimensional case. A number follows these prefixes.
+
+{p 4 8 2}{cmd:draw}, in the unidimensional case, this option allows drawing the
+Items Characteristic Curves on a graph.
+
+{p 4 8 2}{cmd:title} defines the title of the graphs.
+
+{p 4 8 2}{cmd:group} defines, in the unidimensional case, two groups of patients, for
+example a "treated" group (coded 1) and a "reference" group (coded 0). {cmd:group}
+defines the expected rate of individuals of the first group. By default, the
+affectation in the two groups is randomly provided (see the {cmd:norandom} option).
+
+{p 4 8 2}{cmd:norandom} allows affecting between the two groups the exact rates of individuals
+defined in the {cmd:group} option.
+
+{p 4 8 2}{cmd:deltagroup} defines, in the unidimensional case, the difference between the
+means of the latent trait between the two groups defined by the {cmd:group} option. This
+option is disabled if the {cmd:group} option is not defined. The variance of the latent
+trait is considered as equal in the two groups.
+
+{title:Outputs}
+
+{p 4 8 2}{cmd:r(nbobs)}: Number of simulated individuals.
+
+{p 4 8 2}{cmd:r(mean_#)}: Empirical mean of the #th latent trait.
+
+{p 4 8 2}{cmd:r(var_#)}: Empirical variance of the #th latent trait.
+
+{p 4 8 2}{cmd:r(cov_12)}: Empirical covariance between the two latent traits
+(if there is two simulated dimensions).
+
+{p 4 8 2}{cmd:r(rho)}: Empirical correlation coefficient between the two latent
+traits (if there is two simulated dimensions).
+
+{title:Examples}
+
+{p 4 8 2}{cmd: . simirt , dim(7) clear} /*simulates data by a Rasch model*/
+
+{p 4 8 2}{cmd: . simirt , diff(gauss 0 1) dim(7) disc(.8 1.2 1.4 .6 1.4 1.0 1.1) clear}
+ /*simulates data by a Birnbaum model*/
+
+{p 4 8 2}{cmd: . simirt , diff(uniform -2 3 0 1) dim(7 7) cov(2 4 1) clear}/*
+simulates data with a bidimensional latent trait*/
+
+{p 4 8 2}{cmd: . simirt , dim(7) clear group(.5) deltagroup(1)} /*simulates
+data by a Rasch model, with two groups of approximate equal size of patients
+and a difference between the means of the latent trait for the two groups of 1*/
+
+{p 4 8 2}{cmd: . simirt , dim(7) clear rsm(1 .5 .2)} /*Data simulated by a RSM. Each item
+has until 5 modalities*/
+
+{title:Notes about the models}
+
+{p 4 8 2}{bf:Rasch model}: By default, you can describe only the {cmd:diff} option.
+
+{p 4 8 2}{bf:Birnbaum model and OPLM}: By default, the {cmd:diff} and the {cmd:disc} options must be defined.
+
+{p 4 8 2}{bf:3-PLM}: By default, the {cmd:diff}, the {cmd:disc} and the {cmd:pmin} options must be defined.
+
+{p 4 8 2}{bf:4-PLM}: By default, the {cmd:diff}, the {cmd:disc}, the {cmd:pmin} and the {cmd:pmax} options must be defined.
+
+{p 4 8 2}{bf:5-PM}: The {cmd:diff}, the {cmd:disc}, the {cmd:pmin}, the {cmd:pmax} and the {cmd:acc} options must be defined.
+
+{p 4 8 2}{bf:RSM}: The {cmd:rsm1} [and eventually the {cmd:rsm2}] option(s) must be defined. The {cmd:disc}, the {cmd:pmin}, the {cmd:pmax} and the {cmd:acc} options cannot be defined.
+
+{p 4 8 2}{bf:PCM}: The {cmd:pcm} option must be defined. The {cmd:disc}, the {cmd:pmin}, the {cmd:pmax} and the {cmd:acc} options cannot be defined.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}EA 4275 "Team of Biostatistics, Pharmacoepidemiology and Subjective Measures in Health Sciences"{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
+
+
diff --git a/Modules/ado/personal/s/simirt.zip b/Modules/ado/personal/s/simirt.zip
new file mode 100644
index 0000000..310e86b
Binary files /dev/null and b/Modules/ado/personal/s/simirt.zip differ
diff --git a/Modules/ado/personal/t/tcm.ado b/Modules/ado/personal/t/tcm.ado
new file mode 100644
index 0000000..8617cc8
--- /dev/null
+++ b/Modules/ado/personal/t/tcm.ado
@@ -0,0 +1,645 @@
+* Tcm : Estimation pour une entité géographique donnée de la région centre des taux de mortalitré par age
+* quinquennal, et du TCM, avec possibilité de comparer ce dernier à une valeur théorique
+*
+* Version 2.6 : 21 janvier 2005 (corrections pour le calcul test du TCM à une valeur de référence)
+* Version 2.5 : 13 janvier 2005 (corrections pour le calcul du nb de décès observés avec ICMPART)
+* Version 2.4 : 11 janvier 2005 (quelques améliorations par rapport à la version 2.3)
+* Version 2.3 : 6 janvier 2005 (options ICM et ICMPART, age maximal par defaut à 95)
+* Version 2.2 : 16 décembre 2004
+* Version 2.1 : 7 décembre 2004
+* Version 2 : 22 octobre 2004
+* Version 1.4 : 2 septembre 2004
+* Version 1.3: 16 aout 2004
+* Version 1.2: 22 juillet 2004
+* Version 1.1: 16 juillet 2004
+* Version 1: 16 juillet 2004
+*
+* Jean-benoit Hardouin, Observatoire Régional de la Santé du Centre - Orléans - France
+* jean-benoit.hardouin@orscentre.fr
+*
+* Copyright 2004-2005 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 tcm,rclass
+version 7.0
+syntax [, s10(numlist) agemax(int 95) sexe(int 0) sexestd(int 0) anneepop(int 1999) anneepopstd(int 1999) annees(numlist) anneesstd(numlist) codegeo(int 1) codegeostd(int 0) prema(int 65) details tcmcomp(real 0) icm icmpart(numlist)]
+
+
+/*********************************************************************************************
+TESTS PRELIMINAIRES
+*********************************************************************************************/
+
+if `sexe'<0|`sexe'>2 {
+ di in red "Vous devez indiquer un sexe parmi 0 (deux sexes confondus), 1 (hommes) ou 2 (femmes)"
+ exit
+}
+if `sexestd'<0|`sexestd'>2 {
+ di in red "Vous devez indiquer un sexe de reference parmi 0 (deux sexes confondus), 1 (hommes) ou 2 (femmes)"
+ exit
+}
+if `anneepop'<82|(`anneepop'>99&`anneepop'<1982)|`anneepop'>1999 {
+ di in red "Vous devez indiquer une annee de reference entre 1982 et 1999 [82 et 99] (compris)"
+ exit
+}
+if `codegeo'==0 {
+ di in red "Il n'est pas encore possible de travailler sur la France entiere, mais cela viendra bien assez tot"
+ exit
+}
+
+local st = "$S_TIME"
+
+
+/*********************************************************************************************
+SI UNE BASE EST OUVERTE, ON LA SAUVEGARDE
+*********************************************************************************************/
+
+capture su *
+if _rc==0 {
+ tempfile tmp
+ if "`details'"!="" {
+ di in green "** Sauvegarde en cours"
+ }
+ qui save `tmp',replace
+}
+preserve
+
+/*********************************************************************************************
+PAR DEFAUT
+*********************************************************************************************/
+
+
+if "`s10'"=="" {
+ local s10des Toutes les causes
+ local s10 101(1)105 201(1)231 301 302 401 501 502 601 602 701(1)707 801(1)806 901(1)903 1001 1101 1201 1301 1401 1501 1600(1)1603 1701(1)1709
+}
+else {local s10des `s10'}
+
+if "`annees'"=="" {
+ local annees 1998(1)2000
+}
+local anneesdes `annees'
+
+if "`anneesstd'"=="" {
+ local anneesstd `annees'
+}
+local anneesdesstd `anneesstd'
+
+/*********************************************************************************************
+VERIFICATION ICM
+Pour calculer un ICM, il faut que le sexe, la période et la population de référence
+*********************************************************************************************/
+
+if `sexestd'!=`sexe'&"`icm'"!="" {
+ di in yellow "Le sexe de la population de reference (option sexestd) a ete modifie pour etre identique a celui de la population de travail (option sexe) et a desormais pour valeur `sexe'"
+ local sexestd=`sexe'
+}
+if "`anneesstd'"!="`annees'"&"`icm'"!="" {
+ di in yellow "La periode utilisee pour la population de reference (option anneesstd) a ete modifiee pour etre identique a celle utilisee pour la population de travail (option annees) et a desormais pour valeur `annees'"
+ local anneesstd `annees'
+}
+if "`anneepopstd'"!="`anneepop'"&"`icm'"!="" {
+ di in yellow "La population de reference (option anneepopstd) a ete modifiee pour etre identique a la population de travail (option anneepop) et a desormais pour valeur `anneepop'"
+ local anneepopstd `anneepop'
+}
+if "`icm'"==""&"`annees'"=="`anneesstd'"&`sexe'==`sexestd' {
+ di in yellow "Les options indiquees semblent etre correctes pour calculer un ICM"
+ local icm icm
+}
+else if "`icm'"==""{
+ di in yellow "Les options indiquees ne semblent pas etre correctes pour calculer un ICM : Attention en utilisant celui-ci"
+}
+
+/*********************************************************************************************
+SI LA STANDARDISATION SE FAIT SUR LA FRANCE
+*********************************************************************************************/
+
+
+if `codegeostd'==0 {
+ use "C:\ado\personal\files\dcfrance8000long.dta", clear
+ qui gen flagstd=0
+ foreach i of numlist `anneesstd' {
+ qui replace flagstd=1 if annee==`i'
+ }
+ qui keep if flagstd==1
+
+ qui replace flagstd=0
+ foreach i of numlist `s10' {
+ qui replace flagstd=1 if s10==`i'
+ }
+ qui keep if flagstd==1
+
+ qui replace flagstd=0
+ if `sexestd'!=0 {
+ qui replace flagstd=1 if sexe==`sexestd'
+ qui keep if flagstd==1
+ }
+
+ qui gen n=1
+ foreach i of numlist 0 1 5(5)`=`agemax'-5' {
+ qui su n if age==`i' [weight=eff]
+ local Nstd`i'=r(sum)
+ }
+ qui su n if age>=`agemax' [weight=eff]
+ local Nstd`agemax'=r(sum)
+}
+
+
+
+/*********************************************************************************************
+ON OUVRE LA BASE DE MORTALITE
+*********************************************************************************************/
+
+if "`details'"!="" {
+ di in green "** Ouverture de la base"
+}
+use "C:\ado\personal\files\dccentre8000reduit.dta",replace
+
+if "`details'"!="" {
+ di in green "** Base ouverte"
+}
+
+/*********************************************************************************************
+ON SELECTIONNE LES INFORMATIONS
+*********************************************************************************************/
+
+
+if "`details'"!="" {
+ di in green "** Selection de l'information necessaire"
+}
+
+
+
+numlist "`annees'"
+local nbans:word count `r(numlist)'
+local mod=mod(`nbans',2)
+if `mod'==0 {
+ local juillet=""
+}
+else if `mod'==1 {
+ local juillet="juillet"
+}
+if `codegeo'<100&"`juillet'"=="" {
+ local commpoptr="Estimation INSEE au 1er janvier"
+}
+else if `codegeo'<100&"`juillet'"!="" {
+ local commpoptr="Estimation INSEE au 1er juillet"
+}
+else if `codegeo'>100 {
+ local commpoptr="Rétropolation entre les recencements pour"
+}
+
+numlist "`anneesstd'"
+local nbansstd:word count `r(numlist)'
+local mods=mod(`nbansstd',2)
+if `mods'==0 {
+ local juilletstd=""
+}
+else if `mods'==1 {
+ local juilletstd="juillet"
+}
+if `codegeostd'<100&"`juilletstd'"=="" {
+ local commpopstd="Estimation INSEE au 1er janvier"
+}
+else if `codegeostd'<100&"`juilletstd'"!="" {
+ local commpopstd="Estimation INSEE au 1er juillet"
+}
+else if `codegeostd'>100 {
+ local commpopstd="Rétropolation entre les recencements pour"
+}
+
+
+tempvar keeps10 keepsexe keepannees keepgeo
+gen `keeps10'=0
+gen `keepsexe'=0
+gen `keepannees'=0
+gen `keepgeo'=0
+
+if "`details'"!="" {
+ di in green "** Selection en fonction du sexe"
+}
+
+if `sexe'==0 {
+ qui replace `keepsexe'=1
+}
+else {
+ qui replace `keepsexe'=1 if sexe==`sexe'
+}
+
+qui keep if `keepsexe'==1
+
+
+if "`details'"!="" {
+ di in green "** Selection des annees"
+}
+
+foreach i of numlist `annees' {
+ qui replace `keepannees'=1 if annee==`i'
+}
+
+qui keep if `keepannees'==1
+
+if "`details'"!="" {
+ di in green "** Selection de la zone geographique"
+}
+
+if `codegeo'==1 {
+ qui replace `keepgeo'=1
+}
+
+if `codegeo'>10&`codegeo'<100 {
+ qui replace `keepgeo'=1 if deptdom==`codegeo'
+}
+
+if `codegeo'>1000&`codegeo'<10000&int(`codegeo'/100)!=24 {
+ qui replace `keepgeo'=1 if codepct==`codegeo'
+}
+
+if int(`codegeo'/100)==24 {
+ qui replace `keepgeo'=1 if ze94==`codegeo'
+}
+
+if `codegeo'>10000&`codegeo'<100000 {
+ qui replace `keepgeo'=1 if comdom==`codegeo'
+}
+
+qui keep if `keepgeo'==1
+
+
+if "`details'"!="" {
+ di in green "** Selection des codes S10"
+}
+
+foreach i of numlist `s10' {
+ qui replace `keeps10'=1 if S10==`i'
+}
+
+qui keep if `keeps10'==1
+
+
+if "`details'"!="" {
+ di in green "** Selection finale"
+}
+
+qui keep if `keeps10'==1&`keepsexe'==1&`keepannees'==1&`keepgeo'==1
+
+if "`details'"!="" {
+ di in green "** Selection terminee"
+}
+
+/*********************************************************************************************
+ON CHERCHE LES INTITULES DE ZONE, DE SEXE POUR LA POPULATION DE TRAVAIL
+*********************************************************************************************/
+
+qui count
+local N=r(N)
+qui count if age!=0
+local N0=r(N)
+if `codegeo'==1 {local zone region Centre}
+else if `codegeo'==18 {local zone Cher}
+else if `codegeo'==28 {local zone Eure-et-Loir}
+else if `codegeo'==36 {local zone Indre}
+else if `codegeo'==37 {local zone Indre-et-Loire}
+else if `codegeo'==41 {local zone Loir-et-Cher}
+else if `codegeo'==45 {local zone Loiret}
+else {
+ qui trouve `codegeo'
+ local zone `r(trouve`codegeo')'
+ if "`zone'"=="" {
+ local zone Non reconnue
+ }
+}
+
+if `sexe'==0 {local sexedes Deux sexes}
+else if `sexe'==1 {local sexedes Hommes}
+else if `sexe'==2 {local sexedes Femmes}
+else {local sexedes Non reconnu}
+
+/*********************************************************************************************
+ON CHERCHE LES INTITULES DE ZONE, DE SEXE POUR LA POPULATION DE STANDARDISATION
+*********************************************************************************************/
+
+
+if `sexestd'==0 {local sexerefdes Deux sexes}
+else if `sexestd'==1 {local sexerefdes Hommes}
+else if `sexestd'==2 {local sexerefdes Femmes}
+else {local sexerefdes Non reconnu}
+
+
+if `codegeostd'==0 {local zonestd France metropolitaine}
+else if `codegeostd'==1 {local zonestd region Centre}
+else if `codegeostd'==18 {local zonestd Cher}
+else if `codegeostd'==28 {local zonestd Eure-et-Loir}
+else if `codegeostd'==36 {local zonestd Indre}
+else if `codegeostd'==37 {local zonestd Indre-et-Loire}
+else if `codegeostd'==41 {local zonestd Loir-et-Cher}
+else if `codegeostd'==45 {local zonestd Loiret}
+else {
+ qui trouve `codegeostd'
+ local zonestd `r(trouve`codegeostd')'
+ if "`zonestd'"=="" {
+ local zonestd Non reconnue
+ }
+}
+
+/*********************************************************************************************
+ENTETE DE SORTIE
+*********************************************************************************************/
+
+di in green "- POPULATION DE TRAVAIL -"
+di in green "Zone geographique : " in yellow "`zone'"
+di in green "Periode : " in yellow "`anneesdes'" in green " (" in yellow "`nbans' an(s)" in green ")"
+di in green "Population : " in yellow "`commpoptr' `anneepop'"
+di in green "Sexe : " in yellow "`sexedes'"
+di
+di in green "- POPULATION DE REFERENCE -"
+di in green "Zone geographique : " in yellow "`zonestd' "
+di in green "Periode : " in yellow "`anneesdesstd'" in green " (" in yellow "`nbansstd' an(s)" in green ")"
+di in green "Population : " in yellow "`commpopstd' `anneepopstd'"
+di in green "Sexe: " in yellow "`sexerefdes'"
+di
+di in green "Deces prematures : <" in yellow "`prema'" in green " ans"
+di in green "S10 : " in yellow "`s10des'"
+di
+
+/*********************************************************************************************
+NB DE DECES ET DE DECES PREMATURES
+*********************************************************************************************/
+
+di in green "Nombre de deces concernes : " in yellow `N' _col(55) in green "Nombre de deces concernes >0 an : " in yellow `N0'
+qui count if age<`prema'
+local Nprema=r(N)
+local Pprema=`Nprema'/`N'
+qui count if age<`prema'&age>0
+local N0prema=r(N)
+local P0prema=`N0prema'/`N0'
+di in green "Nombre de deces prematures : " in yellow `Nprema' in green " (" in yellow %5.1f `=`Pprema'*100' in green "%)" _col(55) in green "Nombre de deces prematures >0 an : " in yellow `N0prema' in green " (" in yellow %5.1f `=`P0prema'*100' in green "%)"
+
+/*********************************************************************************************
+TAILLE DE POPULATION DE LA POPULATION DE TRAVAIL
+*********************************************************************************************/
+
+tempvar agerec
+gen `agerec'=age
+qui recode `agerec' 0=0 `agemax'/105=`agemax'
+
+local trancheage 0 1 5(5)`agemax'
+
+qui estpop , annee(`anneepop') codegeo(`codegeo') sexe(`sexe') `juillet'
+foreach i of numlist 0 1 5(5)`=`agemax'-5' {
+ local popr`i'=r(poprq`i')
+}
+local popr`agemax'=0
+foreach i of numlist `agemax'(5)95 {
+ local popr`agemax'=`popr`agemax''+r(poprq`i')
+}
+
+local popr=r(popr)/*-r(popr0)*/
+
+
+/*********************************************************************************************
+TAILLE DE POPULATION DE LA POPULATION DE STANDARDISATION
+*********************************************************************************************/
+
+
+qui estpop , annee(`anneepopstd') codegeo(`codegeostd') sexe(`sexestd') `juilletstd'
+foreach i of numlist 0 1 5(5)`=`agemax'-5' {
+ local pop`i'=r(poprq`i')
+}
+local pop`agemax'=0
+foreach i of numlist `agemax'(5)95 {
+ local pop`agemax'=`pop`agemax''+r(poprq`i')
+}
+local pop=r(popr)/*-r(popr0) */
+
+/*********************************************************************************************
+TABLEAU DE SORTIE
+*********************************************************************************************/
+
+di
+di in green "{hline 14}{c TT}{hline 33}{c TT}{hline 33}{c TT}{hline 20}"
+di in green _col(15) "{c |}" _col(21) "POPULATION DE TRAVAIL" _col(49) "{c |}" _col(55) "POPULATION DE REFERENCE" _col(83) "{c |}"
+di in green "{hline 14}{c +}{hline 33}{c +}{hline 33}{c +}{hline 20}"
+di in green "Tranche" _col(15) "{c |}" _col(16) "Population" _col(29) "Nombre" _col(37) "Taux brut de" _col(49) "{c |}" _col(50) "Population" _col(61) "Nombre de" _col(71) "Taux brut de" _col(83) "{c |}" _col(85) "Nb de deces"
+di in green "d'age" _col(15) "{c |}" _col(22) "`anneepop'" _col(27) "de deces" _col(39) "mortalite*" _col(49) "{c |}" _col(56) "`anneepopstd'" _col(65) "deces" _col(73) "mortalite*" _col(83) "{c |}" _col(88) "attendus" _col(100) "ICM"
+di in green "{hline 14}{c +}{hline 33}{c +}{hline 33}{c +}{hline 20}"
+
+/*********************************************************************************************
+CALCUL CHEZ LES 0 AN DU TAUX BRUT
+*********************************************************************************************/
+
+local tcm=0
+local vartcm=0
+local varicm=0
+local apvp=0
+
+/*qui count if `agerec'==0
+local Nage0=r(N)
+local txbrut0=`Nage0'/`popr0'*100000/`nbans'
+local txstd0=`Nstd0'/`pop0'*100000/`nbansstd'
+local NE0=`popr0'*`txstd0'/100000*`nbans'
+local apvp0=`Nage0'*`prema'
+di in green "O an" _col(15) "{c |}" _col(18) in yellow %8.0f `popr0' _col(27) %8.0f `Nage0' _col(40) %8.1f `txbrut0' _col(49) in green "{c |}" in yellow _col(52) %8.0f `pop0' _col(62) %8.0f `Nstd0' _col(74) %8.1f `txstd0' _col(83) in green "{c |}" _col(88) in yellow %8.1f `NE0' _col(97) %6.1f `=`Nage0'/`NE0'*100'
+di in green "{dup 14:-}{c +}{dup 33:-}{c +}{dup 33:-}{c +}{dup 20:-}"
+*/
+/*********************************************************************************************
+CALCUL POUR CHAQUE TRANCHE D'AGE DU TAUX BRUT ET DE LA CONTRIBUTION AU TCM
+*********************************************************************************************/
+*set trace on
+if "`icmpart'"!="" {
+ local icmpartmin:word 1 of `icmpart'
+ local icmpartmax:word 2 of `icmpart'
+ qui count if `agerec'>=`icmpartmin'&`agerec'<=`icmpartmax'
+ local Npart=r(N)
+}
+
+local N0std=0
+local NE=0
+local NEpart=0
+foreach i of numlist `trancheage' {
+ qui count if `agerec'==`i'
+ local Nage`i'=r(N)
+ if `i'==0 {
+ local tranche 0 an
+ }
+ else if `i'==1 {
+ local tranche 1-4 ans
+ local apvp1=`Nage`i''*62
+ local apvp=`apvp'+`apvp1'
+ }
+ else if `i'==`agemax' {
+ local tranche `agemax' ans et plus
+ }
+ else {
+ local tranche `i'-`=`i'+4' ans
+ if `i'<65 {
+ local apvp`i'=`Nage`i''*(62.5-`i')
+ local apvp=`apvp'+`apvp`i''
+ }
+ }
+ local N0std=`N0std'+`Nstd`i''
+ local txbrut`i'=`Nage`i''/`popr`i''*100000/`nbans'
+ local txstd`i'=`Nstd`i''/`pop`i''*100000/`nbansstd'
+ local NE`i'=`popr`i''*`txstd`i''/100000*`nbans'
+ local NE=`NE'+`NE`i''
+ if "`icmpart'"!="" {
+ if `icmpartmin'<=`i'&`icmpartmax'>=`i' {
+ local NEpart=`NEpart'+`NE`i''
+ }
+ }
+ local icm`i'=`Nage`i''/`NE`i''*100
+ *local varicm=`varicm'+`icm`i''
+ local tcm=`tcm'+`txbrut`i''*`pop`i''/`pop'
+ local vartcm=`vartcm'+(`pop`i''/`pop')^2*`txbrut`i''/100000/`popr`i''
+ di in green "`tranche'" _col(15) "{c |}" _col(18) in yellow %8.0f `popr`i'' _col(27) %8.0f `Nage`i'' _col(40) %8.1f `txbrut`i'' _col(49) in green "{c |}" in yellow _col(52) %8.0f `pop`i'' _col(62) %8.0f `Nstd`i'' _col(74) %8.1f `txstd`i'' _col(83) in green "{c |}" in yellow _col(88) %8.1f `NE`i'' _col(97) %6.1f `icm`i''
+}
+di in green "{hline 14}{c +}{hline 33}{c +}{hline 33}{c +}{hline 20}"
+
+/*********************************************************************************************
+TAUX BRUT GLOBAL
+*********************************************************************************************/
+
+local txbrut=`N'/`popr'*100000/`nbans'
+local txbrutstd=`=`N0std'/`pop'*100000/`nbansstd''
+local icm=`N'/`NE'*100
+*local A=`varicm'
+local varicm=`icm'^2/`N'
+di in green "Total" _col(15) "{c |}" in yellow _col(18) %8.0f `popr' _col(27) %8.0f `N' _col(40) %8.1f `txbrut' _col(49) in green "{c |}" in yellow _col(52) %8.0f `pop' _col(62) %8.0f `N0std' _col(74) %8.1f `=`N0std'/`pop'*100000/`nbansstd'' in green _col(83) "{c |}" in yellow _col(88) %8.1f `NE' _col(97) %6.1f `icm'
+di in green "{hline 14}{c BT}{hline 33}{c BT}{hline 33}{c BT}{hline 20}"
+
+di in green "APVP=" _col(18) in yellow %10.1f `apvp'
+
+/*********************************************************************************************
+TCM
+*********************************************************************************************/
+
+
+local tcmicmoins=(`tcm'/100000-1.96*sqrt(`vartcm'))*100000
+local tcmicplus=(`tcm'/100000+1.96*sqrt(`vartcm'))*100000
+local icmicmoins=`icm'*(1-1/(9*`N')-1.96/(3*sqrt(`N')))^3
+local icmicplus=(`N'+1)/`NE'*(1-1/(9*(`N'+1))+1.96/(3*sqrt(`N'+1)))^3*100
+
+di in green "TCM" _col(20) in yellow %8.2f `tcm' _col(35) in green "Ecart type" _col(45) in yellow %8.2f `=sqrt(`vartcm')*100000' _col(61) in green "[" in yellow %8.2f `tcmicmoins' in green ";" in yellow %8.2f `tcmicplus' in green "]"
+di in green "ICM" _col(20) in yellow %8.2f `icm' _col(35) in green "Ecart type" _col(45) in yellow %8.2f `=sqrt(`varicm')' _col(61) in green "[" in yellow %8.2f `icmicmoins' in green ";" in yellow %8.2f `icmicplus' in green "] (methode de Byar)"
+local Zicm=(abs(`N'-`NE')-.5)/sqrt(`NE')
+local pvalueicm=1-norm(abs(`Zicm'))
+di in green "H0: ICM=100" _col(35) "Z=" in yellow %6.4f `Zicm' _col(45) in green "p=" in yellow %6.4f `pvalueicm'
+
+/*********************************************************************************************
+ICM PARTIEL
+*********************************************************************************************/
+
+if "`icmpart'"!="" {
+ di in green "{dup 103:-}"
+ if `icmpartmax'==`agemax' {
+ local icmpartmaxdis "`icmpartmax' et plus"
+ }
+ else {
+ local icmpartmaxdis=`icmpartmax'+4
+ }
+ di in green "ICM Partiel pour les `icmpartmin'/`icmpartmaxdis'"
+ di in green "Deces observes : " _col(20) in yellow %8.0f `Npart'
+ di in green "Deces attendus : " _col(20) in yellow %8.2f `NEpart'
+ local icmpart=`Npart'/`NEpart'*100
+ local varicmpart=`icmpart'^2/`Npart'
+ local icmparticmoins=`icmpart'*(1-1/(9*`Npart')-1.96/(3*sqrt(`Npart')))^3
+ local icmparticplus=(`Npart'+1)/`NEpart'*(1-1/(9*(`Npart'+1))+1.96/(3*sqrt(`Npart'+1)))^3*100
+ local Zicmpart=(abs(`Npart'-`NEpart')-.5)/sqrt(`NEpart')
+ local pvalueicmpart=1-norm(abs(`Zicmpart'))
+ di in green "ICM (`icmpartmin'/`icmpartmaxdis')" _col(20) in yellow %8.2f `icmpart' _col(35) in green "Ecart type" _col(45) in yellow %8.2f `=sqrt(`varicmpart')' _col(61) in green "[" in yellow %8.2f `icmparticmoins' in green ";" in yellow %8.2f `icmparticplus' in green "] (methode de Byar)"
+ di in green "H0: ICM(`icmpartmin'/`icmpartmaxdis')=100" _col(35) "Z=" in yellow %6.4f `Zicmpart' _col(45) in green "p=" in yellow %6.4f `pvalueicmpart'
+ return scalar ICMpart=`icmpart'
+ return scalar ZICMpart=`Zicmpart'
+ return scalar pvalueICMpart=`pvalueicmpart'
+}
+
+
+di in green "{hline 103}"
+di in green "*: par an pour 100 000 habitants"
+*set trace on
+
+
+/*********************************************************************************************
+COMPARAISON DU TCM (TEST)
+*********************************************************************************************/
+
+if `tcmcomp'!=0 {
+ local Z=(`tcm'-`tcmcomp')/100000/(sqrt(`vartcm'))
+ local pvalue=1-norm(abs(`Z'))
+ di
+ di in green "Comparaison du TCM a la valeur theorique (`tcmcomp') : Z= " in yellow %8.4f `Z' in green " p= " in yellow %6.4f `pvalue'
+ return scalar ZTCM=`Z'
+ return scalar pvalueTCM=`pvalue'
+}
+
+/*********************************************************************************************
+SORTIES
+*********************************************************************************************/
+
+return scalar N0=`N0'
+return scalar APVP=`apvp'
+return scalar Popref=`popr'
+return scalar TCM=`tcm'
+return scalar TCMICplus=`tcmicplus'
+return scalar TCMICmoins=`tcmicmoins'
+return scalar ICM=`icm'
+return scalar ICMICmoins=`icmicmoins'
+return scalar ICMICplus=`icmicplus'
+return scalar N0prema=`N0prema'
+return scalar ZICM=`Zicm'
+return scalar pvalueICM=`pvalueicm'
+return scalar txbrut=`txbrut'
+return scalar txbrutstd=`txbrutstd'
+tempname matsave
+numlist "0 1 5(5)`agemax'"
+local j `r(numlist)'
+local l:word count `j'
+matrix define `matsave'=J(`l',9,0)
+forvalues i=1/`l' {
+ local k:word `i' of `j'
+ matrix `matsave'[`i',1]=`k'
+ matrix `matsave'[`i',2]=`Nage`k''
+ matrix `matsave'[`i',3]=`popr`k''
+ matrix `matsave'[`i',4]=`txbrut`k''
+ matrix `matsave'[`i',5]=`pop`k''
+ matrix `matsave'[`i',6]=`Nstd`k''
+ matrix `matsave'[`i',7]=`txstd`k''
+ matrix `matsave'[`i',8]=`NE`k''
+ matrix `matsave'[`i',9]=`icm`k''
+}
+matrix colnames `matsave'="classe d'age" "nb deces" "pop" "taux brut" "pop reference" "nb deces reference" "taux brut reference" "deces attendus" "icm"
+return matrix donnees `matsave'
+
+/*********************************************************************************************
+RECUPERATION SI BESOIN DE LA BASE INITIALE
+*********************************************************************************************/
+
+restore,not
+qui drop _all
+if "`tmp'"!="" {
+ if "`details'"!="" {
+ di
+ di in green "** Restauration"
+ }
+ qui use `tmp'
+}
+if "`details'"!="" {
+ capture qui elapse `st'
+ di in green "** Temps d'execution : " in yellow "$S_elap " in green "secondes"
+}
+
+end
+
diff --git a/Modules/ado/personal/t/testclv.ado b/Modules/ado/personal/t/testclv.ado
new file mode 100644
index 0000000..61cb729
--- /dev/null
+++ b/Modules/ado/personal/t/testclv.ado
@@ -0,0 +1,142 @@
+program define testclv
+syntax [,corr(real 0) nosim]
+
+clear
+qui set matsize 800
+qui set memory 128m
+set more off
+
+if `corr'==0 {
+ local rho 0.0
+}
+else if `corr'==1 {
+ local rho 1.0
+}
+else {
+ local rho 0`corr'
+}
+
+if "`sim'"=="" {
+ capture use "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\result.dta", clear
+ if _rc==0 {
+ mkmat *,matrix(result)
+ use "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\resultpoly.dta", clear
+ mkmat *,matrix(resultpoly)
+ use "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\result2.dta", clear
+ mkmat *,matrix(result2)
+ use "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\resultpoly2.dta", clear
+ mkmat *,matrix(resultpoly2)
+
+ count if resultpoly21!=0
+ local deb=r(N)+1
+ }
+ else {
+ matrix result=J(100,14,0)
+ matrix resultpoly=J(100,14,0)
+ matrix result2=J(100,14,0)
+ matrix resultpoly2=J(100,14,0)
+ local deb=1
+ }
+ forvalues i=`deb'/100 {
+ di "`i'" _c
+ qui simirt,dim(7 7) cov(1 1 `rho') clear nbobs(500) store(C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\data`i') replace
+ di "." _c
+ qui clv i*,nodendro nobiplot
+ di "." _c
+ local group:word 1 of `r(bestthresold)'
+ local group2:word 2 of `r(bestthresold)'
+ qui clv,nodendro nobiplot cons(`group')
+ di "." _c
+ matrix tmp=r(affect)
+ matrix result[`i',1]=tmp
+ di "." _c
+ qui clv,nodendro nobiplot cons(`group2')
+ di "." _c
+ matrix tmp=r(affect)
+ matrix result2[`i',1]=tmp
+
+ di "." _c
+ qui clv i*,nodendro nobiplot method(polychoric)
+ di "." _c
+ local group:word 1 of `r(bestthresold)'
+ local group2:word 2 of `r(bestthresold)'
+ qui clv,nodendro nobiplot cons(`group')
+ di "."
+ matrix tmp=r(affect)
+ matrix resultpoly[`i',1]=tmp
+ di "." _c
+ qui clv,nodendro nobiplot cons(`group2')
+ di "."
+ matrix tmp=r(affect)
+ matrix resultpoly2[`i',1]=tmp
+
+ drop _all
+ svmat result
+ save "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\result",replace
+
+ drop _all
+ svmat resultpoly
+ save "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\resultpoly",replace
+
+ drop _all
+ svmat result2
+ save "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\result2",replace
+
+ drop _all
+ svmat resultpoly2
+ save "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\resultpoly2",replace
+
+ }
+}
+foreach file in "result" "result2" "resultpoly" "resultpoly2" "result2nd" "result2nd2" {
+ drop _all
+ di "`file'"
+ use "C:\Documents and Settings\Jean-Benoit\Mes documents\THESE\clv\simul (rho=`rho')\\`file'",clear
+ quietly {
+ forvalues i=1/7 {
+ rename `file'`i' itemA`i'
+ rename `file'`=`i'+7' itemB`i'
+ }
+ gen conc=0
+ gen dis=0
+ forvalues i=1/7 {
+ forvalues j=`=`i'+1'/7 {
+ replace conc=conc+1 if itemA`i'==itemA`j'
+ replace conc=conc+1 if itemB`i'==itemB`j'
+ }
+ }
+ forvalues i=1/7 {
+ forvalues j=1/7 {
+ replace dis=dis+1 if itemA`i'==itemB`j'
+ }
+ }
+ gen result=.
+ replace result=1 if conc==42&dis==0&result==.
+ replace result=3 if conc<42&dis==0&result==.
+ replace result=4 if dis>0&conc>0&result==.
+ replace result=5 if dis==49&result==.
+ egen nbcl=rowmax(item*)
+ }
+ if "`file'"=="result" {
+ local text="CLV Classique"
+ }
+ if "`file'"=="result2" {
+ local text="CLV Classique 2e choix"
+ }
+ if "`file'"=="resultpoly" {
+ local text="CLV Polychoric"
+ }
+ if "`file'"=="resultpoly2" {
+ local text="CLV Polychoric 2e choix"
+ }
+ if "`file'"=="result2nd" {
+ local text="CLV 2nd ordre "
+ }
+ if "`file'"=="result2nd2" {
+ local text="CLV 2nd ordre 2e choix"
+ }
+ di in gr "`text'"
+ tab result
+}
+
+end
diff --git a/Modules/ado/personal/t/todate.ado b/Modules/ado/personal/t/todate.ado
new file mode 100644
index 0000000..ca575d2
--- /dev/null
+++ b/Modules/ado/personal/t/todate.ado
@@ -0,0 +1,168 @@
+*! 1.3.0 NJC 6 Sept 2005
+* 1.2.1 NJC 29 July 2003
+* 1.2.0 NJC 4 July 2001
+* 1.1.0 NJC 7 June 2001
+program todate
+ version 8
+ syntax varlist [if] [in], Pattern(string) Generate(string) ///
+ [ Format(string) Cend(numlist int >200 <=10000 max=1) ]
+
+ // existing and new varlists
+ tokenize `varlist'
+ local nvars : word count `varlist'
+
+ // do before second -syntax-
+ marksample touse, novarlist
+
+ local 0 "`generate'"
+ syntax newvarlist
+
+ if `nvars' != `: word count `varlist'' {
+ di as err "number of new variables not equal to" _c
+ di as err " number of existing variables"
+ exit 198
+ }
+
+ // partial test of format
+ if "`format'" != "" {
+ capture display `format' 1
+ if _rc {
+ di as err "invalid format()"
+ exit 120
+ }
+ }
+
+ // parse pattern into m d y h q w elements
+ // indulge upper case
+ local pattern = lower("`pattern'")
+ local plength = length("`pattern'")
+
+ forval i = 1 / `plength' {
+ local p = substr("`pattern'",`i',1)
+
+ if "`p'" == "m" local mlist "`mlist' `i'"
+ else if "`p'" == "d" local dlist "`dlist' `i'"
+ else if "`p'" == "y" local ylist "`ylist' `i'"
+ else if "`p'" == "h" local hlist "`hlist' `i'"
+ else if "`p'" == "q" local qlist "`qlist' `i'"
+ else if "`p'" == "w" local wlist "`wlist' `i'"
+ else {
+ di as err "invalid pattern"
+ exit 198
+ }
+ }
+
+ // allow mdy yh yq ym yw permutations
+ foreach i in m d y h q w {
+ if "``i'list'" != "" {
+ local ptype "`ptype'`i'"
+ local pels "`pels' `i'"
+ }
+ }
+
+ if !inlist("`ptype'", "yh", "yq", "my", "yw", "mdy") {
+ di as err "invalid pattern type: `ptype'"
+ exit 198
+ }
+ if "`ptype'" == "my" local ptype "ym"
+
+ // contiguous digits will have range == # elements - 1
+ foreach i in `pels' {
+ local `i'1 : word 1 of ``i'list'
+ local `i'len : word count ``i'list'
+ local last : word ``i'len' of ``i'list'
+ local range = `last' - ``i'1'
+ local range2 = ``i'len' - 1
+ if `range' != `range2' {
+ di as err "`i' digits not contiguous in pattern"
+ exit 198
+ }
+ }
+
+ // year digits and cend() compatible?
+ if `ylen' != 4 & "`cend'" == "" {
+ di as err "`ylen' digit years: need cend() option?"
+ exit 198
+ }
+ else if `ylen' == 4 & "`cend'" != "" {
+ di as txt "4 digit years: cend() option ignored"
+ local cend
+ }
+
+ // for each variable in original varlist
+ qui forval i = 1 / `nvars' {
+ tempvar strdate datelen touse2
+
+ // markout separately for each variable
+ gen byte `touse2' = `touse'
+ markout `touse2' ``i'', strok
+
+ // working string variable copy of date variable
+ capture confirm string variable ``i''
+ if _rc gen `strdate' = string(``i'',"%12.0g") if `touse2'
+ else gen `strdate' = trim(``i'') if `touse2'
+ local v "``i''"
+ local `i' "`strdate'"
+
+ // how long is date variable?
+ gen `datelen' = length(``i'')
+ su `datelen' if `touse2', meanonly
+ local range = r(max) - r(min)
+ local min = r(min)
+ local max = r(max)
+
+ if `max' != `plength' {
+ noi di as res "`v': " ///
+ as txt "length does not match pattern"
+ continue
+ }
+
+ // range == 0 is no problem
+ if `range' == 1 { /* leading zero needs to be supplied? */
+ replace `strdate' = "0" + `strdate' ///
+ if `datelen' == `min' & `touse2'
+ }
+ else if `range' >= 2 { /* range of lengths >= 2 => skip this */
+ noi di as res "`v': " ///
+ as txt "length too variable to handle"
+ continue
+ }
+
+ // construct month, day, year, half, quarter, week as needed
+ foreach j in `pels' {
+ tempvar `j'
+ gen ``j'' = real(substr(``i'',``j'1',``j'len'))
+ }
+
+ if "`cend'" != "" {
+ local c1 = int(`cend' / 100)
+ local c2 = mod(`cend',100)
+ replace `y' = ///
+ `y' + 100 * cond(`y' <= `c2', `c1', `c1' - 1)
+ }
+
+ // generate new variable
+ local newvar : word `i' of `varlist'
+ if "`ptype'" == "mdy" {
+ gen `newvar' = mdy(`m',`d',`y') if `touse2'
+ }
+ else {
+ local o = substr("`ptype'",2,1)
+ gen `newvar' = y`o'(`y',``o'') if `touse2'
+ }
+
+ if "`format'" != "" format `format' `newvar'
+ else {
+ if index("`ptype'", "d") format %d `newvar'
+ else if index("`ptype'", "w") format %tw `newvar'
+ else if index("`ptype'", "m") format %tm `newvar'
+ else if index("`ptype'", "q") format %tq `newvar'
+ else if index("`ptype'", "h") format %th `newvar'
+ }
+
+ _crcslbl `newvar' ``i''
+
+ drop `touse2'
+ }
+end
+
diff --git a/Modules/ado/personal/t/torumm.ado b/Modules/ado/personal/t/torumm.ado
new file mode 100644
index 0000000..a77c7bc
--- /dev/null
+++ b/Modules/ado/personal/t/torumm.ado
@@ -0,0 +1,10 @@
+program define torumm
+syntax varlist ,File(string) [Replace msp]
+tempname string
+egen `string'=concat(`varlist')
+if "`msp'"=="" {
+ replace `string'=subinstr(`string',"."," ",.)
+}
+*tab `string'
+outsheet `string' using "`file'", `replace' nonames noquote
+end
diff --git a/Modules/ado/personal/t/tosas.ado b/Modules/ado/personal/t/tosas.ado
new file mode 100644
index 0000000..f631d47
--- /dev/null
+++ b/Modules/ado/personal/t/tosas.ado
@@ -0,0 +1,29 @@
+program define tosas,eclass
+version 10.0
+syntax [varlist] [if] [in] [,Name(string) pgm(string) Batch]
+preserve
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+local dir=c(tmpdir)
+tempfile tosasfile totsasfile
+qui outsheet `varlist' using "`tosasfile'.txt",replace
+qui outsheet `varlist' using "d:\essai.txt",replace
+if "`name'"=="" {
+ local name stata
+}
+drop _all
+qui set obs 1000
+qui gen txt=""
+qui replace txt="PROC IMPORT OUT=WORK.`name' DATAFILE='`tosasfile'.txt' DBMS=TAB REPLACE;GETNAMES=YES;DATAROW=2; RUN;" in 3
+qui replace txt="`pgm'" in 4
+qui outsheet txt using "`tosasfile'_pgmsas.txt", replace nonames noquote
+if "`batch'"!="" {
+ shell "C:\Program Files\SAS\SASFoundation\9.3\sas.exe" "`tosasfile'_pgmsas.txt" -print "`tosasfile'.lst" -nolog
+ view "`tosasfile'.lst"
+}
+else {
+ shell "C:\Program Files\SASHome\SASFoundation\9.3\core\sasexe\SASOACT.EXE" action=Submit datatype=SASFile filename="`tosasfile'_pgmsas.txt" progid=SAS.Application.903
+}
+restore
+end
diff --git a/Modules/ado/personal/t/traces v4.ado b/Modules/ado/personal/t/traces v4.ado
new file mode 100644
index 0000000..08eef7d
--- /dev/null
+++ b/Modules/ado/personal/t/traces v4.ado
@@ -0,0 +1,346 @@
+*! Version 4 22January2015
+************************************************************************************************************
+* Traces: Traces of items
+* Version 4: January 22, 2015 /*ICC*/
+*
+* Historic:
+* Version 1 (2003-06-29): Jean-Benoit Hardouin
+* Version 2 (2003-07-04): Jean-Benoit Hardouin
+* version 3 (2003-07-09): Jean-Benoit Hardouin
+* Version 3.1 (2005-06-07): Jean-Benoit Hardouin /*small modifications*/
+* Version 3.2: May 27, 2007 /*onlyone option*/
+* Version 3.3: October 16, 2012 /*minor modifications*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2003, 2005, 2007, 2012, 2015 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 traces, rclass
+version 8.0
+syntax varlist(numeric min=2) [, COMPare(varlist min=2 max=2) ICC SAVeicc noGraph Score Test Restscore Logistic CI CUMulative REPFiles(string) SCOREFiles(string) RESTSCOREFiles(string) LOGISTICFile(string) noDraw noDRAWComb REPlace ONLYone(string) THResholds(string) Black]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if "`onlyone'"!=""&"`drawcomb'"!="" {
+ local drawcomb
+}
+
+tempvar varscore
+qui gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+ local score="score"
+}
+
+local modamax=0
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+}
+
+
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+
+forvalues i=0/`maxscore' {
+ qui count if `varscore'==`i'
+ local nscore`i'=r(N)
+}
+
+
+global score
+global restscore
+global logistic
+qui count
+local N=r(N)
+if `c(matsize)'<`N'&"`saveicc'"!="" {
+ set matsize `N'
+}
+
+
+if "`score'"!="" {
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+ tempname varscore2
+ qui gen `varscore2'=`varscore'
+ qui recode `varscore' `recode'
+ qui label values `varscore' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+ local listicc
+
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar icc``i''
+ gen `icc``i'''=0
+ local listicc `listicc' `icc``i'''
+ forvalues k=1/`modamax`i'' {
+ tempvar propscore`i'`k' tmp
+ if "`cumulative'"!="" {
+ qui gen `tmp'=``i''>=`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `tmp'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''=`k'"
+ *di "replace icc``i''=icc``i''+`k'*`propscore`i'`k''"
+ qui replace `icc``i'''=`icc``i'''+`k'*`propscore`i'`k''
+ }
+ local y`i'="`y`i'' `propscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ forvalues l=1/`maxscore' {
+ qui count if `varscore'==`l'
+ local nscore`l'=r(N)
+ }
+ qui gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ qui gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`nograph'"=="" {
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title("Trace of the item ``i'' as a function of the score") ytitle("Rate of positive response") `draw' /*areastyle(none)*/
+ }
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`icc'"!=""&"`nograph'"!=""{
+ qui graph twoway (line `icc``i''' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax`i'') xlabel(`minimum'(1)`nbgroups',valuelabel) name(icc`i',replace) title("Approximate ICC of the item ``i'' as a function of the score") ytitle("Mean response") `draw' /*areastyle(none)*/
+ }
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `repfiles'\\`scorefiles'``i'' ,`replace'
+ }
+ }
+ if "`saveicc'"!="" {
+ local listicc `listicc' `varscore'
+ tempname matscore
+ mkmat `listicc',matrix(`matscore')
+ }
+ if "`thresholds'"!="" {
+ qui replace `varscore'=`varscore2'
+ }
+}
+ if "`compare'"!=""&"`nograph'"!="" {
+ local tmp1 : word 1 of `compare'
+ local tmp2 : word 2 of `compare'
+ di "compare `compare' tmp1 `tmp1' tmp2 `tmp2'"
+ label variable `icc`tmp1'' `tmp1'
+ label variable `icc`tmp2'' `tmp2'
+ di "qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title(Comparison of the ICC of the items `tmp1' and `tmp2') `draw' /*areastyle(none)*/"
+ qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(blue red) clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) /*name(score`i',replace)*/ title("Comparison of the ICC of the items `tmp1' and `tmp2'") ytitle("Mean response") /*areastyle(none)*/
+ }
+if "`restscore'"!="" {
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar restscore`i'
+ qui gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+
+ *di "recode `restscore`i'' `recode'"
+ qui recode `restscore`i'' `recode'
+ qui label values `restscore`i'' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ qui gen `rtmp'=``i''>=`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `rtmp'=``i''==`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ qui gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ qui gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ local restscoremax=`scoremax'-`modamax`i''
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`nograph'"!="" {
+ *tab `proprestscore`i'1' `restscore`i''
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(restscore`i',replace) title("Trace of the item ``i'' as a function of the restscore") ytitle("Rate of positive response") `draw'
+ }
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `repfiles'\\`restscorefiles'``i'' ,`replace'
+ }
+ }
+}
+if "logistic"!="" {
+ forvalues i=1/`nbitems' {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ qui gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+if "`drawcomb'"!="" {
+ local drawcomb="nodraw"
+}
+
+if ("`score'"!=""&"`onlyone'"=="")&"`nograph'"!="" {
+ graph combine $score , title("Trace of the items as a function of the score") name(score,replace) `drawcomb'
+ if "`scorefiles'"!="" {
+ graph save score `repfiles'\\`scorefiles' ,`replace'
+ }
+}
+
+if ("`restscore'"!=""&"`onlyone'"=="")&"`nograph'"!="" {
+ graph combine $restscore , title("Trace of the items as a function of the restscores") name(restscore,replace) `drawcomb'
+ if "`restscorefiles'"!="" {
+ graph save restscore `repfiles'\\`restscorefiles' ,`replace'
+ }
+}
+if ("`logistic'"!="")&"`nograph'"!="" {
+ graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `drawcomb'
+ if "`logisticfile'"!="" {
+ graph save logistic `repfiles'\\`logisticfile' ,`replace'
+ }
+}
+if "`saveicc'"!="" {
+ return matrix matscore=`matscore'
+}
+end
+
+
diff --git a/Modules/ado/personal/t/traces v5 avec items numeric ne marche pas - Copie.ado b/Modules/ado/personal/t/traces v5 avec items numeric ne marche pas - Copie.ado
new file mode 100644
index 0000000..1ba1be2
--- /dev/null
+++ b/Modules/ado/personal/t/traces v5 avec items numeric ne marche pas - Copie.ado
@@ -0,0 +1,357 @@
+*! Version 5 5March2016
+************************************************************************************************************
+* Traces: Traces of items
+* Version 5: March 5, 2016 /*numerical items*/
+*
+* Historic:
+* Version 1 (2003-06-29): Jean-Benoit Hardouin
+* Version 2 (2003-07-04): Jean-Benoit Hardouin
+* version 3 (2003-07-09): Jean-Benoit Hardouin
+* Version 3.1 (2005-06-07): Jean-Benoit Hardouin /*small modifications*/
+* Version 3.2: May 27, 2007 /*onlyone option*/
+* Version 3.3: October 16, 2012 /*minor modifications*/
+* Version 4: January 22, 2015 /*ICC*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* EA4275-SPHERE "MethodS in Patients-centered outcomes and HEalth ResEarches"
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2003, 2005, 2007, 2012, 2015, 2016 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 traces, rclass
+version 8.0
+syntax varlist(numeric min=2) [, COMPare(varlist min=2 max=2) ICC SAVeicc noGraph Score Test Restscore Logistic CI CUMulative REPFiles(string) SCOREFiles(string) RESTSCOREFiles(string) LOGISTICFile(string) noDraw noDRAWComb REPlace ONLYone(string) THResholds(string) Black]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if "`onlyone'"!=""&"`drawcomb'"!="" {
+ local drawcomb
+}
+
+tempvar varscore
+qui gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+ local score="score"
+}
+
+local modamax=-999
+local modamin=999
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ local modamin`i'=r(min)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+ if `modamin`i''<`modamin' {
+ local modamin=`modamin`i''
+ }
+}
+
+/*
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+*/
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+local minscore=r(min)
+
+forvalues i=`minscore'/`maxscore' {
+ qui count if `varscore'>`=`i'-0.5'&`varscore'<=`=`i'+0.5'
+ local nscore`i'=r(N)
+}
+
+
+global score
+global restscore
+global logistic
+qui count
+local N=r(N)
+if `c(matsize)'<`N'&"`saveicc'"!="" {
+ set matsize `N'
+}
+
+
+if "`score'"!="" {
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode min/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "min/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+ tempname varscore2
+ qui gen `varscore2'=`varscore'
+ qui recode `varscore' `recode'
+ qui label values `varscore' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+ local listicc
+
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar icc``i''
+ gen `icc``i'''=0
+ local listicc `listicc' `icc``i'''
+ local l=0
+ forvalues k=`=`modamin`i''+1'/`modamax`i'' {
+ tempvar propscore`i'`l' tmp
+ if "`cumulative'"!="" {
+ qui gen `tmp'=``i''>=`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`l''=mean(`tmp')
+ label variable `propscore`i'`l'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `tmp'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`l''=mean(`tmp')
+ label variable `propscore`i'`l'' "Item ``i''=`k'"
+ *di "replace icc``i''=icc``i''+`k'*`propscore`i'`k''"
+ qui replace `icc``i'''=`icc``i'''+`k'*`propscore`i'`l''
+ }
+ local y`i'="`y`i'' `propscore`i'`l''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ forvalues m=1/`maxscore' {
+ qui count if `varscore'==`m'
+ local nscore`m'=r(N)
+ }
+ qui gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ qui gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ local ++l
+ }
+
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`graph'"=="" {
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title("Trace of the item ``i'' as a function of the score") ytitle("Rate of positive response") `draw' /*areastyle(none)*/
+ }
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`icc'"!=""&"`graph'"==""{
+ qui graph twoway (line `icc``i''' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax`i'') xlabel(`minimum'(1)`nbgroups',valuelabel) name(icc`i',replace) title("Approximate ICC of the item ``i'' as a function of the score") ytitle("Mean response") `draw' /*areastyle(none)*/
+ }
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `repfiles'\\`scorefiles'``i'' ,`replace'
+ }
+ }
+ if "`saveicc'"!="" {
+ local listicc `listicc' `varscore'
+ tempname matscore
+ mkmat `listicc',matrix(`matscore')
+ }
+ if "`thresholds'"!="" {
+ qui replace `varscore'=`varscore2'
+ }
+}
+ if "`compare'"!=""&"`nograph'"!="" {
+ local tmp1 : word 1 of `compare'
+ local tmp2 : word 2 of `compare'
+ di "compare `compare' tmp1 `tmp1' tmp2 `tmp2'"
+ label variable `icc`tmp1'' `tmp1'
+ label variable `icc`tmp2'' `tmp2'
+ di "qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title(Comparison of the ICC of the items `tmp1' and `tmp2') `draw' /*areastyle(none)*/"
+ qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(blue red) clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) /*name(score`i',replace)*/ title("Comparison of the ICC of the items `tmp1' and `tmp2'") ytitle("Mean response") /*areastyle(none)*/
+ }
+if "`restscore'"!="" {
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar restscore`i'
+ qui gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "min/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+
+ *di "recode `restscore`i'' `recode'"
+ qui recode `restscore`i'' `recode'
+ qui label values `restscore`i'' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ qui gen `rtmp'=``i''>=`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `rtmp'=``i''==`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ qui gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ qui gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ local restscoremax=`scoremax'-`modamax`i''
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`nograph'"!="" {
+ *tab `proprestscore`i'1' `restscore`i''
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(restscore`i',replace) title("Trace of the item ``i'' as a function of the restscore") ytitle("Rate of positive response") `draw'
+ }
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `repfiles'\\`restscorefiles'``i'' ,`replace'
+ }
+ }
+}
+if "`logistic'"!="" {
+ forvalues i=1/`nbitems' {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ qui gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+if "`drawcomb'"!="" {
+ local drawcomb="nodraw"
+}
+
+*di " (`score'!=&`onlyone'==)&`nograph'!= {"
+if ("`score'"!=""&"`onlyone'"=="")&"`nograph'"!="" {
+ graph combine $score , title("Trace of the items as a function of the score") name(score,replace) `drawcomb'
+ if "`scorefiles'"!="" {
+ graph save score `repfiles'\\`scorefiles' ,`replace'
+ }
+}
+
+if ("`restscore'"!=""&"`onlyone'"=="")&"`nograph'"!="" {
+ graph combine $restscore , title("Trace of the items as a function of the restscores") name(restscore,replace) `drawcomb'
+ if "`restscorefiles'"!="" {
+ graph save restscore `repfiles'\\`restscorefiles' ,`replace'
+ }
+}
+if ("`logistic'"!="")&"`nograph'"!="" {
+ graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `drawcomb'
+ if "`logisticfile'"!="" {
+ graph save logistic `repfiles'\\`logisticfile' ,`replace'
+ }
+}
+if "`saveicc'"!="" {
+ return matrix matscore=`matscore'
+}
+end
+
+
diff --git a/Modules/ado/personal/t/traces.ado b/Modules/ado/personal/t/traces.ado
new file mode 100644
index 0000000..c5751c0
--- /dev/null
+++ b/Modules/ado/personal/t/traces.ado
@@ -0,0 +1,429 @@
+*! Version 5.2 24September2019
+*!Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Traces: Traces of items
+*
+* Historic:
+* Version 1 (2003-06-29) [Jean-Benoit Hardouin]
+* Version 2 (2003-07-04 [Jean-Benoit Hardouin]
+* version 3 (2003-07-09) [Jean-Benoit Hardouin]
+* Version 3.1 (2005-06-07) [Jean-Benoit Hardouin] /*small modifications*/
+* Version 3.2: May 27, 2007 [Jean-Benoit Hardouin] /*onlyone option*/
+* Version 3.3: October 16, 2012 [Jean-Benoit Hardouin] /*minor modifications*/
+* Version 4: January 22, 2015 [Jean-Benoit Hardouin] /*ICC*/
+* Version 5: March 5, 2016 [Jean-Benoit Hardouin] /*numerical items*/
+* Version 5.1: July 13, 2019 [Jean-Benoit Hardouin] /*Bugs Corrections*/
+* Version 5.2: September 24, 2019 [Jean-Benoit Hardouin] /*Bugs Corrections*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* INSERM UMR 1246-SPHERE "Methods in Patient Centered Outcomes and Health Research", Nantes University, University of Tours
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program :http://www.anaqol.org
+*
+* Copyright 2003, 2005, 2007, 2012, 2015, 2016, 2019 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 traces, rclass
+version 8.0
+syntax varlist(numeric min=2) [, /*COMPare(varlist min=2 max=2*/ ICC noGraph Score Test Restscore Logistic CI CUMulative REPFiles(string) DIRSave(string) FILESave SCOREFiles(string) RESTSCOREFiles(string) LOGISTICFile(string) ICCFile(string) noDraw noDRAWComb REPlace ONLYone(string) THResholds(string) Black]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if "`onlyone'"!=""&"`drawcomb'"!="" {
+ local drawcomb
+}
+
+if "`repfiles'"!=""&"`dirsave'"=="" {
+ local dirsave `repfile'
+}
+if "`filesave'"=="" {
+ local saving
+}
+else {
+ if "`dirsave'"=="" {
+ local dirsave `c(pwd)'
+ }
+ if "`scorefiles'"=="" {
+ local scorefiles score
+ }
+ if "`restscorefiles'"=="" {
+ local restscorefiles restscore
+ }
+ if "`logicticfile'"=="" {
+ local logisticfile logistic
+ }
+ if "`iccfiles'"=="" {
+ local iccfiles icc
+ }
+}
+
+tempvar varscore
+qui gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+ local score="score"
+}
+
+local modamax=-999
+local modamin=999
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ local modamin`i'=r(min)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+ if `modamax`i''>`modamax' {
+ local modamax=`modamax`i''
+ }
+ if `modamin`i''<`modamin' {
+ local modamin=`modamin`i''
+ }
+}
+
+/*
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+*/
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+local minscore=r(min)
+
+forvalues i=`minscore'/`maxscore' {
+ qui count if `varscore'>`=`i'-0.5'&`varscore'<=`=`i'+0.5'
+ local nscore`i'=r(N)
+}
+
+
+global score
+global restscore
+global logistic
+qui count
+local N=r(N)
+if `c(matsize)'<`N'&"`saveicc'"!="" {
+ set matsize `N'
+}
+
+
+if "`score'"!="" {
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode min/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "min/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+ tempname varscore2
+ qui gen `varscore2'=`varscore'
+ qui recode `varscore' `recode'
+ qui label values `varscore' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+ local listicc
+ local widthicc
+
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar icc``i''
+ gen `icc``i'''=0
+ label variable `icc``i''' "``i''"
+ local listicc `listicc' `icc``i'''
+ local l=0
+ *set trace on
+ forvalues k=`=`modamin`i''+1'/`modamax`i'' {
+ tempvar propscore`i'`k' tmp propscoreicc`i'`k' tmp2
+ if "`cumulative'"!="" {
+ qui gen `tmp'=``i''>=`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `tmp'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''=`k'"
+ }
+ if "`icc'"!="" {
+ qui gen `tmp2'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscoreicc`i'`k''=mean(`tmp2')
+ qui replace `icc``i'''=`icc``i'''+`k'*`propscoreicc`i'`k''
+ }
+ *di "replace icc``i''=icc``i''+`k'*`propscore`i'`k''"
+ local y`i'="`y`i'' `propscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ forvalues m=1/`maxscore' {
+ qui count if `varscore'==`m'
+ local nscore`m'=r(N)
+ }
+ qui gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ qui gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ local ++l
+ }
+ *set trace on
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`graph'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`scorefiles'_``i'',replace)"
+ }
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title("Trace of the item ``i'' as a function of the score") ytitle("Rate of positive response") `draw' `saving'
+ }
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`icc'"!=""&"`graph'"==""{
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`iccfiles'_``i'',replace)"
+ }
+ local widthicc `widthicc' medthick
+ qui graph twoway (line `icc``i''' `varscore', /*clpattern(`style') clcolor(`color')*/ clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax`i'') xlabel(`minimum'(1)`nbgroups',valuelabel) name(icc`i',replace) title("Approximate ICC of the item ``i'' as a function of the score") ytitle("Mean response") `draw' `saving'
+ }
+ /*
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `dirsave'\\`scorefiles'``i'' ,`replace'
+ }
+ */
+ }
+ if "`saveicc'"!="" {
+ local listicc `listicc' `varscore'
+ tempname matscore
+ mkmat `listicc',matrix(`matscore')
+ }
+ if "`thresholds'"!="" {
+ qui replace `varscore'=`varscore2'
+ }
+ if "`onlyone'"==""&"`icc'"!=""&"`graph'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`iccfiles',replace)"
+ }
+ qui graph twoway (line `listicc' `varscore', /*clpattern(`style') clcolor(`color')*/ clwidth(`widthicc')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax`i'') xlabel(`minimum'(1)`nbgroups',valuelabel) name(icc,replace) title("Approximate ICC of the items as a function of the score") ytitle("Mean response") `draw' `saving'
+ }
+}
+/*
+ if "`compare'"!=""&"`graph'"=="" {
+ local tmp1 : word 1 of `compare'
+ local tmp2 : word 2 of `compare'
+ di "compare `compare' tmp1 `tmp1' tmp2 `tmp2'"
+ label variable `icc`tmp1'' `tmp1'
+ label variable `icc`tmp2'' `tmp2'
+ di "qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title(Comparison of the ICC of the items `tmp1' and `tmp2') `draw' /*areastyle(none)*/"
+ qui graph twoway (line `icc`tmp1'' `varscore', clpattern(`style') clcolor(blue red) clwidth(`width')) (line `icc`tmp2'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , ylabel(0(.5)`modamax') xlabel(`minimum'(1)`nbgroups',valuelabel) /*name(score`i',replace)*/ title("Comparison of the ICC of the items `tmp1' and `tmp2'") ytitle("Mean response") /*areastyle(none)*/
+ }
+*/
+*set trace on
+if "`restscore'"!="" {
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar restscore`i'
+ qui gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "min/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+
+ *di "recode `restscore`i'' `recode'"
+ qui recode `restscore`i'' `recode'
+ qui label values `restscore`i'' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ qui gen `rtmp'=``i''>=`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `rtmp'=``i''==`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ qui gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ qui gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ local restscoremax=`scoremax'-`modamax`i''
+ if ("``i''"=="`onlyone'"|"`onlyone'"=="")&"`graph'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`restscorefiles'_``i'',replace)"
+ }
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(restscore`i',replace) title("Trace of the item ``i'' as a function of the restscore") ytitle("Rate of positive response") `draw' `saving'
+ }
+ /*
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `dirsave'\\`restscorefiles'``i'' ,`replace'
+ }
+ */
+ }
+}
+if "`logistic'"!="" {
+ forvalues i=1/`nbitems' {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ qui gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+
+if "`score'"!=""&"`onlyone'"==""&"`graph'"==""&"`drawcomb'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`scorefiles',replace)"
+ }
+ local score
+ local restscoreg
+ forvalues i=1/`nbitems'{
+ local score `score' score`i'
+ local restscoreg `restscoreg' restscore`i'
+ }
+
+ qui graph combine `score', title("Trace of the items as a function of the score") name(score,replace) `draw' `saving'
+ /*
+ if "`scorefiles'"!="" {
+ graph save score `dirsave'\\`scorefiles' ,`replace'
+ }
+ */
+}
+
+if "`restscore'"!=""&"`onlyone'"==""&"`graph'"==""&"`drawcomb'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`restscorefiles',replace)"
+ }
+ qui graph combine `restscoreg' , title("Trace of the items as a function of the restscores") name(restscore,replace) `draw' `saving'
+ /*
+ if "`restscorefiles'"!="" {
+ graph save restscore `dirsave'\\`restscorefiles' ,`replace'
+ }
+ */
+}
+if "`logistic'"!=""&"`onlyone'"==""&"`graph'"=="" {
+ if "`filesave'"!="" {
+ local saving "saving(`dirsave'//`logisticfile',replace)"
+ }
+ qui graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `draw'
+ /*
+ if "`logisticfile'"!="" {
+ graph save logistic `dirsave'\\`logisticfile' ,`replace'
+ }
+ */
+}
+if "`saveicc'"!="" {
+ return matrix matscore=`matscore'
+}
+end
+
+
diff --git a/Modules/ado/personal/t/traces.hlp b/Modules/ado/personal/t/traces.hlp
new file mode 100644
index 0000000..af423a4
--- /dev/null
+++ b/Modules/ado/personal/t/traces.hlp
@@ -0,0 +1,99 @@
+{smcl}
+{* 6May2013}{...}
+{hline}
+help for {hi:traces}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Graphical representations of the traces of dichotomous and polytomous items}
+
+{p 8 14 2}{cmd:traces} {it:varlist} [{cmd:,} {cmdab:s:core} {cmdab:r:estscore}
+{cmdab:ci} {cmdab:t:est} {cmdab:cum:ulative} {cmdab:l:ogistic}
+{cmdab:repf:ile}({it:directory}) {cmdab:scoref:iles}({it:string})
+{cmdab:restscoref:iles}({it:string}) {cmdab:logisticf:ile}({it:string})
+{cmdab:nod:raw} {cmdab:nodrawc:omb} {cmdab:rep:lace} {cmdab:only:one}({it:varname}) {cmdab:thr:esholds}({it:string})]
+
+
+{title:Description}
+
+{p 4 8 2}{cmd:traces} builds graphical representations of various kinds of
+traces (non parametric Item Response Functions) for dichotomous or polytomous items.
+
+{title:Options}
+
+{p 4 8 2}{cmd:score} displays the graphical representations of the traces of the
+items as a function of the total score. This is the defaut option if none {cmd:score},
+none {cmd:restscore}, none {cmd:logistic} are indicated.
+
+{p 4 8 2}{cmd:restscore} displays the graphical representations of the
+traces of the items as a function of the rest-score (total score unless the item).
+
+{p 4 8 2}{cmd:ci} displays the confidence interval at 95% of the traces.
+
+{p 4 8 2}{cmd:test} tests the nullity of the slope of dichotomous items traces
+with a linear model.
+
+{p 4 8 2}{cmd:cumulative} displays cumulative traces for polytomous
+items instead of classical traces.
+
+{p 4 8 2}{cmd:logistic} displays the graphical representation of the logitic
+traces of the items as a function of the score: each trace is the result of a
+logistic model with the response to the item as variable to explicate and the
+score (and a constant) as explicative variable. This kind of trace is possible
+only for dichotomous items. All the logistic traces are represented in the same
+graph.
+
+{p 4 8 2}{cmd:repfile}({it:directory}) is the directory where the files are saved.
+
+{p 4 8 2}{cmd:scorefiles}({it:string}) defines the generic name of the files containing the graphical representations of the traces as a function of the score.
+The name will be followed by the name of each item and by the .gph extension. If this option is not
+indicated, the corresponding graphs will be not saved.
+
+{p 4 8 2}{cmd:restscorefiles}({it:string}) defines the generic name of the files containing the graphical representations of the traces as a function of the rest-scores.
+The name will be followed by the name of each item and by the .gph extension. If this option is not
+indicated, the corresponding graphs will be not saved.
+
+{p 4 8 2}{cmd:logisticfile}({it:string}) defines the name of the file containing the graphical representations of the logistic traces. This name will be followed by the .gph extension.
+If this option is not indicated, the corresponding graph will be not saved.
+
+{p 4 8 2}{cmd:nodraw} does not display the graphs by items.
+
+{p 4 8 2}{cmd:nodrawcomb} does not display the combined graphs by items.
+
+{p 4 8 2}{cmd:replace} replaces graphical files when they already exist.
+
+{p 4 8 2}{cmd:onlyone} displays only the trace of a given item.
+
+{p 4 8 2}{cmd:thresholds} groups the individuals as a function of the (rest-)score. The string contains the maximal values of the (rest-)score in each group.
+
+
+
+{title:Example}
+
+ {p 4 8 2}{cmd:. traces item1 item2 item3 item4 , score repfile(c:\graphs) scorefiles(score) nodraw nodrawcomb replace} /*creates the graphs files of the
+traces as a function of the score but do not display them.*/
+
+ {p 4 8 2}{cmd:. traces item1 item2 item3 item4 , score restscore} /*displays
+the graphical representations of the traces of the items as a function of the
+score and of the rest-scores, but does not save them*/
+
+ {p 4 8 2}{cmd:. traces itemA*} /*displays the graphical
+representations of the traces of the items as a function of the score, by
+default*/
+
+ {p 4 8 2}{cmd:. traces itemA*} ,only(itemA2) thresholds(2 3 5)/*displays the graphical
+representations of the traces of the item A2 as a function of the score. Individuals are grouped: a first group of individuals with scores from 0 to 2, a second group with a score of 3, a third group with a score between 4 and 5 and a last group with a score superior to 5*/
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Website {browse "http://www.anaqol.org":AnaQol}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help graph}, {help loevH} and {help gengroup} if installed.{p_end}
diff --git a/Modules/ado/personal/t/traces3.ado b/Modules/ado/personal/t/traces3.ado
new file mode 100644
index 0000000..ffd63a9
--- /dev/null
+++ b/Modules/ado/personal/t/traces3.ado
@@ -0,0 +1,232 @@
+************************************************************************************************************
+* Traces: Traces of items
+* version 3: July 9, 2003
+*
+* Historic:
+* Version 1 (2003-06-29): Jean-Benoit Hardouin
+* Version 2 (2003-07-04): Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, Regional Health Observatory of Orléans - France
+* jean-benoit.hardouin@neuf.fr
+*
+* News about this program : http://anaqol.free.fr
+* FreeIRT Project : http://freeirt.free.fr
+*
+* Copyright 2003 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 traces
+version 8.0
+syntax varlist(numeric min=2) [, score test restscore logistic ci cumulative repfiles(string) scorefiles(string) restscorefiles(string) logisticfile(string) nodraw nodrawcomb replace]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+tempvar varscore
+gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+local score="score"
+}
+
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+}
+
+if `flag'==1 {
+di as error "The lower modalities of the item must be 0"
+exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+
+forvalues i=0/`maxscore' {
+ qui count if `varscore'==`i'
+ local nscore`i'=r(N)
+}
+
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is impossible with polytomic items"
+ exit
+}
+
+global score
+global restscore
+global logistic
+
+forvalues i=1/`nbitems' {
+ if "`score'"!="" {
+ local y`i'
+ forvalues k=1/`modamax`i'' {
+ tempvar propscore`i'`k' tmp
+ if "`cumulative'"!="" {
+ gen `tmp'=``i''>=`k'
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ gen `tmp'=``i''==`k'
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `propscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore`i'')
+ gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore`i'')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(0(1)`scoremax') name(score`i',replace) title("Trace of the item ``i'' in fonction of the score") ytitle("Rate of positive response") `draw'
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `repfiles'\\`scorefiles'``i'' ,`replace'
+ }
+ }
+ if "`restscore'"!="" {
+ local y`i'
+ tempvar restscore`i'
+ gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ gen `rtmp'=``i''>=`k'
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ gen `rtmp'=``i''==`k'
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+}
+ local restscoremax=`scoremax'-`modamax`i''
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(0(1)`restscoremax') name(restscore`i',replace) title("Trace of the item ``i'' in fonction of the restscore") ytitle("Rate of positive response") `draw'
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `repfiles'\\`restscorefiles'``i'' ,`replace'
+ }
+ }
+ if "logistic"!="" {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+
+if "`drawcomb'"!="" {
+local drawcomb="nodraw"
+}
+
+if "`score'"!="" {
+graph combine $score , title("Trace of the items in function of the score") name(score,replace) `drawcomb'
+if "`scorefiles'"!="" {
+ graph save score `repfiles'\\`scorefiles' ,`replace'
+}
+}
+
+if "`restscore'"!="" {
+graph combine $restscore , title("Trace of the items in function of the restscores") name(restscore,replace) `drawcomb'
+if "`restscorefiles'"!="" {
+ graph save restscore `repfiles'\\`restscorefiles' ,`replace'
+}
+}
+
+if "`logistic'"!="" {
+graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `drawcomb'
+if "`logisticfile'"!="" {
+ graph save logistic `repfiles'\\`logisticfile' ,`replace'
+}
+}
+
+
+end
+
+
diff --git a/Modules/ado/personal/t/traces32.ado b/Modules/ado/personal/t/traces32.ado
new file mode 100644
index 0000000..8495b13
--- /dev/null
+++ b/Modules/ado/personal/t/traces32.ado
@@ -0,0 +1,309 @@
+*! Version 3.2 27May2007
+************************************************************************************************************
+* Traces: Traces of items
+* Version 3.2: May 27, 2007 (onlyone option)
+*
+* Historic:
+* Version 1 (2003-06-29): Jean-Benoit Hardouin
+* Version 2 (2003-07-04): Jean-Benoit Hardouin
+* version 3 (2003-07-09): Jean-Benoit Hardouin
+* Version 3.1 (2005-06-07): Jean-Benoit Hardouin /*small modifications*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2003, 2005, 2007 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 traces
+version 8.0
+syntax varlist(numeric min=2) [, Score Test Restscore Logistic CI CUMulative REPFiles(string) SCOREFiles(string) RESTSCOREFiles(string) LOGISTICFile(string) noDraw noDRAWComb REPlace ONLYone(string) THResholds(string)]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if "`onlyone'"!=""&"`drawcomb'"!="" {
+ local drawcomb
+}
+
+tempvar varscore
+qui gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+ local score="score"
+}
+
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+}
+
+
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+
+forvalues i=0/`maxscore' {
+ qui count if `varscore'==`i'
+ local nscore`i'=r(N)
+}
+
+
+global score
+global restscore
+global logistic
+
+if "`score'"!="" {
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+ tempname varscore2
+ qui gen `varscore2'=`varscore'
+ qui recode `varscore' `recode'
+ qui label values `varscore' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues i=1/`nbitems' {
+ local y`i'
+ forvalues k=1/`modamax`i'' {
+ tempvar propscore`i'`k' tmp
+ if "`cumulative'"!="" {
+ qui gen `tmp'=``i''>=`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `tmp'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `propscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ forvalues l=1/`maxscore' {
+ qui count if `varscore'==`l'
+ local nscore`l'=r(N)
+ }
+ qui gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ qui gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ if "``i''"=="`onlyone'"|"`onlyone'"=="" {
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title("Trace of the item ``i'' as a function of the score") ytitle("Rate of positive response") `draw'
+ }
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `repfiles'\\`scorefiles'``i'' ,`replace'
+ }
+ }
+ if "`thresholds'"!="" {
+ qui replace `varscore'=`varscore2'
+ }
+}
+if "`restscore'"!="" {
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar restscore`i'
+ qui gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+
+ *di "recode `restscore`i'' `recode'"
+ qui recode `restscore`i'' `recode'
+ qui label values `restscore`i'' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ qui gen `rtmp'=``i''>=`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `rtmp'=``i''==`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ qui gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ qui gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ local restscoremax=`scoremax'-`modamax`i''
+ if "``i''"=="`onlyone'"|"`onlyone'"=="" {
+ *tab `proprestscore`i'1' `restscore`i''
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(restscore`i',replace) title("Trace of the item ``i'' as a function of the restscore") ytitle("Rate of positive response") `draw'
+ }
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `repfiles'\\`restscorefiles'``i'' ,`replace'
+ }
+ }
+}
+if "logistic"!="" {
+ forvalues i=1/`nbitems' {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ qui gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+if "`drawcomb'"!="" {
+ local drawcomb="nodraw"
+}
+
+if "`score'"!=""&"`onlyone'"=="" {
+ graph combine $score , title("Trace of the items as a function of the score") name(score,replace) `drawcomb'
+ if "`scorefiles'"!="" {
+ graph save score `repfiles'\\`scorefiles' ,`replace'
+ }
+}
+
+if "`restscore'"!=""&"`onlyone'"=="" {
+ graph combine $restscore , title("Trace of the items as a function of the restscores") name(restscore,replace) `drawcomb'
+ if "`restscorefiles'"!="" {
+ graph save restscore `repfiles'\\`restscorefiles' ,`replace'
+ }
+}
+if "`logistic'"!="" {
+ graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `drawcomb'
+ if "`logisticfile'"!="" {
+ graph save logistic `repfiles'\\`logisticfile' ,`replace'
+ }
+}
+
+
+end
+
+
diff --git a/Modules/ado/personal/t/traces33.ado b/Modules/ado/personal/t/traces33.ado
new file mode 100644
index 0000000..be4f550
--- /dev/null
+++ b/Modules/ado/personal/t/traces33.ado
@@ -0,0 +1,310 @@
+*! Version 3.3 16October2012
+************************************************************************************************************
+* Traces: Traces of items
+* Version 3.3: October 16, 2012 /*minor modifications*/
+*
+* Historic:
+* Version 1 (2003-06-29): Jean-Benoit Hardouin
+* Version 2 (2003-07-04): Jean-Benoit Hardouin
+* version 3 (2003-07-09): Jean-Benoit Hardouin
+* Version 3.1 (2005-06-07): Jean-Benoit Hardouin /*small modifications*/
+* Version 3.2: May 27, 2007 /*onlyone option*/
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2003, 2005, 2007, 2012 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 traces
+version 8.0
+syntax varlist(numeric min=2) [, Score Test Restscore Logistic CI CUMulative REPFiles(string) SCOREFiles(string) RESTSCOREFiles(string) LOGISTICFile(string) noDraw noDRAWComb REPlace ONLYone(string) THResholds(string) Black]
+
+local nbitems : word count `varlist'
+tokenize `varlist'
+
+if "`onlyone'"!=""&"`drawcomb'"!="" {
+ local drawcomb
+}
+
+tempvar varscore
+qui gen `varscore'=0
+label variable `varscore' "Total score"
+local scoremax=0
+local flag=0
+
+if "`score'"==""&"`restscore'"==""&&"`logistic'"=="" {
+ local score="score"
+}
+
+forvalues i=1/`nbitems' {
+ qui replace `varscore'=`varscore'+``i''
+ qui su ``i''
+ local modamax`i'=r(max)
+ if r(min)!=0 {
+ local flag=1
+ }
+ local scoremax=`scoremax'+`modamax`i''
+ if `modamax`i''!=1 {
+ local flagbin=0
+ }
+}
+
+
+if `flag'==1 {
+ di as error "The lower modality of the item must be 0"
+ exit
+}
+if "`flagbin'"!=""&"`logistic'"!="" {
+ di as error "The logistic option is not possible with polytomous items"
+ exit
+}
+
+qui su `varscore'
+local maxscore=r(max)
+
+forvalues i=0/`maxscore' {
+ qui count if `varscore'==`i'
+ local nscore`i'=r(N)
+}
+
+
+global score
+global restscore
+global logistic
+
+if "`score'"!="" {
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+ tempname varscore2
+ qui gen `varscore2'=`varscore'
+ qui recode `varscore' `recode'
+ qui label values `varscore' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues i=1/`nbitems' {
+ local y`i'
+ forvalues k=1/`modamax`i'' {
+ tempvar propscore`i'`k' tmp
+ if "`cumulative'"!="" {
+ qui gen `tmp'=``i''>=`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `tmp'=``i''==`k'&``i''!=.
+ bysort `varscore' : egen `propscore`i'`k''=mean(`tmp')
+ label variable `propscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `propscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icscoreminus icscoreplus
+ forvalues l=1/`maxscore' {
+ qui count if `varscore'==`l'
+ local nscore`l'=r(N)
+ }
+ qui gen `icscoreminus'=`propscore`i'1'-1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ qui gen `icscoreplus'=`propscore`i'1'+1.96*sqrt(`propscore`i'1'*(1-`propscore`i'1')/`nscore1')
+ label variable `icscoreminus' "Lower 95% confidence interval"
+ label variable `icscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icscoreminus' `icscoreplus' `propscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `propscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ if "``i''"=="`onlyone'"|"`onlyone'"=="" {
+ qui graph twoway (line `y`i'' `varscore', clpattern(`style') clcolor(`color') clwidth(`width')) if `varscore'!=0&`varscore'!=`maxscore' , note("`note'") ylabel(0(.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(score`i',replace) title("Trace of the item ``i'' as a function of the score") ytitle("Rate of positive response") `draw' areastyle(none)
+ }
+ global score "$score score`i'"
+ if "`scorefiles'"!="" {
+ graph save score`i' `repfiles'\\`scorefiles'``i'' ,`replace'
+ }
+ }
+ if "`thresholds'"!="" {
+ qui replace `varscore'=`varscore2'
+ }
+}
+if "`restscore'"!="" {
+ forvalues i=1/`nbitems' {
+ local y`i'
+ tempvar restscore`i'
+ qui gen `restscore`i''=`varscore'-``i''
+ label variable `restscore`i'' "Rest score with respect to the item ``i''"
+ if "`thresholds'"!="" {
+ * set trace on
+ local nbth:word count `thresholds'
+ forvalues t=1/`nbth' {
+ local th`t':word `t' of `thresholds'
+ }
+ tempname label
+ local recode 0/`th1'=1 `=`th`nbth''+1'/max=`=`nbth'+1'
+ qui label define `label' 1 "0/`th1'",add
+ qui label define `label' `=`nbth'+1' "`=`th`nbth''+1'/max",add
+ forvalues j=2/`nbth' {
+ local recode `recode' `=`th`=`j'-1''+1'/`th`j''=`j'
+ qui label define `label' `j' "`=`th`=`j'-1''+1'/`th`j''",add
+ }
+
+ *di "recode `restscore`i'' `recode'"
+ qui recode `restscore`i'' `recode'
+ qui label values `restscore`i'' `label'
+ local nbgroups=`nbth'+1
+ local minimum=1
+ }
+ else {
+ local nbgroups=`maxscore'
+ local minimum=0
+ }
+
+ forvalues k=1/`modamax`i'' {
+ tempvar rtmp proprestscore`i'`k'
+ if "`cumulative'"!="" {
+ qui gen `rtmp'=``i''>=`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''>=`k'"
+ }
+ else {
+ qui gen `rtmp'=``i''==`k'&``i''!=.
+ bysort `restscore`i'': egen `proprestscore`i'`k''=mean(`rtmp')
+ label variable `proprestscore`i'`k'' "Item ``i''=`k'"
+ }
+ local y`i'="`y`i'' `proprestscore`i'`k''"
+ local style="solid"
+ local color="black"
+ local width="medthick"
+ if `modamax`i''==1&"`ci'"!="" {
+ tempvar icrestscoreminus icrestscoreplus
+ qui su `restscore`i''
+ local maxrestscore=r(max)
+ forvalues l=1/`maxrestscore' {
+ qui count if `restscore`i''==`l'
+ local nrestscore`i'=r(N)
+ }
+ qui gen `icrestscoreminus'=`proprestscore`i'1'-1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ qui gen `icrestscoreplus'=`proprestscore`i'1'+1.96*sqrt(`proprestscore`i'1'*(1-`proprestscore`i'1')/`nrestscore`i'')
+ label variable `icrestscoreminus' "Lower 95% confidence interval"
+ label variable `icrestscoreplus' "Upper 95% confidence interval"
+ local y`i'="`icrestscoreminus' `icrestscoreplus' `proprestscore`i'1'"
+ local style="dash dash solid"
+ local color="red red black"
+ local width="thin thin medthick"
+ }
+ if `modamax`i''==1&"`test'"!="" {
+ qui regress `proprestscore`i'1' `varscore'
+ local p=Fden(e(df_m),e(df_r),e(F))
+ if `p'<0.0001 {
+ local note="Test: slope=0, p<0.0001"
+ }
+ else {
+ local p=substr("`p'",1,6)
+ local note="Test: slope=0, p=`p'"
+ }
+ }
+ }
+ local restscoremax=`scoremax'-`modamax`i''
+ if "``i''"=="`onlyone'"|"`onlyone'"=="" {
+ *tab `proprestscore`i'1' `restscore`i''
+ qui graph twoway (line `y`i'' `restscore`i'', clpattern(`style') clcolor(`color') clwidth(`width')), note("`note'") ylabel(0(0.25)1) xlabel(`minimum'(1)`nbgroups',valuelabel) name(restscore`i',replace) title("Trace of the item ``i'' as a function of the restscore") ytitle("Rate of positive response") `draw'
+ }
+ global restscore "$restscore restscore`i'"
+ if "`restscorefiles'"!="" {
+ graph save restscore`i' `repfiles'\\`restscorefiles'``i'' ,`replace'
+ }
+ }
+}
+if "logistic"!="" {
+ forvalues i=1/`nbitems' {
+ qui logistic ``i'' `varscore'
+ tempname coef
+ matrix `coef'=e(b)
+ local pente`i'=`coef'[1,1]
+ local intercept`i'=`coef'[1,2]
+ tempvar logit`i'
+ qui gen `logit`i''=exp(`intercept`i''+`pente`i''*`varscore')/(1+exp(`intercept`i''+`pente`i''*`varscore'))
+ label variable `logit`i'' "Item ``i''"
+ sort `varscore'
+ global logistic "$logistic `logit`i''"
+ }
+}
+if "`drawcomb'"!="" {
+ local drawcomb="nodraw"
+}
+
+if "`score'"!=""&"`onlyone'"=="" {
+ graph combine $score , title("Trace of the items as a function of the score") name(score,replace) `drawcomb'
+ if "`scorefiles'"!="" {
+ graph save score `repfiles'\\`scorefiles' ,`replace'
+ }
+}
+
+if "`restscore'"!=""&"`onlyone'"=="" {
+ graph combine $restscore , title("Trace of the items as a function of the restscores") name(restscore,replace) `drawcomb'
+ if "`restscorefiles'"!="" {
+ graph save restscore `repfiles'\\`restscorefiles' ,`replace'
+ }
+}
+if "`logistic'"!="" {
+ graph twoway (line $logistic `varscore'), ylabel(0(0.25)1) xlabel(0(1)`nbitems') title("Logistic traces") ytitle("") name(logistic,replace) `drawcomb'
+ if "`logisticfile'"!="" {
+ graph save logistic `repfiles'\\`logisticfile' ,`replace'
+ }
+}
+
+
+end
+
+
diff --git a/Modules/ado/personal/t/tri.ado b/Modules/ado/personal/t/tri.ado
new file mode 100644
index 0000000..f744081
--- /dev/null
+++ b/Modules/ado/personal/t/tri.ado
@@ -0,0 +1,146 @@
+program define tri
+syntax varlist [fweight iweight] [,global test(int 2) all]
+
+preserve
+local nbvar:word count `varlist'
+tokenize `varlist'
+/*forvalues i=1/`nbvar' {
+ qui su ``i'' [`weight'`exp']
+ qui replace ``i''=(``i''-r(mean))/r(sd)
+} */
+
+
+/*METHOD GLOBAL */
+
+
+/* COVARIANCE OR CORRELATION MATRIX*/
+
+if "`global'"!="" {
+ tempname Cov W
+ qui matrix accum `Cov'=`varlist' [`weight'`exp'],nocons dev
+ qui matrix `Cov'=`Cov'/(`nbind'-1)
+ matrix `W'=J(2,`nbvar',0)
+
+ local newlist
+ tempvar centroid
+ genscore `varlist',mean score(`centroid')
+
+ forvalues i=1/`nbvar' {
+ qui corr ``i'' `centroid' [`weight'`exp']
+ matrix `W'[1,`i']=`r(rho)'
+ }
+
+ forvalues c=1/`nbvar'{
+ local corrmin=2
+ local var=0
+ forvalues i=1/`nbvar' {
+ if `W'[1,`i']<`corrmin'&`W'[2,`i']==0 {
+ local corrmin=`W'[1,`i']
+ local var=`i'
+ }
+ }
+ matrix `W'[2,`var']=`c'
+ }
+ matrix list `W'
+ forvalues c=1/`nbvar' {
+ forvalues i=1/`nbvar' {
+ if `W'[2,`i']==`c' {
+ local newlist `newlist' ``i''
+ }
+ }
+ }
+ local varlist "`newlist'"
+ tokenize `varlist'
+}
+if "`all'"=="" {
+ local time=1
+}
+else {
+ local time=`nbvar'
+}
+
+local maxc=-99
+local part
+forvalues t=1/`time' {
+ tempname W
+ matrix `W'=J(1,`nbvar',0)
+ matrix `W'[1,`t']=1
+ forvalues iter=1/`nbvar' {
+ local dejaselect
+ forvalues i=1/`nbvar' {
+ if `W'[1,`i']!=0 {
+ local dejaselect `dejaselect' ``i''
+ }
+ }
+ tempvar centroid
+ qui genscore `dejaselect',score(`centroid') standardized
+ local maxr=-2
+ local maxi=0
+ forvalues i=1/`nbvar' {
+ if `W'[1,`i']==0 {
+ qui corr `centroid' ``i''
+ local r=r(rho)
+ if `r'>`maxr' {
+ local maxr=`r'
+ local maxi=`i'
+ }
+ }
+ }
+ if `maxi'!=0 {
+ matrix `W'[1,`maxi']=`iter'+1
+ }
+ }
+ local list
+ forvalues class=1/`nbvar' {
+ forvalues i=1/`nbvar' {
+ if `W'[1,`i']==`class' {
+ local list `list' ``i''
+ }
+ }
+ }
+ di "`list'"
+ forvalues i=0/`nbvar' {
+ local j=`nbvar'-`i'
+ if `test'>2 {
+ local jb `j'
+ }
+ else {
+ local jb 0
+ }
+ forvalues k=0/`jb' {
+ local l=`nbvar'-`i'-`k'
+ if `test'>3 {
+ local lb=`l'
+ }
+ else {
+ local lb=0
+ }
+ forvalues m=0/`lb' {
+ local n=`nbvar'-`i'-`k'-`m'
+ qui di "compart `list',part(`i' `k' `m' `n')"
+ di "`i' `k' `m' `n'"
+ if `i'>=0&`k'>=0&`m'>=0&`n'>=0 {
+ di " compart `list',part(`i' `k' `m' `n')"
+ qui compart2 `list',part(`i' `k' `m' `n')
+ local c=r(compart)
+ di "`c'"
+ if `c'>`maxc' {
+ local maxc=`c'
+ local part=r(part)
+ local savlist `list'
+ *di "Best : `c'"
+ }
+ }
+ }
+ }
+ }
+}
+ di "The best partition in two groups is `part'"
+ di "for `savlist'"
+ di "COMPART=`maxc'"
+
+
+
+
+restore
+end
diff --git a/Modules/ado/personal/t/trouve.ado b/Modules/ado/personal/t/trouve.ado
new file mode 100644
index 0000000..10f4190
--- /dev/null
+++ b/Modules/ado/personal/t/trouve.ado
@@ -0,0 +1,110 @@
+************************************************************************************************************
+* Trouve : trouve le nom d'un commune ou d'un canton de la région centre en indiquant son code
+*
+* Version 1.1: 16 aout 2004
+*
+* Jean-benoit Hardouin, Observatoire Régional de la Santé du Centre - Orléans - France
+* jean-benoit.hardouin@neuf.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 trouve,rclass
+version 7.0
+syntax anything
+local nbarg:word count `anything'
+capture su *
+if _rc==0 {
+ tempfile savetrouve
+ qui save `savetrouve',replace
+}
+preserve
+
+numlist "`anything'"
+local list `r(numlist)'
+
+foreach i of numlist `list' {
+ if (`i'>1800&`i'<1900)|(`i'>2800&`i'<2900)|(`i'>3600&`i'<3800)|(`i'>4100&`i'<4200)|(`i'>4500&`i'<4600) {
+ qui use "C:\ado\PERSONAL\files\cantons" ,clear
+ qui su id if codepct==`i'
+ local tmp=r(min)
+ local tmp=nompct[`tmp']
+ if "`tmp'"!="" {
+ di in green "`i' (canton):" in yellow " `tmp'"
+ return local trouve`i' "Canton : `tmp'"
+ }
+ else {
+ di in red "Il n'y a pas de canton avec ce numero (`i') dans la region Centre"
+ }
+ }
+ else if `i'>2400&`i'<2500 {
+ local erreur=0
+ if `i'==2411 {local name Bourges}
+ else if `i'==2412 {local name Vierzon}
+ else if `i'==2413 {local name Saint-Amand-Montrond}
+ else if `i'==2414 {local name Aubigny-sur-Nère}
+ else if `i'==2421 {local name Chartres}
+ else if `i'==2422 {local name Dreux}
+ else if `i'==2423 {local name Chateaudun}
+ else if `i'==2424 {local name Nogent le Rotrou}
+ else if `i'==2431 {local name Chateauroux}
+ else if `i'==2432 {local name Le Blanc}
+ else if `i'==2433 {local name Issoudun}
+ else if `i'==2434 {local name La Chatre}
+ else if `i'==2441 {local name Tours}
+ else if `i'==2442 {local name Amboise}
+ else if `i'==2443 {local name Loches}
+ else if `i'==2444 {local name Chinon}
+ else if `i'==2451 {local name Blois}
+ else if `i'==2452 {local name Vendome}
+ else if `i'==2453 {local name Romoranthin-Lanthenay}
+ else if `i'==2461 {local name Orleans}
+ else if `i'==2462 {local name Montargis}
+ else if `i'==2463 {local name Pithiviers}
+ else if `i'==2464 {local name Gien}
+ else {
+ di in red "Il n'y a pas de zone d'emploi avec ce numero (`i') dans la region Centre"
+ local erreur=1
+ }
+ if `erreur'==0 {
+ di in green "`i' (zone d'emploi):" in yellow " `name'"
+ return local trouve`i' "Zone d'emploi : `name'"
+ }
+ }
+ else if `i'>10000&`i'<100000 {
+ qui use "C:\ado\PERSONAL\files\communes" ,clear
+ qui su id if codecom==`i'
+ local tmp=r(min)
+ local tmp=nomcom[`tmp']
+ if "`tmp'"!="" {
+ di in green "`i' (commune):" in yellow " `tmp'"
+ return local trouve`i' "Commune : `tmp'"
+ }
+ else {
+ di in red "Il n'y a pas de commune avec ce numero (`i') dans la region Centre"
+ }
+ }
+ else {
+ di in red "Ce code n'est pas utilisable"
+ }
+}
+restore,not
+qui drop _all
+if "`savetrouve'"!="" {
+ qui use `savetrouve'
+}
+end
diff --git a/Modules/ado/personal/v/valid.ado b/Modules/ado/personal/v/valid.ado
new file mode 100644
index 0000000..10f2c0a
--- /dev/null
+++ b/Modules/ado/personal/v/valid.ado
@@ -0,0 +1,365 @@
+capture program drop valid
+program valid
+syntax varlist, PARTition(numlist integer >0) [SCOrename(string) IMPute NORound CALCmethod(string) DESCitems GRAPHs cfa CFAMethod(string) CFAStand CONVdiv TCONVdiv(real 0.4) CONVDIVBoxplots Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3) REPet(varlist) KAPpa ICKAPpa(integer 0) kgv(varlist) KGVBoxplots KGVGroupboxplots conc(varlist) tconc(real 0.4)]
+preserve
+
+qui set autotabgraphs on
+
+qui set more off
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+/*
+if `C' > `nbvars' {
+ di in red "The sum of the numbers in the partition option is greater than the number of variables in the dataset"
+ exit 119
+}
+*/
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+local P:word count `partition'
+
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ foreach sco in `scorename' {
+ capture confirm variable `sco'
+ if !_rc {
+ di in red "`sco' is a variable of the dataset. Choose another name"
+ exit 119
+ }
+ tokenize `scorename'
+ local g = 0
+ forvalues i = 1/`S' {
+ if "`sco'" == "``i''" {
+ local `++g'
+ }
+ }
+ if `g' > 1 {
+ di in red "2 or more dimensions have the same name"
+ exit 119
+ }
+ }
+}
+else {
+ local name
+ local nname
+
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+/*
+if "`ident'" == "" {
+ tempvar id
+ qui gen `id' = _n
+}
+else {
+ qui tab `ident', nofreq
+ local u = r(r)
+ if `u' != _N {
+ di in red "`ident' has not unique values"
+ exit 119
+ }
+}
+*/
+/*
+if "`repitems'" !="" {
+ local a : word count `repitems'
+ if mod(`a',2) != 0 {
+ di in red "error repitems: odd number"
+ exit
+ }
+ foreach r in `repitems' {
+ capture confirm variable `r'
+ if _rc!=0 {
+ di in red "`r' does not exist"
+ exit 119
+ }
+ }
+}
+*/
+/*
+local y = 0
+if "`repscores'" !="" {
+ local a : word count `repscores'
+ if mod(`a',2) != 0 {
+ di in red "error repscores : odd number"
+ exit 119
+ }
+ foreach r in `repscores' {
+ local x = 0
+ local y = 0
+ capture confirm variable `r'
+ if _rc!=0 local x = 1
+ foreach s in `scorename' {
+ if "`r'" == "`s'" local y = `y'+1
+ }
+ if `x' == 1 & `y' < 1 {
+ di "`r' " "non défini"
+ exit 119
+ }
+ }
+}
+*/
+
+if "`kgv'" !="" {
+ foreach k in `kgv' {
+ capture confirm variable `k'
+ if _rc!=0 {
+ di in red "`k' does not exist"
+ exit 119
+ }
+ }
+}
+
+if "`conc'" !="" {
+ foreach c in `conc' {
+ capture confirm variable `c'
+ if _rc!=0 {
+ di in red "`c' does not exist"
+ exit 119
+ }
+ }
+}
+/*
+if `t2from' > _N {
+ di in red "Reproductibility : invalid range for observations at time 2 (`t2from' > number of observations)"
+ exit 119
+}
+
+if `t2to' > _N {
+ di in red "Reproductibility : invalid range for observations at time 2 (`t2to' > number of observations)"
+ exit 119
+}
+
+if "`t2from'" != "" & "`t2to'" != "" {
+ if `t2from' > `t2to' {
+ di in red "Reproductibility : invalid range for observations at time 2"
+ exit 119
+ }
+}
+
+if "`t2from'" == "" local t2from = 1
+if "`t2to'" == "" local t2to = _N
+*/
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+di as result "Items used for calculation of the scores"
+di
+
+local i = 1
+local j = 1
+local y = 1
+foreach p in `partition' {
+ tokenize `scorename'
+ di "{bf:``i''} : " _c
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ forvalues z = `y'/`s' {
+ di "{text:`var`z'' }" _c
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+}
+
+qui destring _all, replace
+di
+/*
+local cpt = 0
+if "`sum'" != "" {
+ local cpt `cpt' + 1
+}
+if "`mean'" != "" {
+ local cpt `cpt' + 1
+}
+if "`stand'" != "" {
+ local cpt `cpt' + 1
+}
+if `cpt'>1 {
+ di in red "You must choose between mean, sum or stand (the options are exclusive)"
+ exit 119
+}
+*/
+calcscore `varlist', scorename(`scorename') partition(`partition') calcmethod(`calcmethod')
+
+if "`descitems'" != "" {
+ di as result "{hline}"
+ di "Description of items"
+ di as result "{hline}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+}
+if "`graphs'" != "" {
+ _graph `varlist', partition(`partition') scorename(`scorename') calcmethod(`calcmethod')
+}
+
+if "`repet'" != "" {
+ if "`descitems'" != "" {
+ di as result "{hline}"
+ di "Description of items (time 2)"
+ di as result "{hline}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+}
+
+if "`impute'" != "" {
+ *if "`noround'" != "" {
+ *di "Missing data handling (noround)"
+ *di
+
+ imp `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline}"
+ di "Description of items after missing data handling"
+ di as result "{hline}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`graphs'" != "" {
+ *_graph `varlist', partition(`partition') scorename(`scorename')
+ }
+ if "`repet'" != "" {
+ imp `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+
+
+ *}
+ /*else {
+ di "Missing data handling (round)"
+ di
+ imp `varlist', partition(`partition')
+ di "Description of items after missing data handling"
+ di
+ desc_item `varlist', partition(`partition')
+ if "`graphs'" != "" {
+ *_graph `varlist', partition(`partition') scorename(`scorename')
+ }
+ di "Description of items after missing data handling (time 2)"
+ di
+ if "`repet'" != "" {
+ imp `repet', partition(`partition')
+ desc_item `repet', partition(`partition')
+ }
+ di "{hline}"
+ }*/
+}
+
+/*
+if "`imp'" == "" & "`noround'" != "" {
+ *di "noround"
+ di
+ imp `varlist', partition(`partition') `noround'
+ if "`desc_items'" != "" {
+ di "Description of items after missing data handling"
+ di
+ desc_item `varlist', partition(`partition')
+
+ }
+ if "`graphs'" != "" {
+ *_graph `varlist', partition(`partition') scorename(`scorename')
+ }
+ di "Description of items after missing data handling (time 2)"
+ di
+ imp `repet', partition(`partition') `noround'
+ desc_item `repet', partition(`partition')
+ di "{hline}"
+
+}
+*/
+
+*di "{hline}"
+
+if "`convdiv'" != "" {
+ convdiv `varlist', scorename(`scorename') partition(`partition') tconvdiv(`tconvdiv') `convdivboxplots'
+ *di as result "{hline}"
+ di
+}
+
+/*
+if "`cfa'" != "" {
+ local cpt = 0
+ if "`cfa_ml'" != ""{
+ local method = "cfa_ml"
+ local cpt `cpt' + 1
+ }
+ if "`cfa_mlmv'" != "" {
+ local method = "cfa_mlmv"
+ local cpt `cpt' + 1
+ }
+ if "`cfa_adf'" != "" {
+ local method = "cfa_adf"
+ local cpt `cpt' + 1
+ }
+ else local method = "cfa_ml"
+ if `cpt' > 1 {
+ di in red "You must choose between cfa_ml, cfa_mlmv or cfa_adf (the options are exclusive)"
+ exit 119
+ }
+
+ cfa `varlist', scorename(`scorename') partition(`partition') `method' `cfa_stand'
+ di as result "{hline}"
+}
+*/
+
+if "`cfa'" != "" {
+ cfa `varlist', scorename(`scorename') partition(`partition') cfamethod(`cfamethod') `cfastand'
+ *di as result "{hline}"
+ di
+}
+
+rel `varlist', scorename(`scorename') partition(`partition') alpha(`alpha') delta(`delta') h(`h') hjmin(`hjmin')
+di
+*di "{hline}"
+
+if "`repet'" != "" {
+ repet `varlist', t2(`repet') partition(`partition') scorename(`scorename') `kappa' ickappa(`ickappa') calcmethod(`calcmethod')
+ *di "{hline}"
+ di
+}
+
+if "`kgv'" != "" {
+ kgv `scorename', categ(`kgv') `kgvboxplots' `kgvgroupboxplots'
+ *di "{hline}"
+ di
+}
+
+if "`conc'" != "" {
+ conc `scorename', comp(`conc') tconc(`tconc')
+ *di "{hline}"
+}
+end
diff --git a/Modules/ado/personal/v/valid.dlg b/Modules/ado/personal/v/valid.dlg
new file mode 100644
index 0000000..48f9654
--- /dev/null
+++ b/Modules/ado/personal/v/valid.dlg
@@ -0,0 +1,426 @@
+/*
+ valid.dlg
+*/
+
+VERSION 12.1
+
+POSITION . . 590 280
+
+DIALOG main, label("Validation") tabtitle("General")
+BEGIN
+ TEXT tx_var 10 10 250 ., ///
+ label("Items used for calculating score")
+ VARLIST vl_var @ +20 280 ., ///
+ label("Variables")
+
+ TEXT tx_n 10 +28 200 ., ///
+ label("Number of items")
+
+ EDIT ed_n @ +20 40 ., ///
+ label("number") ///
+ numonly
+
+ TEXT tx_score 110 58 180 ., ///
+ label("Name of the dimension (optional)")
+ EDIT ed_score 130 +20 100 ., ///
+ option(scorename) ///
+
+ BUTTON bt_add 260 75 32 22, ///
+ label("Add") ///
+ onpush(script az) ///
+
+ GROUPBOX gb_1 5 120 284 140,
+
+ TEXT tx_v 10 +10 100 ., ///
+ label("Items used")
+ VARLIST ed_v @ +20 250 ., ///
+ label("Items used")
+
+ TEXT tx_p @ +20 100 ., ///
+ label("Partition")
+
+ EDIT ed_p @ +20 150 ., ///
+ label("Partition") ///
+ option(partition) ///
+ tooltip("Defines the number of items in each dimension")
+ TEXT tx_s @ +20 . ., ///
+ label("Names of the dimensions (optional)")
+ EDIT ed_s @ +20 150 ., ///
+ label("Names of the dimensions") ///
+ option(scorename)
+
+
+ GROUPBOX gb_calc 330 13 245 90, ///
+ label("Calculation of scores")
+
+ RADIO rb_mean +10 +20 100 ., first label("Mean") ///
+ default(1)
+
+
+ RADIO rb_sum @ +20 100 ., label("Sum")
+
+
+ RADIO rb_stand @ +20 140 ., last label("Standardized scores") ///
+ tooltip("Set score from 0 to 100")
+
+ GROUPBOX gb_opt 330 120 245 140, ///
+ label("Options")
+
+ CHECKBOX ck_imp +10 +20 -20 ., ///
+ option(imp) ///
+ label("Imputing missing data") ///
+ onclickon(main.ck_nor.enable) ///
+ onclickoff(main.ck_nor.disable) ///
+ default(1)
+
+ CHECKBOX ck_nor +145 @ -20 ., ///
+ option(noround) ///
+ label("Do not round") ///
+ tooltip("Do not round imputed values")
+
+ CHECKBOX ck_desc 340 +28 -20 ., ///
+ option(descitems) ///
+ label("Description of items") ///
+ default(0)
+
+ CHECKBOX ck_graphs 340 +28 -20 ., ///
+ option(graphs) ///
+ label("Display graphs") ///
+ default(0) ///
+ tooltip("Display histogram of items, biplot of dimensions and biplot of items")
+
+ /*
+ CHECKBOX ck_cfa 340 +28 -20 ., ///
+ option(cfa) ///
+ label("Confirmatory factor analysis") ///
+ default(1)
+
+
+ CHECKBOX ck_conv @ +28 +10 ., ///
+ option(conv_div) ///
+ label("Convergent/discriminant validity") ///
+ default(1)
+ */
+
+END
+
+
+DIALOG cfa, tabtitle("Confirmatory factor analysis")
+BEGIN
+
+ CHECKBOX ck_cfa 10 10 200 ., label("Display confirmatory factor analysis") ///
+ option(cfa) ///
+ onclickon(script cfa_ck_cfa_on) ///
+ onclickoff(script cfa_ck_cfa_off)
+
+ GROUPBOX gb_cfa 10 +30 220 90 , ///
+ label("Estimation method:")
+
+ RADIO rb_ml +10 +24 110 ., first label("Maximum likelihood") ///
+ default(1)
+
+ RADIO rb_mlmv @ +20 200 ., label("Maximum likelihood with missing values")
+
+ RADIO rb_adf @ +20 140 ., last label("Asymptotic distribution free")
+
+
+ CHECKBOX ck_stand 14 +34 140 ., label("Standardize coefficients") ///
+ option(cfastand)
+
+END
+
+
+DIALOG conv, tabtitle("Convergent/divergent validity")
+BEGIN
+
+ CHECKBOX ck_conv_div 10 10 220 ., ///
+ label("Display convergent/divergent validity") ///
+ option(convdiv) ///
+ onclickon(script conv_ck_conv_on) ///
+ onclickoff(script conv_ck_conv_off)
+
+ TEXT tx_conv1 10 +26 220 ., ///
+ label("Correlations between item and its own score")
+ TEXT tx_conv2 @ +17 @ ., ///
+ label("below this value will be highlighted")
+ EDIT ed_conv 250 42 35 ., ///
+ default(0.4) ///
+ option(tconvdiv) ///
+ numonly
+
+ CHECKBOX ck_conv 10 +42 170 ., ///
+ option(convdivboxplots) ///
+ label("Display boxplots of correlations") ///
+ default(1)
+
+END
+
+
+DIALOG rel, tabtitle("Reliability")
+BEGIN
+
+ TEXT tx_rel_a 10 10 350 ., ///
+ label("Cronbach's alpha below this value will be highlighted")
+ EDIT ed_rel_a 320 @ 35 ., ///
+ default(0.7) ///
+ option(alpha) ///
+ numonly
+
+ TEXT tx_rel_d 10 +30 350 ., ///
+ label("Ferguson's delta below this value will be highlighted")
+ EDIT ed_rel_d 320 @ 35 ., ///
+ default(0.9) ///
+ option(delta) ///
+ numonly
+
+ TEXT tx_rel_H 10 +30 380 ., ///
+ label("Loevinger's H coefficient below this value will be highlighted")
+ EDIT ed_rel_H 320 @ 35 ., ///
+ default(0.3) ///
+ option(h) ///
+ numonly
+
+ TEXT tx_rel_h 10 +30 380 ., ///
+ label("Loevinger's Hj coefficient below this value will be highlighted")
+ EDIT ed_rel_h 320 @ 35 ., ///
+ default(0.3) ///
+ option(hjmin) ///
+ numonly
+
+END
+
+
+
+DIALOG rep, tabtitle("Reproducibility")
+BEGIN
+
+ TEXT tx_rep 10 10 250 ., ///
+ label("Items used for calculating scores (time 2)")
+ VARLIST vl_rep @ +20 @ ., ///
+ option(repet) ///
+ label("Items time 2")
+
+ CHECKBOX ck_kappa @ +35 100 ., ///
+ label("Kappa statistic") ///
+ option(kappa) ///
+ onclickon(script rep_ck_kappa_on) ///
+ onclickoff(script rep_ck_kappa_off)
+
+ CHECKBOX ck_ickappa @ +25 280 ., ///
+ label("Confidence interval for kappa") ///
+ onclickon(script rep_ck_ickappa_on) ///
+ onclickoff(script rep_ck_ickappa_off)
+
+ TEXT tx_boot @ +25 220 ., ///
+ label("Number of bootstrap replications to estimate")
+
+ TEXT tx_boot2 @ +15 220 ., ///
+ label("confidence interval (if items are polytomous):")
+
+ SPINNER sp_ickappa +220 -7 45 ., ///
+ label("Number of bootstrap replications") min(1) max(1000) ///
+ default(20) ///
+ option(ickappa)
+
+
+END
+
+
+DIALOG kgv, tabtitle("Known-groups validity")
+BEGIN
+ TEXT tx_kgv 10 10 250 ., ///
+ label("Select qualitative variables for known-groups validity")
+ VARLIST vl_kgv @ +28 250 ., ///
+ option(kgv) ///
+ label("kgv")
+
+ CHECKBOX ck_kgv @ +25 150 ., ///
+ label("Display boxplots") ///
+ option(kgvboxplots) ///
+ default(0) ///
+ onclickon(kgv.ck_kgv_group.enable) ///
+ onclickoff(kgv.ck_kgv_group.disable)
+
+ CHECKBOX ck_kgv_group @ +25 190 ., ///
+ label("Group boxplots in one graph") ///
+ option(kgvgroupboxplots) ///
+ default(0)
+
+END
+
+
+DIALOG conc, tabtitle("Concurrent validity")
+BEGIN
+ TEXT tx_conc 10 10 186 ., ///
+ label("Select scores from other scales")
+ VARLIST vl_conc @ +28 250 ., ///
+ option(conc) ///
+ label("conc")
+
+ TEXT tx_t_conc @ +30 350 ., ///
+ label("Correlations above this value will be highlighted (absolute value)")
+
+ EDIT ed_t_conc 320 @ 30 ., ///
+ default(0.4) ///
+ option(tconc) ///
+ numonly
+
+END
+
+
+PROGRAM az
+BEGIN
+ main.ed_score.withvalue main.ed_s.append "@ "
+ main.vl_var.withvalue main.vl_v.append "@ "
+ main.ed_n.withvalue main.ed_p.append "@ "
+
+ main.vl_var.setvalue ""
+ main.ed_n.setvalue ""
+ main.ed_score.setvalue ""
+END
+
+
+
+
+SCRIPT rep_ck_kappa_on
+BEGIN
+ rep.ck_ickappa.enable
+END
+
+SCRIPT rep_ck_kappa_off
+BEGIN
+ rep.ck_ickappa.disable
+ rep.sp_ickappa.disable
+ rep.ck_ickappa.setoff
+END
+
+SCRIPT rep_ck_ickappa_on
+BEGIN
+ rep.sp_ickappa.enable
+ rep.tx_boot.enable
+ rep.tx_boot2.enable
+END
+
+SCRIPT rep_ck_ickappa_off
+BEGIN
+ rep.sp_ickappa.disable
+ rep.sp_ickappa.setdefault 0
+ rep.tx_boot.disable
+ rep.tx_boot2.disable
+END
+
+SCRIPT cfa_ck_cfa_on
+BEGIN
+ cfa.gb_cfa.enable
+ cfa.rb_ml.enable
+ cfa.rb_mlmv.enable
+ cfa.rb_adf.enable
+ cfa.ck_stand.enable
+END
+
+SCRIPT cfa_ck_cfa_off
+BEGIN
+ cfa.gb_cfa.disable
+ cfa.rb_ml.disable
+ cfa.rb_mlmv.disable
+ cfa.rb_adf.disable
+ cfa.ck_stand.disable
+END
+
+SCRIPT conv_ck_conv_on
+BEGIN
+ conv.tx_conv1.enable
+ conv.tx_conv2.enable
+ conv.ed_conv.enable
+ conv.ck_conv.enable
+END
+
+SCRIPT conv_ck_conv_off
+BEGIN
+ conv.tx_conv1.disable
+ conv.tx_conv2.disable
+ conv.ed_conv.disable
+ conv.ck_conv.disable
+END
+
+OK ok1, label("OK")
+CANCEL can1, label("Cancel")
+SUBMIT sub1, label("Submit")
+HELP hlp1, view("help valid")
+RESET res1
+COPY copy1
+
+PROGRAM command
+BEGIN
+ put "valid "
+ require main.ed_v
+ put main.ed_v
+ require main.ed_p
+
+ beginoptions
+ optionarg main.ed_p
+ optionarg main.ed_s
+ option main.ck_imp
+ option main.ck_nor
+ option main.ck_desc
+ option main.ck_graphs
+
+ if main.rb_mean{
+ put " calcmethod("
+ put "mean"
+ put ")"
+ }
+
+ if main.rb_sum{
+ put " calcmethod("
+ put "sum"
+ put ")"
+ }
+
+ if main.rb_stand{
+ put " calcmethod("
+ put "stand"
+ put ")"
+ }
+
+ option cfa.ck_cfa
+
+ if cfa.rb_ml{
+ put " cfamethod("
+ put "ml"
+ put ")"
+ }
+
+ if cfa.rb_mlmv{
+ put " cfamethod("
+ put "mlmv"
+ put ")"
+ }
+
+ if cfa.rb_adf{
+ put " cfamethod("
+ put "adf"
+ put ")"
+ }
+
+ option cfa.ck_stand
+ option conv.ck_conv_div
+ optionarg conv.ed_conv
+ option conv.ck_conv
+ optionarg rel.ed_rel_a
+ optionarg rel.ed_rel_d
+ optionarg rel.ed_rel_H
+ optionarg rel.ed_rel_h
+ optionarg rep.vl_rep
+ option rep.ck_kappa
+ optionarg rep.sp_ickappa
+ optionarg kgv.vl_kgv
+ option kgv.ck_kgv
+ option kgv.ck_kgv_group
+ optionarg conc.vl_conc
+ optionarg conc.ed_t_conc
+
+ endoptions
+
+
+END
diff --git a/Modules/ado/personal/v/valid.hlp b/Modules/ado/personal/v/valid.hlp
new file mode 100644
index 0000000..4a16d35
--- /dev/null
+++ b/Modules/ado/personal/v/valid.hlp
@@ -0,0 +1,125 @@
+{smcl}
+{* 2013}{...}
+{hline}
+help for {hi:valid}
+{hline}
+
+{title:Syntax}
+
+{p 8 14 2}{cmd:valid} {it:varlist}, {bf:partition}({it:numlist}) [{it:options}]
+
+{p 4 4 2}{it:varlist} contains the variables (items) used to calculate the scores. The first items of {it:varlist} compose the first dimension, the following items define the second dimension, and so on.
+
+{p 4 4 2}{cmd:partition} permits to define in {it:numlist} the number of items in each dimension.
+
+
+{synoptset 20 tabbed}{...}
+{synopthdr}
+{synoptline}
+{syntab:Options}
+{synopt : {opt sco:rename(string)}}define the names of the dimensions{p_end}
+{synopt : {opt imp:ute}}impute missing item responses{p_end}
+{synopt : {help valid##impute_options:{it:impute_options}}}options for imputation of missing data {p_end}
+{synopt : {opt calc:method(method)}}define how scores are calculated{p_end}
+{synopt : {opt desc:items}}display a description of items and dimensions{p_end}
+{synopt : {opt graph:s}}display graphs for items description{p_end}
+{synopt : {opt cfa}}assess structural validity by performing a confirmatory factor analysis{p_end}
+{synopt : {help valid##cfa_options:{it:cfa_options}}}options for confirmatory factor analysis{p_end}
+{synopt : {opt conv:div}}assess convergent and divergent validity assessment{p_end}
+{synopt : {help valid##conv_div_options:{it:conv_div_options}}}options for convergent and divergent validity{p_end}
+{synopt : {help valid##reliability_options:{it:reliability_options}}}options for reliability assessment{p_end}
+{synopt : {opt rep:et(varlist)}}assess reproducibility of scores and items{p_end}
+{synopt : {help valid##repet_options:{it:repet_options}}}options for reproducibility{p_end}
+{synopt : {opt kgv(varlist)}}assess known-groups validity by using qualitative variable(s){p_end}
+{synopt : {help valid##kgv_options:{it:kgv_options}}}options for known-groups validity assessment{p_end}
+{synopt : {opt conc(varlist)}}assess concurrent validity{p_end}
+{synopt : {help valid##conc_options:{it:conc_options}}}options for concurrent validity assessment{p_end}
+
+{p2colreset}{...}
+
+
+{title:Description}
+
+{phang}{cmd:valid} assesses validity and reliability of a multidimensional scale. Specifically it evaluates
+structural validity, convergent and divergent validity, reproducibility, known-groups validity, internal consistency, scalability and sensitivity.
+
+{marker options}{...}
+{title:Options}
+
+{dlgtab:Options}
+
+{phang}{opt sco:rename(string)} allows defining the names of the dimensions. If the option is not used then dimensions are named {it:Dim1}, {it:Dim2},...
+
+{phang}{opt imp:ute} imputes missing items responses with Person Mean Substitution method applied in each dimension. Missing data are imputed only if the number of
+missing values in the dimension is less than half the number of items in the dimension.
+
+{marker impute_options}{...}
+{phang}{it:impute_options} allow specifying options for imputation of missing. By default, imputed values are rounded to the nearest whole number. If {opt nor:ound} is precised then imputed values
+are not rounded. If {opt impute} is absent then {opt noround} is ignored.
+
+{phang}{opt calc:method(method)} defines the method used for calculating scores. {it:method} may be either {bf:mean} (default), {bf:sum} or {bf:stand}(set scores from 0 to 100).
+
+{phang}{opt desc:items} displays a description of items. This option gives missing data rate per item and distribution of item responses. It also gives Cronbach's alpha for each item, which is the alpha statistic
+calculated by removing the item from the dimension. Moreover, the option computes Loevinger's Hj coefficients and the number of non significant Hjk. See {help loevh} for details about Loevinger's coefficients.
+
+{phang}{opt graph:s} displays graphs for items and dimensions description. It provides histograms of scores, a biplot of dimensions and a biplot of items.
+
+{phang}{opt cfa} performs a confirmatory factor analysis with Stata's {help sem} command. It displays estimations of coefficients and several goodness-of-fit indices.
+
+{marker cfa_options}{...}
+{phang}{it:cfa_options} allow specifying options for confirmatory factor analysis. {opt cfam:ethod}({it:method}) specifies the method of estimation of parameters. {it:method} may be either {bf:ml} (maximum
+likelihood), {bf:mlmv} ({bf:ml} with missing values) or {bf:adf} (asymptotic distribution free). The {opt cfas:tand} option displays standardized coefficients.
+
+{phang}{opt conv:div} assesses convergent and divergent validity. The option displays the matrix of correlations between items and dimensions.
+
+{marker convdiv_options}{...}
+{phang}{it:conv_div_options} allow specifying options for convergent and divergent validity. {opt tconv:div(#)} defines a threshold for highlighting some values. # is a real number between 0 and 1 which is equal to 0.4 by
+default. Correlations between items and their own score are printed
+in red if it is less than #. Moreover, if an item is less correlated with its own dimension than with another one the correlation is printed
+in red. The {opt convdivb:oxplots} option displays boxplots for assessing convergent and divergent validity. The boxes represent the correlations between the items of a given dimension and all dimensions. So the box of correlations between items of a given dimension and its score must be higher than other
+boxes. There is as many boxplots (graphs) as dimensions.
+
+{marker reliability_options}{...}
+{phang}{it:reliability_options} allow defining the thresholds for reliability indices. {opt a:lpha(#)} defines a threshold for Cronbach's alpha (see {help alpha}). # is a real number between 0 and 1 which is equal to 0.7
+by default. Cronbach's alpha coefficients less than # are printed in red. {opt d:elta(#)} defines a threshold for Ferguson's delta coefficient (see {help delta}). # is a real number between 0 and 1 which is equal to 0.9
+by default. Ferguson's delta coefficients less than # are printed in red. {opt h(#)} defines a threshold for Loevinger's H coefficient (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. Loevinger's H coefficients less than # are printed in red. {opt hj:min(#)}
+defines a threshold for Loevinger's Hj coefficients. The displayed value is the minimum Hj coefficient for a item in the dimension. (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. If the minimum Loevinger's Hj coefficient is less than # then it is printed in red and the corresponding item is displayed.
+
+{phang}{opt rep:et(varlist)} assesses reproducibility of scores by precising in {it:varlist} the variables corresponding to responses at time 2. Scores are calculated according to the {opt partition()} option. Intraclass
+Correlation Coefficients (ICC) for scores and their 95% confidence interval are computed with Stata's {help icc} command.
+
+{marker repet_options}{...}
+{phang}{it:repet_options} display information about reproducibility of items. The {opt kap:pa} option computes kappa statistic for items with Stata's {help kap} command. The {opt ickap:pa(#)} calculates
+confidence intervals for
+kappa statistics. # is the number of replications for bootstrap used to estimate confidence intervals if items are polytomous. See {help kapci} for more details about calculation of confidence intervals for kappa's
+coefficients. If the {opt kappa} option is absent then {opt ickappa(#)} is ignored.
+
+{phang}{opt kgv(varlist)} assesses known-groups validity according to the grouping variables precised in {it:varlist}.
+
+{marker kgv_options}{...}
+{phang}{it:kgv_options} allow to display graphs for known-groups validity. The {opt kgvb:oxplots} option draws boxplots of scores split into groups of individuals. The {opt kgvg:roupboxplots} option groups
+all boxplots in one graph. If {opt kgvboxplots} is absent then {opt kgvboxplotsgroup} is ignored.
+
+{phang}{opt conc(varlist)} assesses concurrent validity with variables precised in {it:varlist}. These variables are scores from one or several other scales.
+
+{marker conc_options}{...}
+{phang}{it:conc_options} allow to specify options for concurrent validity. The {opt tc:onc(#)} option defines a threshold for correlations between scores and those of other scales in {it:varlist}. Correlation
+coefficients greater than # are displayed in bold.
+
+
+{marker examples}{...}
+{title:Examples}
+
+{phang2}{cmd:. valid item1-item20, part(5 4 6 5)}{p_end}
+
+{phang2}{cmd:. valid item1-item20, part(5 4 6 5) imp graphs cfa cfastand convdiv convdivboxplots kgv(factor_variable) kgvboxplots conc(scoreA-scoreD)}{p_end}
+
+{phang2}{cmd:. valid item1-item20, part(5 4 6 5) imp rep(item1bis-item20bis) kappa}{p_end}
+
+
+{marker alsosee}{...}
+{title:Also see}
+
+{p 4 13 2}help for {help alpha}, {help delta}, {help loevh}, {help icc}, {help kapci}.{p_end}
diff --git a/Modules/ado/personal/v/validscale.ado b/Modules/ado/personal/v/validscale.ado
new file mode 100644
index 0000000..6172ac4
--- /dev/null
+++ b/Modules/ado/personal/v/validscale.ado
@@ -0,0 +1,2981 @@
+*! Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine
+*************************************************************************************************************
+* Stata program : validscale
+* Assess validity and reliability of a multidimensional measurement scale using CTT methods
+
+* Required modules :
+* delta
+* loevh
+* kapci
+* mi_twoway
+* detect
+* imputeitems
+* lstrfun
+* svmat2
+
+* Version 1.1 (September 3, 2018) /*updated the dialog box for Stata 15, fixed a bug with cfarmsea, cfacfi and cfacovs, fixed a bug with descitems when the first observation contained missing data*/
+* Version 1.2 August 13, 2019 /* filessave and dirsave options */
+* Version 1.2.1 August 28, 2019 /* cfa is now a wrapper for sem command; that means that most options of sem_estimation_options should work for cfa */
+* Version 1.2.2 February 17, 2020 /* check if svmat2 is installed */
+
+
+
+*************************************************************************************************************
+
+program define validscale, rclass
+version 12.0
+syntax varlist [if], PARTition(numlist integer >0) [HTML(string) CATegories(numlist) SCOREName(string) scores(varlist) IMPute(string) NORound COMPScore(string) DESCitems GRAPHs cfa CFAMethod(string) cfasb CFAStand CFACov(string) CFARmsea(real -999) CFACFi(real -999) CFAOR CFANOCOVDim CONVdiv TCONVdiv(real 0.4) CONVDIVBoxplots Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3) REPet(varlist) scores2(varlist) KAPpa ICKAPpa(integer 0) kgv(varlist) KGVBoxplots KGVGroupboxplots conc(varlist) tconc(real 0.4) DIRsave(string) FILESsave *]
+preserve
+
+
+foreach c in delta loevh mi_twoway detect imputeitems lstrfun{
+ capture which "`c'"
+ if _rc qui ssc install "`c'"
+}
+
+capture which kapci
+if _rc qui net install st0076, from(http://www.stata-journal.com/software/sj4-4/)
+
+capture which svmat2
+if _rc qui net install dm79, from(http://www.stata.com/stb/stb56)
+
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+global html
+global dirsave
+global filessave
+
+if "`filessave'" != "" {
+ global filessave = "`filessave'"
+}
+
+if "`dirsave'" != "" {
+ global dirsave = "`dirsave'"
+}
+else {
+ global dirsave "`c(pwd)'"
+}
+
+if "`html'" != "" {
+ global html = "`html'"
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local xsize=6
+ local ysize=4
+ di in gr ""
+ di "
"
+ di ""
+}
+
+if "`categories'" == "" {
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ local m `mi' `ma'
+ local categories `categories' `m'
+ }
+}
+
+global categories = "`categories'"
+global compscore = "`compscore'"
+if "$compscore" == "" global compscore = "mean"
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+if "`repet'" != "" {
+ local b:word count `repet'
+ if `nbvars' != `b' {
+ di in red "The number of items in varlist is different from the number of items in repet"
+ exit 119
+ }
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+local P:word count `partition'
+local S:word count `scorename'
+
+if "`scores'" != "" & "`scorename'" != "" {
+ di in red "scorenames() and scores() cannot be used together"
+ exit 119
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ foreach sco in `scorename' {
+ capture confirm variable `sco', exact
+ if !_rc {
+ di in red "`sco' already defined. You must choose names that do not already exist or use the scores() option if the scores are already defined."
+ exit 119
+ }
+ tokenize `scorename'
+ local g = 0
+ forvalues i = 1/`S' {
+ if "`sco'" == "``i''" {
+ local `++g'
+ }
+ }
+ if `g' > 1 {
+ di in red "2 or more dimensions have the same name"
+ exit 119
+ }
+ }
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') categories(`categories')
+ global exist = 0
+ global scorename = "`scorename'"
+}
+
+else if "`scorename'" == "" & "`scores'" == ""{
+
+ local name
+ local nname
+
+ forvalues i = 1/`P' {
+
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+
+ local scorename = "`nname'"
+ global scorename = "`nname'"
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') categories(`categories')
+ global exist = 0
+}
+
+else if "`scores'" != "" {
+ local P:word count `partition'
+ local S2:word count `scores'
+ if `P'!=`S2' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ else {
+ global scorename = "`scores'"
+ local scorename = "`scores'"
+ global exist = 1
+
+ }
+
+}
+
+local nbm : word count $categories
+if `nbm' !=2 &`nbm' !=`P'*2 &`nbm' !=`nbvars'*2 {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+}
+
+if `nbm' == 2{
+ tokenize $categories
+ foreach v in `varlist' {
+ tempvar min
+ tempvar max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ if `min' < `1' {
+ di in red "error in option categories() : some responses have smaller values than the minimum value in categories()"
+ exit 119
+ }
+ if `max' > `2' {
+ di in red "error in option categories() : some responses have greater values than the maximum value in categories()"
+ exit 119
+ }
+ }
+}
+
+if `nbm' == `nbvars'*2 {
+ local i = 1
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ tokenize $categories
+ if `mi' < ``i'' {
+ di in red "error in option categories() : some responses have values less than the minimum value specified for the variable in categories()"
+ exit 119
+ }
+ local `++i'
+ tokenize $categories
+ if `ma' > ``i'' {
+ di in red "error in option categories() : some responses have values greater than the maximum value specified for the variable in categories()"
+ exit 119
+ }
+ local `++i'
+ }
+}
+
+if `nbm' == `P'*2 {
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ //local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+ forvalues w = `y'/`s' {
+ tokenize $categories
+ tempvar min max
+ egen `min' = min(`var`w'')
+ egen `max' = max(`var`w'')
+ local mi = `min'
+ local ma = `max'
+ if `mi' < ``i'' {
+ di in red "error in option categories() : some responses have values less than the minimum value specified"
+ exit 119
+ }
+ local j = `i'+1
+ tokenize $categories
+ if `ma' > ``j'' {
+ di in red "error in option categories() : some responses have values greater than the maximum value specified"
+ exit 119
+ }
+ }
+ local i = `i'+2
+ local y = `s'+1
+ }
+}
+
+if "`cfa'" != "" {
+ if "`cfacov'" != "" {
+ if !strpos("`cfacov'", "*") {
+ di "error in cfacov() option : you must enter covariances between errors as follows: item3*item5 item7*item8 ... "
+ exit 119
+ }
+ local v = subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ }
+
+}
+
+if "`kgv'" !="" {
+ foreach k in `kgv' {
+ capture confirm variable `k'
+ if _rc!=0 {
+ di in red "`k' does not exist"
+ exit 119
+ }
+ }
+}
+
+if "`conc'" !="" {
+ foreach c in `conc' {
+ capture confirm variable `c'
+ if _rc!=0 {
+ di in red "`c' does not exist"
+ exit 119
+ }
+ }
+}
+
+di as result "Items used to compute the scores"
+di
+
+local i = 1
+local j = 1
+local y = 1
+foreach p in `partition' {
+ tokenize `scorename'
+ di "{bf:``i''} : " _c
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ forvalues z = `y'/`s' {
+ di "{text:`var`z'' }" _c
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+}
+
+di
+di as result "Number of observations: " _c
+di as text _N
+
+qui destring _all, replace
+di
+
+if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+}
+
+
+if "`graphs'" != "" {
+ graphs `varlist', partition(`partition')
+}
+
+
+if "`repet'" != "" {
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+}
+
+if "`impute'" != "" {
+ if "`impute'" != "pms" & "`impute'" !="mi" {
+ di in red "option impute() incorrectly specified. You must specify {hi:pms} or {hi:mi}."
+ error 100
+ }
+ if "`impute'" == "pms" {
+ pms `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (PMS imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ pms `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+ if "`impute'" == "mi" {
+ mitw `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (mi two-way imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ mitw `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+}
+
+rel `varlist', scorename(`scorename') partition(`partition') alpha(`alpha') delta(`delta') h(`h') hjmin(`hjmin') categories(`categories')
+di
+
+if "`convdiv'" != "" {
+ convdiv `varlist', partition(`partition') tconvdiv(`tconvdiv') `convdivboxplots'
+ di
+}
+
+if "`cfa'" != "" {
+ cfa `varlist', partition(`partition') cfamethod(`cfamethod') `cfasb' `cfastand' cfacov(`cfacov') cfarmsea(`cfarmsea') cfacfi(`cfacfi') `cfaor' `cfanocovdim' `options'
+ di
+}
+
+if "`repet'" != "" | "`scores2'" != "" {
+ global scores2 = "`scores2'"
+ repet `varlist', t2(`repet') partition(`partition') `kappa' ickappa(`ickappa')
+ di
+}
+
+if "`kgv'" != "" {
+ kgv `scorename', categ(`kgv') `kgvboxplots' `kgvgroupboxplots'
+ di
+}
+
+if "`conc'" != "" {
+ conc `scorename', comp(`conc') tconc(`tconc')
+}
+
+
+//capture restore, not
+end
+
+
+/* pms */
+
+capture program drop pms
+program pms
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+tokenize `varlist'
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ local n : word count `liste'
+ if mod(`n',2)!=0 local max = floor(`n'/2)
+ else local max = `n'/2-1
+
+ if "`noround'" != "" {
+ qui imputeitems `liste', method(pms) max(`max') noround
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+ else {
+ qui imputeitems `liste', method(pms) max(`max')
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+end
+
+
+/* mitw */
+
+capture program drop mitw
+program mitw
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ qui mi_twoway `liste', scorename(scoretmp) add(1) style(wide) clear
+
+ foreach var of varlist `liste' {
+ qui replace `var' = _1_`var'
+ if "`noround'" == "" {
+ qui replace `var' = round(`var')
+ }
+ /*if `var' > `maxm' {
+ qui replace `var' = `maxm'
+ }
+ if `var' < `minm' {
+ qui replace `var' = `minm'
+ }*/
+ qui drop _1_`var'
+ capture drop scoretmp
+ capture drop _1_scoretmp
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+//capture drop _mi_miss
+qui mi unset
+end
+
+
+/* calcscore */
+
+capture program drop calcscore
+program calcscore,rclass
+syntax varlist, PARTition(numlist integer >0) [categories(numlist) COMPscore(string) SCOrename(string)]
+
+local P:word count `partition'
+local S:word count `scorename'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+}
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ tempvar nonmiss
+ qui egen `nonmiss' = rownonmiss(`liste')
+
+ tokenize `scorename'
+ local sc = "``i''"
+
+ if "`compscore'" == "" local compscore = "mean"
+
+ if "`compscore'" != "mean" & "`compscore'" != "sum" & "`compscore'" != "stand" {
+ di in red "option compscore incorrectly specified (choose among mean, sum and stand)"
+ error 198
+ }
+
+ if "`compscore'" == "sum" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`x'
+
+ }
+
+ else if "`compscore'" == "stand" {
+
+ local nbm:word count `categories'
+
+ local nbl:word count `liste'
+ tokenize `categories'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+
+ }
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+ }
+ }
+
+ else {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`nonmiss'
+ qui replace `sc' = (`sc'-`min')/(`max'-`min')*100
+ }
+
+ else {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ }
+
+local `i++'
+local y = `s'+1
+}
+
+end
+
+
+
+/* rel */
+
+capture program drop rel
+program rel,rclass
+syntax varlist, PARTition(numlist integer >0) [CATegories(numlist) SCOrename(string) Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3)]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+di as result "{hline 105}"
+di "{bf:Reliability}"
+di as result "{hline 105}"
+di
+
+local y = 1
+local nbitems = 0
+matrix aa = J(`P',4,.)
+
+foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+matrix d = J(`nbitems',2,.)
+
+local i = 1
+local b = 1
+foreach x in `partition' {
+
+ tokenize `scorename'
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ capture alpha `liste', asi item std
+ local al`i' = r(alpha)
+
+ capture qui loevh `liste', pairwise
+ local h`i' = r(loevH)
+ matrix c = r(loevHj)
+ matrix ct = c'
+
+
+ local lister = ""
+ forvalues w = `y'/`s' {
+ tempvar z
+ qui gen `z' = round(`var`w'')
+ local lister `lister' `z'
+ }
+
+ tempvar nbmiss
+ local nbl : word count `lister'
+ egen `nbmiss' = rowmiss(`lister')
+ qui count if `nbmiss'<`nbl'
+ local n`i' = r(N)
+
+
+ // delta
+
+ if ${exist} == 0 & "$compscore" == "sum" {
+
+ local nbm:word count `categories'
+ tokenize `categories'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+ }
+
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+
+ }
+ }
+
+ else {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ capture delta `lister', min(`min') max(`max')
+ local delt`i' = r(delta)
+
+ }
+
+ else local delt`i' = .
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',1] = ct[`k',1]
+ matrix d[`j',2] = `i'
+ }
+
+ matrix aa [`i',1] = `al`i''
+ matrix aa [`i',2] = `delt`i''
+ matrix aa [`i',3] = `h`i''
+
+ local `i++'
+ local y = `s'+1
+
+ local b = `b'+2
+}
+
+matrix rownames d = `varlist'
+local i = 1
+local y = 1
+
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ matrix C = d[`y'..`s',1.]
+ local min`i' = C[1,1]
+ local n : rownames C
+ tokenize `n'
+ local t`i' = "`1'"
+ forvalues j = 1/`x' {
+ local t = "``j''"
+ if C[`j',1] <= `min`i'' {
+ local min`i' = C[`j',1]
+ local t`i' = "``j''"
+ local itmin`i' = "``j''"
+ }
+ }
+ matrix aa [`i',4] = `min`i''
+ local `i++'
+ local y = `s'+1
+}
+
+matrix colnames aa = "alpha" "delta" "H" "Hj_min"
+
+if "`scorename'"=="" {
+ local i = 1
+ local y = 1
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local maxlen = 0
+foreach sco in `scorename' {
+ local w = length("`sco'")
+ if `w' > `maxlen' local maxlen = `w'
+}
+
+local i = 1
+local j = 1
+local y = 1
+local col = `maxlen'+8
+
+di _col(`col') "{bf:n}" _c
+local col = `col'+6
+di _col(`col') "{bf:alpha}" _c
+local col = `col'+10
+di _col(`col') "{bf:delta}" _c
+local col = `col'+14
+di _col(`col') "{bf:H}" _c
+local col = `col'+5
+di _col(`col') "{bf:Hj_min}"
+
+foreach s in `scorename' {
+ di in blue "{bf:`s'}" _c
+ local col = `maxlen'+3
+
+ local n : di %6.0f `n`i''
+
+ di in blue _col(`col') "{text:`n'}" _c
+ local col = `col'+10
+
+ local a : di %6.2f `al`i''
+ if `a' < `alpha' {
+ di _col(`col') "{error:`a'} " _c
+ }
+ else di _col(`col') "{text:`a'}" _c
+
+ local col = `col'+10
+ local d : di %6.2f `delt`i''
+ if `d' < `delta' {
+ di _col(`col') "{error:`d'} " _c
+ }
+ else di _col(`col') "{text:`d'}" _c
+
+ local col = `col'+10
+ local ht : di %6.2f `h`i''
+ if `ht' < `h' {
+ di _col(`col') "{error:`ht'} " _c
+ }
+ else di _col(`col') "{text:`ht'}" _c
+
+ local col = `col'+8
+ local m : di %8.2f `min`i''
+ if `m' < `hjmin' {
+ di _col(`col') "{error:`m'} " _c
+ di "{text:(item `itmin`i'')}" _c
+ }
+ else di _col(`col') "{text:`m'}" _c
+
+ di
+ local `++i'
+}
+
+end
+
+/* descitems */
+
+capture program drop descitems
+program descitems
+syntax varlist, PARTition(numlist integer >0)
+local i = 1
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+foreach var in `varlist' {
+ qui replace `var' = round(`var')
+}
+
+local lev = ""
+foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ foreach l in `levels' {
+ if strpos("`lev'","`l'") == 0 {
+ local lev `lev' `l'
+ }
+ }
+}
+
+_qsort_index `lev'
+local lev = r(slist1)
+
+local i = 1
+matrix d = J(`nbvars',4,.)
+
+foreach var in `varlist'{
+ qui count if missing(`var')
+ local ct=r(N)
+
+ local tx`i'=`ct'/_N
+ matrix d[`i',1] = `tx`i''
+ local `i++'
+}
+
+matrix rownames d = `varlist'
+matrix colnames d = "missing" "alpha" "Hj"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ qui capture alpha `liste', asi item std
+
+ mat a = r(Alpha)
+ mat at = a'
+
+ qui capture loevh `liste', pairwise pair
+ matrix e = r(loevHj)
+ matrix et = e'
+
+ //matrix ns = r(nbHjkNS)
+ //matrix nst = ns'
+
+
+ matrix pval = r(pvalHjk)
+ forvalues c = 1/`x' {
+ forvalues r = 1/`x' {
+ if pval[`r',`c']>0.05 {
+ local ns`r' = `ns`r''+1
+ }
+ else local ns`r' = `ns`r''+0
+ }
+ }
+
+
+ foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+ }
+ matrix nst = J(`nbitems',1,0)
+ local r = 1
+ forvalues j = `y'/`s'{
+ matrix nst[`j',1]=`ns`r''
+ local `r++'
+ }
+
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',2] = at[`k',1]
+ matrix d[`j',3] = et[`k',1]
+ matrix d[`j',4] = `ns`k''
+
+ }
+ local `i++'
+ local y = `s'+1
+
+ forvalues j = 1/21{
+ local ns`j' = 0
+ }
+}
+
+
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",8)
+ local `++i'
+}
+
+local dec = 10
+local col = `dec'
+
+
+local minm = 999
+local maxm = -999
+foreach mod in $categories {
+ if `mod' < `minm' local minm = `mod'
+ if `mod' > `maxm' local maxm = `mod'
+}
+
+local b = `maxm'-`minm'+1
+
+local i = 1
+local j = 1
+local y = 1
+
+di in blue _col(`dec') "{bf:Missing}" _c
+local col = `col'+11
+di in blue _col(`=`col'+2') "{bf:N}" _c
+
+local col = `col'+9
+di _col(`col') "{bf:Response categories}" _c
+local col = `dec'+18+8*`b'
+di _col(`col') "{bf:Alpha}" _c
+local col = `col'+9
+di _col(`col') "{bf:Loevinger}" _c
+local col = `col'+12
+di _col(`col') "{bf:Number of}"
+
+local col = `dec'-1
+di _col(`col') "{bf:data rate}" _c
+local col = `dec'+18
+
+forvalues m = `minm'/`maxm' {
+ di _col(`=`col'+2') "`m'" _c
+ local col = `col'+8
+}
+
+di as result _col(`col') "- item" _c
+local col = `col'+10
+di as result _col(`col') "Hj coeff" _c
+local col = `col'+12
+di as result _col(`col') "NS Hjk"
+
+local ch = `dec'+18+8*`b'+29
+di "{hline `ch'}"
+
+local i = 1
+foreach x in `varlist' {
+ local varo`i' = "`x'"
+ local `++i'
+}
+
+local y = 1
+foreach p in `partition' {
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ local col = `dec'
+ di "{bf:`var`z''}" _c
+ local t = d[`z',1]
+ local t : di %8.2f `t'*100
+ di _col(`col') "{text:`t'%}" _c
+ qui count if missing(`varo`z'')
+ local m = r(N)
+ local N = _N-`m'
+ local N : di %4.0f `N'
+ local col = `col'+10
+ di _col(`col') "{text:`N'}" _c
+
+ local col = `col'+8
+ forvalues m = `minm'/`maxm' {
+ qui count if round(`varo`z'') == `m'
+ local n = r(N)
+ if `m' == `maxm' & round(`varo`z'')>`maxm' & `varo`z''!=.{
+ local n = `n' + 1
+ }
+ if `m' == `minm' & round(`varo`z'')<`minm' & `varo`z''!=.{
+ local n = `n' + 1
+ }
+ qui count if `varo`z'' != .
+ local d = r(N)
+ local e = `n'/`d'
+ local e : di %4.2f `e'*100
+ if `e' != 0 di _col(`=`col'-1')"{text:`e'%}" _c
+ else di _col(`=`col'-1')"{text: -}" _c
+ local col = `col'+8
+ }
+ local a = d[`z',2]
+ local a : di %4.2f `a'
+ di _col(`=`col'+1') "{text:`a'}" _c
+ local h = d[`z',3]
+ local h : di %5.2f `h'
+ local col = `col'+10
+ di _col(`=`col'+3') "{text:`h'}" _c
+ local ns = d[`z',4]
+ local ns : di %2.0f `ns'
+ local col = `col'+11
+ di _col(`=`col'+7') "{text:`ns'}"
+
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di "{dup `ch':-}"
+}
+end
+
+
+capture program drop graphs
+program graphs
+syntax varlist, PARTition(numlist integer >0)
+
+local P:word count `partition'
+local html = "${html}"
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+if "$compscore" == "stand" local w = 10
+if "$compscore" == "sum" local b = 10
+if "$compscore" == "mean" local w = 0.5
+
+
+
+
+if "`html'"!="" {
+ //set graphics off
+ foreach s in $scorename {
+ qui local saving "saving(`c(tmpdir)'/`html'_`s',replace) nodraw"
+ qui hist `s', name(`s',replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b') `saving'
+ qui graph use `c(tmpdir)'/`html'_`s'.gph
+ qui graph export `c(tmpdir)'/`html'_`s'.png, replace
+ //di ""
+
+ }
+ //set graphics on
+
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_group,replace) nodraw"
+ qui gr combine $scorename, name(group,replace) title("Distribution of scores") `saving'
+ qui graph use `c(tmpdir)'/`html'_group.gph
+ qui graph export `c(tmpdir)'/`html'_group.png, replace
+ //di ""
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_scores,replace) nodraw"
+ qui biplot $scorename, name("Biplot_scores",replace) norow std title("Correlations between scores") xtitle("") ytitle("") `saving'
+ qui graph use `c(tmpdir)'/`html'_scores.gph
+ qui graph export `c(tmpdir)'/`html'_scores.png, replace
+ //di ""
+}
+
+else {
+ set graphics off
+ foreach s in $scorename {
+ qui hist `s', name("`s'",replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b')
+ }
+ set graphics on
+
+ gr combine $scorename, name("Histograms_scores",replace)
+ if ("$filessave"!="") qui graph export ${dirsave}/Histograms_scores.png, replace
+
+ capture biplot $scorename, name("Biplot_scores",replace) norow std title("") xtitle("") ytitle("")
+ if ("$filessave"!="") qui graph export ${dirsave}/Biplot_scores.png, replace
+
+}
+
+
+
+capture biplot `varlist', name("temp",replace) norow std nograph
+
+mat a = r(V)
+
+tempvar a1 a2
+mat colnames a = `a1' `a2'
+svmat a, names(col)
+
+tempvar mina1 mina2 maxa1 maxa2
+egen `mina1' = min(`a1')
+egen `mina2' = min(`a2')
+egen `maxa1' = max(`a1')
+egen `maxa2' = max(`a2')
+local mina1 = `mina1'
+local mina2 = `mina2'
+local maxa1 = `maxa1'+1.4
+local maxa1x = `maxa1'+0.3
+local maxa2 = `maxa2'
+
+local colors = "red blue black green ebblue mint erose orange maroon magenta mint gray teal navy olive sienna"
+local i = 1
+foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+}
+
+local i = 1
+local y = 1
+local c = 1
+local bas = `maxa2'+0.2
+local droite = max(`maxa1',0.2)
+
+foreach x in `partition' {
+ tokenize $scorename
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues j=`y'/`s' {
+ local a = `a1'[`j']
+ local b = `a2'[`j']
+ local call `call' || pcarrowi 0 0 `b' `a' "`var`j''", mlabcolor(`col`i'') color(`col`i'') head
+ }
+ local bas = `bas'-0.2
+ local call `call' text(`bas' `droite' "``i''", size(3) color(`col`i'')) /*`bas' `droite' "``i''", mlabcolor("`r' `g' `b'")*/
+ local `++i'
+ local y = `s'+1
+ local `++c'
+}
+
+
+if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_items,replace) nodraw"
+ qui twoway `call' name("items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) title("Correlations between items") xtitle("") ytitle("") xsize(`xsize') ysize(`ysize') `saving'
+ qui graph use `c(tmpdir)'/`html'_items.gph
+ qui graph export `c(tmpdir)'/`html'_items.png, replace
+ //di ""
+}
+else {
+ qui twoway `call' name("Biplot_items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) xtitle("") ytitle("")
+ if ("$filessave"!="") qui graph export ${dirsave}/Biplot_items.png, replace
+
+}
+
+
+
+end
+
+/* convdiv */
+
+capture program drop convdiv
+program convdiv
+syntax varlist, PARTition(numlist integer >0) [TCONVdiv(real 0.4) convdivboxplots]
+preserve
+
+//qui set autotabgraphs on
+
+
+
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+local P:word count `partition'
+local cptdiv = 0
+local cptconv = 0
+
+if ${exist} != 1 {
+
+ qui detect `varlist', partition(`partition')
+
+ matrix A = r(Corrrestscores)
+ matrix B = r(Corrscores)
+
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ matrix B[`z',`i'] = A[`z',`i']
+ }
+ local `i++'
+ local y = `s'+1
+ }
+
+ matrix colnames B = $scorename
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix}"
+ di "{hline 105}"
+ di
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ /*if "${html}" != "" {
+ di ""
+ di _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di in red _col(`col') "{bf:`t'}" _c
+ //}
+
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{bf:`t'}" _c
+ //}
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ /*if "${html}" != "" {
+ di ""
+ di in red _col(`col') "`t'" _c
+ di ""
+ }*/
+ //else {
+ di in red _col(`col') "`t'" _c
+ //}
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{text:`t'}"_c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{text:`t'}"_c
+ //}
+
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di as text "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+
+}
+
+else if ${exist} == 1 {
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix (without rest-scores)}"
+ di "{hline 105}"
+ di
+
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ qui corr $scorename `varlist'
+ matrix c = r(C)
+ matrix B = c[`=`P'+1'..`nbvars'+`P',1..`P']
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ di in red _col(`col') "{bf:`t'}" _c
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ di _col(`col') "{bf:`t'}" _c
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ di in red _col(`col') "`t'" _c
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ di as text _col(`col') "{text:`t'}"_c
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+}
+
+if "`convdivboxplots'" != "" {
+
+ if "${html}" != "" {
+ local html = "${html}"
+ di "
"
+ di ""
+
+
+ local colors = "red blue green orange maroon magenta ebblue mint erose gray teal navy olive sienna"
+ local i = 1
+ foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+ }
+
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`col`j'') lcolor(`col`j'')) marker(`j', mcolor(`col`j''))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_Conv_div_``h'',replace) nodraw"
+ qui graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black)) `saving'
+ qui graph use `c(tmpdir)'/`html'_Conv_div_``h''.gph
+ qui graph export `c(tmpdir)'/`html'_Conv_div_``h''.png, replace
+
+ di "
"
+
+
+
+ //qui set autotabgraphs on
+ }
+ di "
"
+ di ""
+ }
+
+ else {
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`color') lcolor(`color')) marker(`j', mcolor(`color'))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+ di "ok1"
+ graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black))
+ di "ok2"
+ if ("$filessave"!="") qui graph export ${dirsave}/Conv_div_``h''.png, replace
+ qui set autotabgraphs on
+ }
+ }
+}
+
+
+local t : di %5.3f `tconvdiv'
+local p1 = (`nbvars'-`cptconv')/`nbvars'*100
+local p1 : di %4.1f `p1'
+local p2 = (`nbvars'-`cptdiv')/`nbvars'*100
+local p2 : di %4.1f `p2'
+
+di
+di as result "Convergent validity:" _c
+di as text " `=`nbvars'-`cptconv''/`nbvars' items (`p1'%) have a correlation coefficient with the score of "
+di _col(22) "their own dimension greater than `t'"
+di
+di as result "Divergent validity:" _c
+di as text " `=`nbvars'-`cptdiv''/`nbvars' items (`p2'%) have a correlation coefficient with the score"
+di _col(22) "of their own dimension greater than those computed with other scores."
+
+end
+
+/* cfa */
+
+capture program drop cfa
+program cfa,rclass
+syntax varlist, PARTition(numlist integer >0) [CFAMethod(string) cfasb CFAStand CFACov(string) CFARmsea(real -999) CFACfi(real -999) CFAOR CFANOCOVDim *]
+preserve
+
+if "`cfasb'"!="" & `cfacfi'!=-999 {
+ di in red "You cannot use both cfasb and cfacfi()"
+ exit 119
+}
+
+if "`cfasb'"!="" & `cfarmsea'!=-999 {
+ di in red "You cannot use both cfasb and cfarmsea()"
+ exit 119
+}
+
+
+
+if `cfarmsea' == -999{
+ local cfarmsea
+ //di in red "error in cfaautormsea option : you must specify a value"
+ //exit 119
+}
+if `cfacfi' == -999{
+ local cfacfi
+ //di in red "error in cfaautocfi option : you must specify a value"
+ //exit 119
+}
+
+local nbvars:word count `varlist'
+local P:word count `partition'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+/*
+if "`cfarmsea'" != "" & "`cfacov'" != "" {
+ di in red "You cannot use both cfacov() and cfarmsea"
+ exit 119
+}
+if "`cfacfi'" != "" & "`cfacov'" != "" {
+ di in red "You cannot use both cfacov() and cfacfi"
+ exit 119
+}
+*/
+if "`cfacov'" != "" {
+
+ lstrfun v, subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ lstrfun s, subinstr("`cfacov'","* ","*",.)
+ lstrfun s, subinstr("`s'"," *","*",.)
+ lstrfun s, subinstr("`s'","*","*e.",.)
+ lstrfun f, subinstr("`s'"," "," e.",.)
+ local g e.`f'
+ lstrfun g , lower("`g'")
+ local covs `g'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = lower("`x'")
+ qui rename `x' `var`i''
+ local `++i'
+}
+
+local upscorename = upper("$scorename")
+
+local i = 0
+local y = 1
+tokenize `upscorename'
+foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ local a = "(``i'' -> `liste')"
+ local zz `zz' `a'
+
+ local y = `s'+1
+}
+
+if "`cfamethod'" == "" local cfamethod = "ml"
+
+if "`cfamethod'" != "ml" & "`cfamethod'" != "mlmv" & "`cfamethod'" != "adf" {
+ di "`cfamethod'"
+ di in red "option cfamethod incorrectly specified (choose among ml, mlmv and adf)."
+ error 198
+}
+
+if "`cfastand'" != "" local cfastand = "stand"
+
+if "`cfasb'" != "" {
+ local cfasb = "vce(sbentler)"
+ local sb = "_sb"
+}
+
+di as result "{hline 105}"
+di "{bf:Confirmatory factor analysis}"
+di as result "{hline 105}"
+
+local exitloop = 0
+foreach v in `varlist' {
+ local low = lower("`v'")
+ qui su `low'
+ local range = r(max)-r(min)+1
+ if `range' < 5 & "`cfamethod'"=="ml"{
+ local message "Warning: some items have less than 5 response categories. If multivariate normality assumption does not hold, maximum likelihood estimation might not be appropriate. Consider using cfamethod(adf)."
+ continue, break
+ }
+ else if `range' >= 5 & `range' < 7 & "`cfamethod'"=="ml" & "`cfasb'" == "" {
+ local message "Warning: some items have less than 7 response categories. If multivariate normality assumption does not hold, maximum likelihood estimation might not be appropriate. Consider using cfasb in order to apply Satorra-Bentler adjustment or using cfamethod(adf)."
+ continue
+ }
+}
+
+di in red "`message'"
+
+local ii = 1
+local s
+local stop = 0
+
+while (`ii' == 1 | "`covsi'" != "") & `stop'!=1 {
+ if `ii' == 1 & ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ di
+ di as text "step 1 (model without covariances between errors)"
+ }
+ if "`covs'" != "" & ("`cfarmsea'"!="" | "`cfacfi'"!="") di _n "{bf:step `ii':} {text:`covsi'}"
+ local covsi
+
+
+ if "`cfanocovdim'" == "" {
+ qui sem `zz', method(`cfamethod') `cfastand' cov(`covs') `cfasb' `options'
+ }
+ else {
+ qui sem `zz', method(`cfamethod') `cfastand' cov(`covs') covstruct(_lexogenous, diagonal) `cfasb' `options'
+ }
+ local vce = e(vce)
+
+ /* factor loadings */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix a = a\b
+ }
+
+ /* standard error factor loadings*/
+
+ matrix r = r(table)
+ matrix r = r[2,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sef = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sef = sef\b
+ }
+
+
+ /* intercepts */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a2 = r[2,1]
+ forvalues i=4(2)`n' {
+ matrix b = r[`i',1]
+ matrix a2 = a2\b
+ }
+
+
+ /* standard error intercepts*/
+
+ matrix r = r(table)
+ matrix r = r[2,2...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sei = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sei = sei\b
+ }
+
+ //mat li sei
+ /* error variances */
+
+ local m = `n'+1
+ matrix r = r(table)
+ matrix r = r[1,`m'...]
+ matrix r = r'
+
+ matrix a3 = r[1,1]
+ forvalues i=2/`nbvars' {
+ matrix b = r[`i',1]
+ matrix a3 = a3\b
+ }
+
+ /* variance of dimensions*/
+
+ matrix r = r(table)
+ local n = `nbvars'*3+1
+ matrix r = r[1,`n'...]
+ matrix r = r'
+
+ matrix var = r[1,1]
+ forvalues i=2/`P' {
+ matrix b = r[`i',1]
+ matrix var = var\b
+ }
+
+ //mat li var
+
+ /* Covariances between dimensions */
+
+ matrix r = r(table)
+ local P:word count `partition'
+ if `P' > 1 {
+ local one = 1
+ }
+ else{
+ local one = 0
+ }
+ local n = `nbvars'*3+`one'+`P'
+
+
+ if "`cfanocovdim'" == "" {
+ //mat li r
+ matrix r = r[1,`n'...]
+ //mat li r
+ matrix c = J(`P',`P',.)
+
+ local nbcov:word count `cfacov'
+ local `++nbcov'
+
+ local k = `nbcov'
+ forvalues c = 1/`P' {
+ forvalues r = 2/`P' {
+ if `r'>`c' {
+ matrix c[`r',`c']=r[1,`k']
+ local `++k'
+ }
+ }
+ }
+
+ local k = 1
+ forvalues c = 1/`P' {
+ matrix c[`c',`c']=var[`k',1]
+ local `++k'
+ }
+
+ matrix rownames c = $scorename
+ matrix colnames c = $scorename
+ }
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ local stoprmsea = 0
+ local stopcfi = 0
+ if "`cfarmsea'"!="" {
+ qui estat gof
+ di "rmsea =" round(r(rmsea),0.001)
+ if r(rmsea)<=`cfarmsea' {
+ local stoprmsea = 1
+ }
+ //else local stoprmsea = 0
+ }
+ else local stoprmsea = 1
+ if "`cfacfi'"!="" {
+ qui estat gof
+ di "cfi =" round(r(cfi),0.001)
+ if r(cfi)>=`cfacfi' {
+ local stopcfi = 1
+ }
+ //else local stopcfi = 0
+ }
+ else local stopcfi = 1
+
+
+
+ /* OR */
+ if "`cfaor'"!="" {
+ if `stoprmsea'==1 | `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ /* AND */
+ if "`cfaor'"=="" {
+ if `stoprmsea'==1 & `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ }
+
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") & `stop'!=1 {
+ qui estat mindices, showpclass(mcons merrvar)
+ tempname mm nomcol
+ mat `mm' = r(mindices)
+
+ svmat2 `mm' , r(`nomcol') full
+ gsort - `mm'1
+
+ local nrows = rowsof(`mm')
+
+ local y = 1
+ local i = 0
+ foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues w = `y'/`s' {
+ local class_`var`w'' = `i'
+ }
+ local y = `s'+1
+ }
+
+
+ forvalues i = 1/`nrows' {
+ local tmp3=`nomcol'[`i']
+ lstrfun e, subinstr("`tmp3'","cov(","",.)
+ lstrfun e, subinstr("`e'",")","",.)
+ lstrfun e, subinstr("`e'",":_cons","",.)
+ lstrfun e, subinstr("`e'",",","*",.)
+
+ lstrfun d, subinstr("`e'",","," ",.)
+ lstrfun d, subinstr("`d'","e.","",.)
+ lstrfun d, subinstr("`d'","*"," ",.)
+
+ qui replace `nomcol' = "`d'" in `i'
+
+ local d = `nomcol'[`i']
+
+ tokenize "`d'"
+ if "`class_`1''" != "`class_`2''" {
+ qui replace `nomcol' = "" in `i'
+ }
+
+ local tmp3=`nomcol'[`i']
+
+ if "`tmp3'" != "" {
+ continue, break
+ }
+ else {
+ local e
+ }
+
+
+ }
+
+
+
+
+ local covsi `e'
+ local covs `covs' `e'
+ drop `mm'1-`nomcol'
+
+ }
+
+ if e(converged) == 0 di in red "Warning : model did not converge after `e(ic)' iterations"
+ local `++ii'
+
+}
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+local i = 1
+foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+
+}
+
+local max = 10
+local dec = `max'+5
+
+local max2 = 10
+
+local dec2 = `dec'+`max2'+5
+
+local a = e(N)
+di
+if e(converged) == 0 di in red "Warning : model did not converge after `e(ic)' iterations"
+di as result ""
+if "`covs'" != "" {
+ di as result "{bf:Covariances between errors added:} {text:`covs'}"
+ di
+}
+di "{bf:Number of used individuals: } {text:`a'}"
+di
+//di _col(`=`dec2'+17+4') "{bf:Estimation:}"
+
+
+di as result "{bf:Item}" _c
+di _col(`dec') "{bf:Dimension}" _c
+di _col(`dec2') "{bf:Factor}" _c
+di _col(`=`dec2'+14') "{bf:Standard}" _c
+di _col(`=`dec2'+28') "{bf:Intercept}" _c
+di _col(`=`dec2'+43') "{bf:Standard}" _c
+
+if "`cfastand'" == "" {
+ di _col(`=`dec2'+57') "{bf:Error}" _c
+ di _col(`=`dec2'+66') "{bf:Variance of}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+43') "{bf:error}" _c
+ di _col(`=`dec2'+55') "{bf:variance}" _c
+ di _col(`=`dec2'+67') "{bf:dimension}"
+ local h = `dec2'+76
+}
+else {
+ di _col(`=`dec2'+57') "{bf:Error}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+44') "{bf:error}" _c
+ di _col(`=`dec2'+57') "{bf:variance}"
+ local h = `dec2'+62
+}
+
+di "{hline `h'}"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ tokenize `sc'
+ di "{bf:`var`z''}"_c
+ di _col(`dec') "{bf:``i''}" _c
+ local t = a[`z',1]
+ local t : di %7.2f `t'
+ di _col(`dec2') "{text:`t'}" _c
+
+ local t = sef[`z',1]
+ local t : di %8.2f `t'
+ di _col(`=`dec2'+14') "{text:`t'}" _c
+
+ local t = a2[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+28') "{text:`t'}" _c
+
+ local t = sei[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+42') "{text:`t'}" _c
+
+ local t = a3[`z',1]
+ local t : di %11.2f `t'
+
+ if "`cfastand'" == "" & `z' == `y'{
+ di _col(`=`dec2'+52') "{text:`t'}" _c
+ local t = var[`i',1]
+ local t : di %11.2f `t'
+ di _col(`=`dec2'+66') "{text:`t'}"
+ }
+ else di _col(`=`dec2'+52') "{text:`t'}"
+ }
+ di
+ local `i++'
+ local y = `s'+1
+}
+
+qui estat gof, stats(all)
+
+
+if "`cfasb'" != "" | "`vce'"=="sbentler"{
+ local chi2 = r(chi2sb_ms)
+ local p = r(psb_ms)
+ local ddl = r(df_ms)
+ local ratio = `chi2'/`ddl'
+ local rmsea = r(rmsea_sb)
+ *local lb = r(lb90_rmsea)
+ *local ub = r(ub90_rmsea)
+ local nfi = 1-(r(chi2sb_ms)/r(chi2sb_bs))
+ local rni = 1-(r(chi2sb_ms)-r(df_ms))/(r(chi2sb_bs)-r(df_bs))
+ local cfi = r(cfi_sb)
+ local ifi = (r(chi2sb_bs)-r(chi2sb_ms))/(r(chi2sb_bs)-r(df_ms))
+ local mci = exp(-0.5*((r(chi2sb_ms)-r(df_ms))/(e(N)-1)))
+ local srmr = r(srmr)
+}
+
+else {
+ local chi2 = r(chi2_ms)
+ local p = r(p_ms)
+ local ddl = r(df_ms)
+ local ratio = `chi2'/`ddl'
+ local rmsea = r(rmsea)
+ local lb = r(lb90_rmsea)
+ local ub = r(ub90_rmsea)
+ local nfi = 1-(r(chi2_ms)/r(chi2_bs))
+ local rni = 1-(r(chi2_ms)-r(df_ms))/(r(chi2_bs)-r(df_bs))
+ local cfi = r(cfi)
+ local ifi = (r(chi2_bs)-r(chi2_ms))/(r(chi2_bs)-r(df_ms))
+ local mci = exp(-0.5*((r(chi2_ms)-r(df_ms))/(e(N)-1)))
+ local srmr = r(srmr)
+}
+
+if "`cfanocovdim'" == "" {
+ di
+ di "Covariances between dimensions:"
+ mat li c, nodotz noheader format(%4.2f)
+}
+
+di
+if "`cfasb'" != "" | "`vce'"=="sbentler" {
+ di "{bf:Goodness of fit (with Satorra-Bentler correction):}"
+}
+else {
+ di "{bf:Goodness of fit:}"
+}
+di
+
+
+
+if "${html}" != "" {
+
+di as result _col(4) "chi2" _c
+di as result _col(20) "df" _c
+di as result _col(28) "chi2/df" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI"
+
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}"
+
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+di as result _col(4) "CFI" _c
+di as result _col(15) "IFI" _c
+di as result _col(26) "MCI"
+local t : di %5.3f `cfi'
+di _col(4) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(15) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(26) "{text:`t'}"
+di as result
+}
+else {
+di as result _col(4) "chi2" _c
+di as result _col(20) "df" _c
+di as result _col(28) "chi2/df" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI" _c
+di as result _col(94) "CFI" _c
+di as result _col(104) "IFI" _c
+di as result _col(114) "MCI"
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}" _c
+local t : di %5.3f `cfi'
+di _col(92) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(102) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(112) "{text:`t'}"
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+
+}
+end
+
+
+/* repet */
+
+capture program drop repet
+program repet,rclass
+syntax varlist, PARTition(numlist integer >0) [t2(varlist) KAPpa ICKAPpa(integer 0)]
+preserve
+
+local nbvars : word count `varlist'
+
+if `ickappa' <= 0 {
+ local ickappa = ""
+}
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local P:word count `partition'
+
+if "$scores2" != "" {
+ local t:word count $scores2'
+ if `P' != `t' {
+ di in red "The number of score names given in scores2() is different from the number of scores defined"
+ exit 119
+ }
+}
+
+if "`t2'" != "" {
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local maxit = 1
+ forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `maxit' local maxit = `len'
+ }
+
+ local decit = `maxit' + 4
+ local colit = `decit'
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ if "$scores2" == "" {
+ foreach sco in $scorename {
+ *local t = "`sco'bis"
+ tempname s
+ local scorename2 `scorename2' `s'
+ }
+
+ qui calcscore `t2', scorename(`scorename2') partition(`partition') compscore(${compscore}) categories($categories)
+
+ }
+
+ else {
+ foreach sco in $scores2 {
+ local scorename2 `scorename2' `sco'
+ }
+ }
+
+ local i = 1
+ foreach var in `varlist' {
+ tokenize `t2'
+ qui kap `var' ``i''
+ local k`i' = r(kappa)
+ if "`ickappa'" != "" {
+ qui kapci `var' ``i'', reps(`ickappa')
+ local lbk`i' = r(lb_bc)
+ local ubk`i' = r(ub_bc)
+ }
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ tokenize `scorename2'
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize `sc'
+ local max = length("dimension")
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+ di "{bf:Dimension}" _c
+ di _col(`=`dec'+2') "{bf:n}" _c
+ local col = `dec'+6
+ di _col(`col') "{bf:Item}" _c
+ local col = `col'+`decit'
+
+ if "`kappa'" != "" {
+ di _col(`col') "{bf:Kappa}" _c
+ local col = `col'+10
+ if "`ickappa'" != "" {
+ di _col(`col') "{bf:95% CI for Kappa}" _c
+ local col = `col'+20
+ }
+
+ }
+
+ di _col(`=`col'+2') "{bf:ICC}" _c
+ local col = `col'+9
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ local zz = 0
+ foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ local z : word count `levels'
+ if `z' > 2 local zz = 1
+ }
+
+ if "`kappa'" != "" & "`ickappa'" != "" & `zz' == 1 {
+ local col = `dec'+`decit'+16
+ di _col(`col') "{bf:(bootstrapped)}"
+ }
+
+
+ if "`ickappa'" != "" local h = `dec'+6+`decit'+10+8+21+12+1
+ else if "`kappa'" != "" local h = `dec'+6+`decit'+10+8+21+12-20
+ else local h = `dec'+6+`decit'+10+8+21+12-29
+ di "{hline `h'}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize `sc'
+ di "{bf:``i''}" _c
+ di _col(`dec') "{text:`n`i''}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+6
+ di _col(`col') "{text:`var`y''}" _c
+
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`y''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`i''
+ local ubk : di %5.2f `ubk`i''
+ local col = `col'+11
+ di _col(`col') "{text:[`lbk' ; `ubk']}" _c
+ local col = `decit'+50
+ }
+
+ else local col = `decit'+30
+ }
+ else local col = `decit'+20
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+8
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ forvalues z = `w'/`s' {
+ local col = `dec'+6
+ di _col(`col') "{text:`var`z''}" _c
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`z''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`z''
+ local ubk : di %5.2f `ubk`z''
+ local col = `col'+11
+ di _col(`col')"{text:[`lbk' ; `ubk']}"
+ }
+ else di
+
+ }
+ else di
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+ }
+}
+
+else {
+ local i = 1
+ foreach s in $scorename {
+ tokenize $scores2
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize $scorename
+ local max = length("dimension")
+
+ local h = 1
+ foreach s in $scorename {
+ local s`h' = abbrev("`s'",10)
+ local sc `sc' `s`h''
+ local `++h'
+ }
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ di "{bf:Dimension}" _c
+ local col = `dec'
+ di _col(`col') "{bf:n}" _c
+
+
+ di _col(`=`col'+6') "{bf:ICC}" _c
+ local col = `col'+14
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ di "{hline 50}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize $scorename
+ di "{bf:``i''}" _c
+ local n : di % 4.0f `n`i''
+ di _col(`=`dec'-3') "{text:`n'}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+4
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+9
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ local `i++'
+ }
+}
+
+end
+
+
+/* kgv */
+
+capture program drop kgv
+program kgv,rclass
+syntax varlist, categ(varlist) [KGVBoxplots KGVGroupboxplots]
+
+foreach c in `categ' {
+ tempname j
+ capture encode `c', generate(`j')
+ capture confirm variable `j'
+ if _rc local j = "`c'"
+ local categ2 `categ2' `j'
+}
+
+local i = 1
+local j = 1
+local k = 0
+local max = 0
+local a : word count `categ'
+local nb:word count `varlist'
+
+di as result "{hline 105}"
+di "{bf:Known-groups validity}"
+di as result "{hline 105}"
+di
+
+foreach sco in `varlist' {
+ foreach cat in `categ2' {
+ local nblev = 0
+ local maxlen`j' = 0
+
+ qui anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ qui kwallis `sco', by(`cat')
+ local p2`i'_`j' = chi2tail(r(df), r(chi2))
+
+
+ /*local inf30 = 0
+ qui tab `cat' if `sco'!=., matcell(x)
+ local r = r(r)
+ forvalues n = 1/`r' {
+ if x[`n',1]<48 {
+ local `++inf30'
+ }
+ }
+ if `inf30' > 0 {
+ //di in red "kw"
+ kwallis `sco', by(`cat')
+ local p2`i'_`j' = chi2tail(r(df), r(chi2))
+ anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+
+ }
+ else {
+ //di in red "aov"
+ anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ }*/
+
+
+ qui levelsof `cat', local(levels)
+ local lbe : value label `cat'
+
+ foreach l of local levels {
+ qui count if `sco' !=. & `cat' == `l'
+ local `++k'
+ local eff`i'_`j'_`k' = r(N)
+
+ if "`lbe'" != "" {
+ local ll`j'_`k' : label `lbe' `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ else {
+ local ll`j'_`k' = `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ qui su `sco' if `cat' == `l'
+ local m`i'_`j'_`k' = r(mean)
+ local s`i'_`j'_`k' = r(sd)
+ local nblev = `nblev' + 1
+ }
+ if `nblev' > `max' local max = `nblev'
+ local `++j'
+ local k = 0
+ }
+ local `++i'
+ local j = 1
+}
+
+local i = 1
+foreach s in `varlist' {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+local maxs = 0
+forvalues j=1/`nb' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `maxs' local maxs = `len`j''
+}
+
+local i = 1
+local k = 0
+local j = 2
+
+foreach cat in `categ'{
+ local `++k'
+ tokenize `categ'
+ local c`k' = "``i'' ``j''"
+ local i = `i' + 2
+ local j = `j' + 2
+}
+
+
+local d = 1
+local f = 2
+forvalues h = 1/`a' {
+ if `f' > `a' local f = `f'-1
+ local j = 1
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`col') "{bf:`cat'}" _c
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+ di
+
+ local j = `d'
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`=`col'+`maxlen`j''+5') "{bf: mean }" _c
+ di "{bf: sd }" _c
+ di "{bf:p-value}" _c
+ //di "{bf:p-value (Kruskal-Wallis)}" _c
+
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+
+ local j = `d'
+ local col = `maxs'+6
+
+ di
+ di
+ local i = 1
+ local col = `maxs'+6
+
+ forvalues g = 1/`nb' {
+
+ di "{bf:`s`g''}" _c
+ forvalues k = 1/`max' {
+ forvalues j = `d'/`f' {
+
+ di _col(`col') "{bf:`ll`j'_`k''} " _c
+ if "`eff`i'_`j'_`k''" != "" di as text "(n=`eff`i'_`j'_`k'')" _c
+ local m : di %6.2f `m`i'_`j'_`k''
+ di _col(`=`col'+`maxlen`j''+10') "{text:`m'} " _c
+
+ local s : di %8.2f `s`i'_`j'_`k''
+ di "{text: `s'} " _c
+
+ if `k' == 1 {
+ local p : di %8.3f `p`i'_`j''
+ local p2 : di %4.3f `p2`i'_`j''
+ di _col(`=`col'+31') "{text:`p'} " _c
+ di _col(`=`col'+35') "{text:(KW: `p2')} " _c
+ }
+ local col = `col' + `maxlen`j'' + 5 + 40
+ }
+ di
+ local col = `maxs'+6
+
+ }
+ di
+
+ local `++i'
+
+ }
+ local d = `d'+2
+ local f = `f'+2
+ if `d' > `a' continue, break
+ di
+}
+
+if "`kgvboxplots'" != "" {
+ local html = "${html}"
+ if "`html'" != "" {
+ di "
"
+ di ""
+ if "`kgvgroupboxplots'" != "" {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") nodraw
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph export `c(tmpdir)'/`html'_kgv`s'.png, replace
+
+
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv,replace) nodraw"
+ qui gr combine `g', name(kgv,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv.gph
+ qui graph export `c(tmpdir)'/`html'_kgv.png, replace
+ //di "
"
+
+ }
+ else {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'")
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph export `c(tmpdir)'/`html'_kgv`s'.png, replace
+ //di "
"
+
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ }
+ di "
"
+ di ""
+
+ }
+ else {
+ if "`kgvgroupboxplots'" != "" {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") nodraw
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ gr combine `g', name(Known_groups_validity,replace)
+ if ("$filessave"!="") qui graph export ${dirsave}/Known_groups_validity.png, replace
+
+ }
+ else {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')")
+ if ("$filessave"!="") qui graph export ${dirsave}/Known_groups_validity_`c'_`s'.png, replace
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ }
+ }
+}
+
+end
+
+
+/* conc */
+
+capture program drop conc
+program conc,rclass
+syntax varlist, comp(varlist) [tconc(real 0.4)]
+
+di as result "{hline 105}"
+di "{bf:Concurrent validity}"
+di as result "{hline 105}"
+di
+
+local n : word count `varlist'
+local p : word count `comp'
+
+matrix m = J(`n',`p',.)
+matrix rownames m = `varlist'
+matrix colnames m = `comp'
+local r = 1
+
+foreach i in `varlist' {
+ local c = 1
+ foreach j in `comp' {
+ qui corr `i' `j'
+ mat e = r(C)
+ local f = e[2,1]
+ mat m[`r',`c'] = `f'
+ local `++c'
+ }
+ local `++r'
+}
+
+tokenize `varlist'
+local maxv = length("`1'")
+forvalues i=1/`n' {
+ local lenv = length("``i''")
+ if `lenv' > `maxv' local maxv = `lenv'
+}
+
+local decv = `maxv'+6
+
+tokenize `comp'
+local maxc = length("`1'")
+forvalues i=1/`p' {
+ local lenc = length("``i''")
+ if `lenc' > `maxc' local maxc = `lenc'
+}
+
+local decc = `maxc'+4
+
+local col = `decv'
+foreach c in `comp' {
+ di as result _col(`col') "`c'" _c
+ local col = `col'+`decc'
+}
+di
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+forvalues i=1/`n' {
+ di as result "`var`i''" _c
+ local col = `decv'
+ forvalues j=1/`p' {
+ local t = m[`i',`j']
+ if `t' > `tconc' | `t' < -`tconc' {
+ di as result _col(`=`col'-1') %5.2f `t' _c
+ }
+ else di as text _col(`=`col'-1') %5.2f `t' _c
+ local col = `col'+`decc'
+ }
+ di
+}
+
+capture restore, not
+end
+
diff --git a/Modules/ado/personal/v/validscale.ado (old) b/Modules/ado/personal/v/validscale.ado (old)
new file mode 100644
index 0000000..12d9b42
--- /dev/null
+++ b/Modules/ado/personal/v/validscale.ado (old)
@@ -0,0 +1,2979 @@
+*! Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine
+*************************************************************************************************************
+* Stata program : validscale
+* Assess validity and reliability of a multidimensional measurement scale using CTT methods
+
+* Required modules :
+* delta
+* loevh
+* kapci
+* mi_twoway
+* detect
+* imputeitems
+* lstrfun
+
+* Version 1.1 (September 3, 2018) /*updated the dialog box for Stata 15, fixed a bug with cfarmsea, cfacfi and cfacovs, fixed a bug with descitems when the first observation contained missing data*/
+* Version 1.2 August 13, 2019 /* filessave and dirsave options */
+
+
+*************************************************************************************************************
+
+program define validscale, rclass
+version 12.0
+syntax varlist [if], PARTition(numlist integer >0) [HTML(string) CATegories(numlist) SCOREName(string) scores(varlist) IMPute(string) NORound COMPScore(string) DESCitems GRAPHs cfa CFAMethod(string) cfasb CFAStand CFACov(string) CFARmsea(real -999) CFACFi(real -999) CFAOR CFANOCOVDim CONVdiv TCONVdiv(real 0.4) CONVDIVBoxplots Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3) REPet(varlist) scores2(varlist) KAPpa ICKAPpa(integer 0) kgv(varlist) KGVBoxplots KGVGroupboxplots conc(varlist) tconc(real 0.4) DIRsave(string) FILESsave]
+preserve
+
+
+foreach c in delta loevh mi_twoway detect imputeitems lstrfun{
+ capture which "`c'"
+ if _rc qui ssc install "`c'"
+}
+capture which kapci
+if _rc qui net install st0076, from(http://www.stata-journal.com/software/sj4-4/)
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+global html
+global dirsave
+global filessave
+
+if "`filessave'" != "" {
+ global filessave = "`filessave'"
+}
+
+if "`dirsave'" != "" {
+ global dirsave = "`dirsave'"
+}
+else {
+ global dirsave "`c(pwd)'"
+}
+
+if "`html'" != "" {
+ global html = "`html'"
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local xsize=6
+ local ysize=4
+ di in gr ""
+ di "
"
+ di ""
+}
+
+if "`categories'" == "" {
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ local m `mi' `ma'
+ local categories `categories' `m'
+ }
+}
+
+global categories = "`categories'"
+global compscore = "`compscore'"
+if "$compscore" == "" global compscore = "mean"
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+if "`repet'" != "" {
+ local b:word count `repet'
+ if `nbvars' != `b' {
+ di in red "The number of items in varlist is different from the number of items in repet"
+ exit 119
+ }
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+local P:word count `partition'
+local S:word count `scorename'
+
+if "`scores'" != "" & "`scorename'" != "" {
+ di in red "scorenames() and scores() cannot be used together"
+ exit 119
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ foreach sco in `scorename' {
+ capture confirm variable `sco', exact
+ if !_rc {
+ di in red "`sco' already defined. You must choose names that do not already exist or use the scores() option if the scores are already defined."
+ exit 119
+ }
+ tokenize `scorename'
+ local g = 0
+ forvalues i = 1/`S' {
+ if "`sco'" == "``i''" {
+ local `++g'
+ }
+ }
+ if `g' > 1 {
+ di in red "2 or more dimensions have the same name"
+ exit 119
+ }
+ }
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') categories(`categories')
+ global exist = 0
+ global scorename = "`scorename'"
+}
+
+else if "`scorename'" == "" & "`scores'" == ""{
+
+ local name
+ local nname
+
+ forvalues i = 1/`P' {
+
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+
+ local scorename = "`nname'"
+ global scorename = "`nname'"
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') categories(`categories')
+ global exist = 0
+}
+
+else if "`scores'" != "" {
+ local P:word count `partition'
+ local S2:word count `scores'
+ if `P'!=`S2' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ else {
+ global scorename = "`scores'"
+ local scorename = "`scores'"
+ global exist = 1
+
+ }
+
+}
+
+local nbm : word count $categories
+if `nbm' !=2 &`nbm' !=`P'*2 &`nbm' !=`nbvars'*2 {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+}
+
+if `nbm' == 2{
+ tokenize $categories
+ foreach v in `varlist' {
+ tempvar min
+ tempvar max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ if `min' < `1' {
+ di in red "error in option categories() : some responses have smaller values than the minimum value in categories()"
+ exit 119
+ }
+ if `max' > `2' {
+ di in red "error in option categories() : some responses have greater values than the maximum value in categories()"
+ exit 119
+ }
+ }
+}
+
+if `nbm' == `nbvars'*2 {
+ local i = 1
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ tokenize $categories
+ if `mi' < ``i'' {
+ di in red "error in option categories() : some responses have values less than the minimum value specified for the variable in categories()"
+ exit 119
+ }
+ local `++i'
+ tokenize $categories
+ if `ma' > ``i'' {
+ di in red "error in option categories() : some responses have values greater than the maximum value specified for the variable in categories()"
+ exit 119
+ }
+ local `++i'
+ }
+}
+
+if `nbm' == `P'*2 {
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ //local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+ forvalues w = `y'/`s' {
+ tokenize $categories
+ tempvar min max
+ egen `min' = min(`var`w'')
+ egen `max' = max(`var`w'')
+ local mi = `min'
+ local ma = `max'
+ if `mi' < ``i'' {
+ di in red "error in option categories() : some responses have values less than the minimum value specified"
+ exit 119
+ }
+ local j = `i'+1
+ tokenize $categories
+ if `ma' > ``j'' {
+ di in red "error in option categories() : some responses have values greater than the maximum value specified"
+ exit 119
+ }
+ }
+ local i = `i'+2
+ local y = `s'+1
+ }
+}
+
+if "`cfa'" != "" {
+ if "`cfacov'" != "" {
+ if !strpos("`cfacov'", "*") {
+ di "error in cfacov() option : you must enter covariances between errors as follows: item3*item5 item7*item8 ... "
+ exit 119
+ }
+ local v = subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ }
+
+}
+
+if "`kgv'" !="" {
+ foreach k in `kgv' {
+ capture confirm variable `k'
+ if _rc!=0 {
+ di in red "`k' does not exist"
+ exit 119
+ }
+ }
+}
+
+if "`conc'" !="" {
+ foreach c in `conc' {
+ capture confirm variable `c'
+ if _rc!=0 {
+ di in red "`c' does not exist"
+ exit 119
+ }
+ }
+}
+
+di as result "Items used to compute the scores"
+di
+
+local i = 1
+local j = 1
+local y = 1
+foreach p in `partition' {
+ tokenize `scorename'
+ di "{bf:``i''} : " _c
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ forvalues z = `y'/`s' {
+ di "{text:`var`z'' }" _c
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+}
+
+di
+di as result "Number of observations: " _c
+di as text _N
+
+qui destring _all, replace
+di
+
+if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+}
+
+
+if "`graphs'" != "" {
+ graphs `varlist', partition(`partition')
+}
+
+
+if "`repet'" != "" {
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+}
+
+if "`impute'" != "" {
+ if "`impute'" != "pms" & "`impute'" !="mi" {
+ di in red "option impute() incorrectly specified. You must specify {hi:pms} or {hi:mi}."
+ error 100
+ }
+ if "`impute'" == "pms" {
+ pms `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (PMS imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ pms `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+ if "`impute'" == "mi" {
+ mitw `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (mi two-way imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ mitw `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+}
+
+rel `varlist', scorename(`scorename') partition(`partition') alpha(`alpha') delta(`delta') h(`h') hjmin(`hjmin') categories(`categories')
+di
+
+if "`convdiv'" != "" {
+ convdiv `varlist', partition(`partition') tconvdiv(`tconvdiv') `convdivboxplots'
+ di
+}
+
+if "`cfa'" != "" {
+ cfa `varlist', partition(`partition') cfamethod(`cfamethod') `cfasb' `cfastand' cfacov(`cfacov') cfarmsea(`cfarmsea') cfacfi(`cfacfi') `cfaor' `cfanocovdim'
+ di
+}
+
+if "`repet'" != "" | "`scores2'" != "" {
+ global scores2 = "`scores2'"
+ repet `varlist', t2(`repet') partition(`partition') `kappa' ickappa(`ickappa')
+ di
+}
+
+if "`kgv'" != "" {
+ kgv `scorename', categ(`kgv') `kgvboxplots' `kgvgroupboxplots'
+ di
+}
+
+if "`conc'" != "" {
+ conc `scorename', comp(`conc') tconc(`tconc')
+}
+
+
+//capture restore, not
+end
+
+
+/* pms */
+
+capture program drop pms
+program pms
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+tokenize `varlist'
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ local n : word count `liste'
+ if mod(`n',2)!=0 local max = floor(`n'/2)
+ else local max = `n'/2-1
+
+ if "`noround'" != "" {
+ qui imputeitems `liste', method(pms) max(`max') noround
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+ else {
+ qui imputeitems `liste', method(pms) max(`max')
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+end
+
+
+/* mitw */
+
+capture program drop mitw
+program mitw
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ qui mi_twoway `liste', scorename(scoretmp) add(1) style(wide) clear
+
+ foreach var of varlist `liste' {
+ qui replace `var' = _1_`var'
+ if "`noround'" == "" {
+ qui replace `var' = round(`var')
+ }
+ /*if `var' > `maxm' {
+ qui replace `var' = `maxm'
+ }
+ if `var' < `minm' {
+ qui replace `var' = `minm'
+ }*/
+ qui drop _1_`var'
+ capture drop scoretmp
+ capture drop _1_scoretmp
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+//capture drop _mi_miss
+qui mi unset
+end
+
+
+/* calcscore */
+
+capture program drop calcscore
+program calcscore,rclass
+syntax varlist, PARTition(numlist integer >0) [categories(numlist) COMPscore(string) SCOrename(string)]
+
+local P:word count `partition'
+local S:word count `scorename'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+}
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ tempvar nonmiss
+ qui egen `nonmiss' = rownonmiss(`liste')
+
+ tokenize `scorename'
+ local sc = "``i''"
+
+ if "`compscore'" == "" local compscore = "mean"
+
+ if "`compscore'" != "mean" & "`compscore'" != "sum" & "`compscore'" != "stand" {
+ di in red "option compscore incorrectly specified (choose among mean, sum and stand)"
+ error 198
+ }
+
+ if "`compscore'" == "sum" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`x'
+
+ }
+
+ else if "`compscore'" == "stand" {
+
+ local nbm:word count `categories'
+
+ local nbl:word count `liste'
+ tokenize `categories'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+
+ }
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+ }
+ }
+
+ else {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`nonmiss'
+ qui replace `sc' = (`sc'-`min')/(`max'-`min')*100
+ }
+
+ else {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ }
+
+local `i++'
+local y = `s'+1
+}
+
+end
+
+
+
+/* rel */
+
+capture program drop rel
+program rel,rclass
+syntax varlist, PARTition(numlist integer >0) [CATegories(numlist) SCOrename(string) Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3)]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+di as result "{hline 105}"
+di "{bf:Reliability}"
+di as result "{hline 105}"
+di
+
+local y = 1
+local nbitems = 0
+matrix aa = J(`P',4,.)
+
+foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+matrix d = J(`nbitems',2,.)
+
+local i = 1
+local b = 1
+foreach x in `partition' {
+
+ tokenize `scorename'
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ capture alpha `liste', asi item std
+ local al`i' = r(alpha)
+
+ capture qui loevh `liste', pairwise
+ local h`i' = r(loevH)
+ matrix c = r(loevHj)
+ matrix ct = c'
+
+
+ local lister = ""
+ forvalues w = `y'/`s' {
+ tempvar z
+ qui gen `z' = round(`var`w'')
+ local lister `lister' `z'
+ }
+
+ tempvar nbmiss
+ local nbl : word count `lister'
+ egen `nbmiss' = rowmiss(`lister')
+ qui count if `nbmiss'<`nbl'
+ local n`i' = r(N)
+
+
+ // delta
+
+ if ${exist} == 0 & "$compscore" == "sum" {
+
+ local nbm:word count `categories'
+ tokenize `categories'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+ }
+
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+
+ }
+ }
+
+ else {
+ di in red "option categories() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ capture delta `lister', min(`min') max(`max')
+ local delt`i' = r(delta)
+
+ }
+
+ else local delt`i' = .
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',1] = ct[`k',1]
+ matrix d[`j',2] = `i'
+ }
+
+ matrix aa [`i',1] = `al`i''
+ matrix aa [`i',2] = `delt`i''
+ matrix aa [`i',3] = `h`i''
+
+ local `i++'
+ local y = `s'+1
+
+ local b = `b'+2
+}
+
+matrix rownames d = `varlist'
+local i = 1
+local y = 1
+
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ matrix C = d[`y'..`s',1.]
+ local min`i' = C[1,1]
+ local n : rownames C
+ tokenize `n'
+ local t`i' = "`1'"
+ forvalues j = 1/`x' {
+ local t = "``j''"
+ if C[`j',1] <= `min`i'' {
+ local min`i' = C[`j',1]
+ local t`i' = "``j''"
+ local itmin`i' = "``j''"
+ }
+ }
+ matrix aa [`i',4] = `min`i''
+ local `i++'
+ local y = `s'+1
+}
+
+matrix colnames aa = "alpha" "delta" "H" "Hj_min"
+
+if "`scorename'"=="" {
+ local i = 1
+ local y = 1
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local maxlen = 0
+foreach sco in `scorename' {
+ local w = length("`sco'")
+ if `w' > `maxlen' local maxlen = `w'
+}
+
+local i = 1
+local j = 1
+local y = 1
+local col = `maxlen'+8
+
+di _col(`col') "{bf:n}" _c
+local col = `col'+6
+di _col(`col') "{bf:alpha}" _c
+local col = `col'+10
+di _col(`col') "{bf:delta}" _c
+local col = `col'+14
+di _col(`col') "{bf:H}" _c
+local col = `col'+5
+di _col(`col') "{bf:Hj_min}"
+
+foreach s in `scorename' {
+ di in blue "{bf:`s'}" _c
+ local col = `maxlen'+3
+
+ local n : di %6.0f `n`i''
+
+ di in blue _col(`col') "{text:`n'}" _c
+ local col = `col'+10
+
+ local a : di %6.2f `al`i''
+ if `a' < `alpha' {
+ di _col(`col') "{error:`a'} " _c
+ }
+ else di _col(`col') "{text:`a'}" _c
+
+ local col = `col'+10
+ local d : di %6.2f `delt`i''
+ if `d' < `delta' {
+ di _col(`col') "{error:`d'} " _c
+ }
+ else di _col(`col') "{text:`d'}" _c
+
+ local col = `col'+10
+ local ht : di %6.2f `h`i''
+ if `ht' < `h' {
+ di _col(`col') "{error:`ht'} " _c
+ }
+ else di _col(`col') "{text:`ht'}" _c
+
+ local col = `col'+8
+ local m : di %8.2f `min`i''
+ if `m' < `hjmin' {
+ di _col(`col') "{error:`m'} " _c
+ di "{text:(item `itmin`i'')}" _c
+ }
+ else di _col(`col') "{text:`m'}" _c
+
+ di
+ local `++i'
+}
+
+end
+
+/* descitems */
+
+capture program drop descitems
+program descitems
+syntax varlist, PARTition(numlist integer >0)
+local i = 1
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+foreach var in `varlist' {
+ qui replace `var' = round(`var')
+}
+
+local lev = ""
+foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ foreach l in `levels' {
+ if strpos("`lev'","`l'") == 0 {
+ local lev `lev' `l'
+ }
+ }
+}
+
+_qsort_index `lev'
+local lev = r(slist1)
+
+local i = 1
+matrix d = J(`nbvars',4,.)
+
+foreach var in `varlist'{
+ qui count if missing(`var')
+ local ct=r(N)
+
+ local tx`i'=`ct'/_N
+ matrix d[`i',1] = `tx`i''
+ local `i++'
+}
+
+matrix rownames d = `varlist'
+matrix colnames d = "missing" "alpha" "Hj"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ qui capture alpha `liste', asi item std
+
+ mat a = r(Alpha)
+ mat at = a'
+
+ qui capture loevh `liste', pairwise pair
+ matrix e = r(loevHj)
+ matrix et = e'
+
+ //matrix ns = r(nbHjkNS)
+ //matrix nst = ns'
+
+
+ matrix pval = r(pvalHjk)
+ forvalues c = 1/`x' {
+ forvalues r = 1/`x' {
+ if pval[`r',`c']>0.05 {
+ local ns`r' = `ns`r''+1
+ }
+ else local ns`r' = `ns`r''+0
+ }
+ }
+
+
+ foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+ }
+ matrix nst = J(`nbitems',1,0)
+ local r = 1
+ forvalues j = `y'/`s'{
+ matrix nst[`j',1]=`ns`r''
+ local `r++'
+ }
+
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',2] = at[`k',1]
+ matrix d[`j',3] = et[`k',1]
+ matrix d[`j',4] = `ns`k''
+
+ }
+ local `i++'
+ local y = `s'+1
+
+ forvalues j = 1/21{
+ local ns`j' = 0
+ }
+}
+
+
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",8)
+ local `++i'
+}
+
+local dec = 10
+local col = `dec'
+
+
+local minm = 999
+local maxm = -999
+foreach mod in $categories {
+ if `mod' < `minm' local minm = `mod'
+ if `mod' > `maxm' local maxm = `mod'
+}
+
+local b = `maxm'-`minm'+1
+
+local i = 1
+local j = 1
+local y = 1
+
+di in blue _col(`dec') "{bf:Missing}" _c
+local col = `col'+11
+di in blue _col(`=`col'+2') "{bf:N}" _c
+
+local col = `col'+9
+di _col(`col') "{bf:Response categories}" _c
+local col = `dec'+18+8*`b'
+di _col(`col') "{bf:Alpha}" _c
+local col = `col'+9
+di _col(`col') "{bf:Loevinger}" _c
+local col = `col'+12
+di _col(`col') "{bf:Number of}"
+
+local col = `dec'-1
+di _col(`col') "{bf:data rate}" _c
+local col = `dec'+18
+
+forvalues m = `minm'/`maxm' {
+ di _col(`=`col'+2') "`m'" _c
+ local col = `col'+8
+}
+
+di as result _col(`col') "- item" _c
+local col = `col'+10
+di as result _col(`col') "Hj coeff" _c
+local col = `col'+12
+di as result _col(`col') "NS Hjk"
+
+local ch = `dec'+18+8*`b'+29
+di "{hline `ch'}"
+
+local i = 1
+foreach x in `varlist' {
+ local varo`i' = "`x'"
+ local `++i'
+}
+
+local y = 1
+foreach p in `partition' {
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ local col = `dec'
+ di "{bf:`var`z''}" _c
+ local t = d[`z',1]
+ local t : di %8.2f `t'*100
+ di _col(`col') "{text:`t'%}" _c
+ qui count if missing(`varo`z'')
+ local m = r(N)
+ local N = _N-`m'
+ local N : di %4.0f `N'
+ local col = `col'+10
+ di _col(`col') "{text:`N'}" _c
+
+ local col = `col'+8
+ forvalues m = `minm'/`maxm' {
+ qui count if round(`varo`z'') == `m'
+ local n = r(N)
+ if `m' == `maxm' & round(`varo`z'')>`maxm' & `varo`z''!=.{
+ local n = `n' + 1
+ }
+ if `m' == `minm' & round(`varo`z'')<`minm' & `varo`z''!=.{
+ local n = `n' + 1
+ }
+ qui count if `varo`z'' != .
+ local d = r(N)
+ local e = `n'/`d'
+ local e : di %4.2f `e'*100
+ if `e' != 0 di _col(`=`col'-1')"{text:`e'%}" _c
+ else di _col(`=`col'-1')"{text: -}" _c
+ local col = `col'+8
+ }
+ local a = d[`z',2]
+ local a : di %4.2f `a'
+ di _col(`=`col'+1') "{text:`a'}" _c
+ local h = d[`z',3]
+ local h : di %5.2f `h'
+ local col = `col'+10
+ di _col(`=`col'+3') "{text:`h'}" _c
+ local ns = d[`z',4]
+ local ns : di %2.0f `ns'
+ local col = `col'+11
+ di _col(`=`col'+7') "{text:`ns'}"
+
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di "{dup `ch':-}"
+}
+end
+
+
+capture program drop graphs
+program graphs
+syntax varlist, PARTition(numlist integer >0)
+
+local P:word count `partition'
+local html = "${html}"
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+if "$compscore" == "stand" local w = 10
+if "$compscore" == "sum" local b = 10
+if "$compscore" == "mean" local w = 0.5
+
+
+
+
+if "`html'"!="" {
+ //set graphics off
+ foreach s in $scorename {
+ qui local saving "saving(`c(tmpdir)'/`html'_`s',replace) nodraw"
+ qui hist `s', name(`s',replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b') `saving'
+ qui graph use `c(tmpdir)'/`html'_`s'.gph
+ qui graph save `c(tmpdir)'/`html'_`s'.gph, replace
+ //di ""
+
+ }
+ //set graphics on
+
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_group,replace) nodraw"
+ qui gr combine $scorename, name(group,replace) title("Distribution of scores") `saving'
+ qui graph use `c(tmpdir)'/`html'_group.gph
+ qui graph save `c(tmpdir)'/`html'_group.gph, replace
+ //di ""
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_scores,replace) nodraw"
+ qui biplot $scorename, name("Biplot_scores",replace) norow std title("Correlations between scores") xtitle("") ytitle("") `saving'
+ qui graph use `c(tmpdir)'/`html'_scores.gph
+ qui graph save `c(tmpdir)'/`html'_scores.gph, replace
+ //di ""
+}
+
+else {
+ set graphics off
+ foreach s in $scorename {
+ qui local saving "saving(${dirsave}/Histograms_scores_`s',replace) nodraw"
+
+ qui hist `s', name("`s'",replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b') `saving'
+ }
+ set graphics on
+
+ qui local saving "saving(${dirsave}/Histograms_scores,replace) nodraw"
+
+ gr combine $scorename, name("Histograms_scores",replace) `saving'
+ if ("$filessave"!="") qui graph save ${dirsave}/Histograms_scores.gph, replace
+
+ qui local saving "saving(${dirsave}/biplot_scores,replace) nodraw"
+
+ capture biplot $scorename, name("Biplot_scores",replace) norow std title("") xtitle("") ytitle("") `saving'
+ if ("$filessave"!="") qui graph save ${dirsave}/Biplot_scores.gph, replace
+
+}
+
+
+
+capture biplot `varlist', name("temp",replace) norow std nograph
+
+mat a = r(V)
+
+tempvar a1 a2
+mat colnames a = `a1' `a2'
+svmat a, names(col)
+
+tempvar mina1 mina2 maxa1 maxa2
+egen `mina1' = min(`a1')
+egen `mina2' = min(`a2')
+egen `maxa1' = max(`a1')
+egen `maxa2' = max(`a2')
+local mina1 = `mina1'
+local mina2 = `mina2'
+local maxa1 = `maxa1'+1.4
+local maxa1x = `maxa1'+0.3
+local maxa2 = `maxa2'
+
+local colors = "red blue black green ebblue mint erose orange maroon magenta mint gray teal navy olive sienna"
+local i = 1
+foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+}
+
+local i = 1
+local y = 1
+local c = 1
+local bas = `maxa2'+0.2
+local droite = max(`maxa1',0.2)
+
+foreach x in `partition' {
+ tokenize $scorename
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues j=`y'/`s' {
+ local a = `a1'[`j']
+ local b = `a2'[`j']
+ local call `call' || pcarrowi 0 0 `b' `a' "`var`j''", mlabcolor(`col`i'') color(`col`i'') head
+ }
+ local bas = `bas'-0.2
+ local call `call' text(`bas' `droite' "``i''", size(3) color(`col`i'')) /*`bas' `droite' "``i''", mlabcolor("`r' `g' `b'")*/
+ local `++i'
+ local y = `s'+1
+ local `++c'
+}
+
+
+if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_items,replace) nodraw"
+ qui twoway `call' name("items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) title("Correlations between items") xtitle("") ytitle("") xsize(`xsize') ysize(`ysize') `saving'
+ qui graph use `c(tmpdir)'/`html'_items.gph
+ qui graph save `c(tmpdir)'/`html'_items.gph, replace
+ //di ""
+}
+else {
+ qui twoway `call' name("Biplot_items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) xtitle("") ytitle("")
+ if ("$filessave"!="") qui graph save ${dirsave}/Biplot_items.gph, replace
+
+}
+
+
+
+end
+
+/* convdiv */
+
+capture program drop convdiv
+program convdiv
+syntax varlist, PARTition(numlist integer >0) [TCONVdiv(real 0.4) convdivboxplots]
+preserve
+
+//qui set autotabgraphs on
+
+
+
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+local P:word count `partition'
+local cptdiv = 0
+local cptconv = 0
+
+if ${exist} != 1 {
+
+ qui detect `varlist', partition(`partition')
+
+ matrix A = r(Corrrestscores)
+ matrix B = r(Corrscores)
+
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ matrix B[`z',`i'] = A[`z',`i']
+ }
+ local `i++'
+ local y = `s'+1
+ }
+
+ matrix colnames B = $scorename
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix}"
+ di "{hline 105}"
+ di
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ /*if "${html}" != "" {
+ di ""
+ di _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di in red _col(`col') "{bf:`t'}" _c
+ //}
+
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{bf:`t'}" _c
+ //}
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ /*if "${html}" != "" {
+ di ""
+ di in red _col(`col') "`t'" _c
+ di ""
+ }*/
+ //else {
+ di in red _col(`col') "`t'" _c
+ //}
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{text:`t'}"_c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{text:`t'}"_c
+ //}
+
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di as text "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+
+}
+
+else if ${exist} == 1 {
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix (without rest-scores)}"
+ di "{hline 105}"
+ di
+
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ qui corr $scorename `varlist'
+ matrix c = r(C)
+ matrix B = c[`=`P'+1'..`nbvars'+`P',1..`P']
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ di in red _col(`col') "{bf:`t'}" _c
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ di _col(`col') "{bf:`t'}" _c
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ di in red _col(`col') "`t'" _c
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ di as text _col(`col') "{text:`t'}"_c
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+}
+
+if "`convdivboxplots'" != "" {
+
+ if "${html}" != "" {
+ local html = "${html}"
+ di "
"
+ di ""
+
+
+ local colors = "red blue green orange maroon magenta ebblue mint erose gray teal navy olive sienna"
+ local i = 1
+ foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+ }
+
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`col`j'') lcolor(`col`j'')) marker(`j', mcolor(`col`j''))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_Conv_div_``h'',replace) nodraw"
+ qui graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black)) `saving'
+ qui graph use `c(tmpdir)'/`html'_Conv_div_``h''.gph
+ qui graph save `c(tmpdir)'/`html'_Conv_div_``h''.gph, replace
+
+ di "
"
+
+
+
+ //qui set autotabgraphs on
+ }
+ di "
"
+ di ""
+ }
+
+ else {
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`color') lcolor(`color')) marker(`j', mcolor(`color'))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+ di "ok1"
+ graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black))
+ di "ok2"
+ if ("$filessave"!="") qui graph save ${dirsave}/Conv_div_``h''.gph, replace
+ qui set autotabgraphs on
+ }
+ }
+}
+
+
+local t : di %5.3f `tconvdiv'
+local p1 = (`nbvars'-`cptconv')/`nbvars'*100
+local p1 : di %4.1f `p1'
+local p2 = (`nbvars'-`cptdiv')/`nbvars'*100
+local p2 : di %4.1f `p2'
+
+di
+di as result "Convergent validity:" _c
+di as text " `=`nbvars'-`cptconv''/`nbvars' items (`p1'%) have a correlation coefficient with the score of "
+di _col(22) "their own dimension greater than `t'"
+di
+di as result "Divergent validity:" _c
+di as text " `=`nbvars'-`cptdiv''/`nbvars' items (`p2'%) have a correlation coefficient with the score"
+di _col(22) "of their own dimension greater than those computed with other scores."
+
+end
+
+/* cfa */
+
+capture program drop cfa
+program cfa,rclass
+syntax varlist, PARTition(numlist integer >0) [CFAMethod(string) cfasb CFAStand CFACov(string) CFARmsea(real -999) CFACfi(real -999) CFAOR CFANOCOVDim]
+preserve
+
+
+
+
+if "`cfasb'"!="" & `cfacfi'!=-999 {
+ di in red "You cannot use both cfasb and cfacfi()"
+ exit 119
+}
+
+if "`cfasb'"!="" & `cfarmsea'!=-999 {
+ di in red "You cannot use both cfasb and cfarmsea()"
+ exit 119
+}
+
+
+
+if `cfarmsea' == -999{
+ local cfarmsea
+ //di in red "error in cfaautormsea option : you must specify a value"
+ //exit 119
+}
+if `cfacfi' == -999{
+ local cfacfi
+ //di in red "error in cfaautocfi option : you must specify a value"
+ //exit 119
+}
+
+local nbvars:word count `varlist'
+local P:word count `partition'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+/*
+if "`cfarmsea'" != "" & "`cfacov'" != "" {
+ di in red "You cannot use both cfacov() and cfarmsea"
+ exit 119
+}
+if "`cfacfi'" != "" & "`cfacov'" != "" {
+ di in red "You cannot use both cfacov() and cfacfi"
+ exit 119
+}
+*/
+if "`cfacov'" != "" {
+
+ lstrfun v, subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ lstrfun s, subinstr("`cfacov'","* ","*",.)
+ lstrfun s, subinstr("`s'"," *","*",.)
+ lstrfun s, subinstr("`s'","*","*e.",.)
+ lstrfun f, subinstr("`s'"," "," e.",.)
+ local g e.`f'
+ lstrfun g , lower("`g'")
+ local covs `g'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = lower("`x'")
+ qui rename `x' `var`i''
+ local `++i'
+}
+
+local upscorename = upper("$scorename")
+
+local i = 0
+local y = 1
+tokenize `upscorename'
+foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ local a = "(``i'' -> `liste')"
+ local zz `zz' `a'
+
+ local y = `s'+1
+}
+
+if "`cfamethod'" == "" local cfamethod = "ml"
+
+if "`cfamethod'" != "ml" & "`cfamethod'" != "mlmv" & "`cfamethod'" != "adf" {
+ di "`cfamethod'"
+ di in red "option cfamethod incorrectly specified (choose among ml, mlmv and adf)."
+ error 198
+}
+
+if "`cfastand'" != "" local cfastand = "stand"
+
+if "`cfasb'" != "" {
+ local cfasb = "vce(sbentler)"
+ local sb = "_sb"
+}
+
+di as result "{hline 105}"
+di "{bf:Confirmatory factor analysis}"
+di as result "{hline 105}"
+
+local exitloop = 0
+foreach v in `varlist' {
+ local low = lower("`v'")
+ qui su `low'
+ local range = r(max)-r(min)+1
+ if `range' < 5 & "`cfamethod'"=="ml"{
+ local message "Warning: some items have less than 5 response categories. If multivariate normality assumption does not hold, maximum likelihood estimation might not be appropriate. Consider using cfamethod(adf)."
+ continue, break
+ }
+ else if `range' >= 5 & `range' < 7 & "`cfamethod'"=="ml" & "`cfasb'" == "" {
+ local message "Warning: some items have less than 7 response categories. If multivariate normality assumption does not hold, maximum likelihood estimation might not be appropriate. Consider using cfasb in order to apply Satorra-Bentler adjustment or using cfamethod(adf)."
+ continue
+ }
+}
+
+di in red "`message'"
+
+local ii = 1
+local s
+local stop = 0
+
+while (`ii' == 1 | "`covsi'" != "") & `stop'!=1 {
+ if `ii' == 1 & ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ di
+ di as text "step 1 (model without covariances between errors)"
+ }
+ if "`covs'" != "" & ("`cfarmsea'"!="" | "`cfacfi'"!="") di _n "{bf:step `ii':} {text:`covsi'}"
+ local covsi
+
+ if "`cfanocovdim'" == "" {
+ qui sem `zz', method(`cfamethod') `cfastand' cov(`covs') iterate(50) `cfasb'
+ }
+ else {
+ qui sem `zz', method(`cfamethod') `cfastand' cov(`covs') iterate(50) covstruct(_lexogenous, diagonal) `cfasb'
+ }
+
+ /* factor loadings */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix a = a\b
+ }
+
+ /* standard error factor loadings*/
+
+ matrix r = r(table)
+ matrix r = r[2,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sef = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sef = sef\b
+ }
+
+
+ /* intercepts */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a2 = r[2,1]
+ forvalues i=4(2)`n' {
+ matrix b = r[`i',1]
+ matrix a2 = a2\b
+ }
+
+
+ /* standard error intercepts*/
+
+ matrix r = r(table)
+ matrix r = r[2,2...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sei = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sei = sei\b
+ }
+
+ //mat li sei
+ /* error variances */
+
+ local m = `n'+1
+ matrix r = r(table)
+ matrix r = r[1,`m'...]
+ matrix r = r'
+
+ matrix a3 = r[1,1]
+ forvalues i=2/`nbvars' {
+ matrix b = r[`i',1]
+ matrix a3 = a3\b
+ }
+
+ /* variance of dimensions*/
+
+ matrix r = r(table)
+ local n = `nbvars'*3+1
+ matrix r = r[1,`n'...]
+ matrix r = r'
+
+ matrix var = r[1,1]
+ forvalues i=2/`P' {
+ matrix b = r[`i',1]
+ matrix var = var\b
+ }
+
+ //mat li var
+
+ /* Covariances between dimensions */
+
+ matrix r = r(table)
+ local P:word count `partition'
+ if `P' > 1 {
+ local one = 1
+ }
+ else{
+ local one = 0
+ }
+ local n = `nbvars'*3+`one'+`P'
+
+
+ if "`cfanocovdim'" == "" {
+ //mat li r
+ matrix r = r[1,`n'...]
+ //mat li r
+ matrix c = J(`P',`P',.)
+
+ local nbcov:word count `cfacov'
+ local `++nbcov'
+
+ local k = `nbcov'
+ forvalues c = 1/`P' {
+ forvalues r = 2/`P' {
+ if `r'>`c' {
+ matrix c[`r',`c']=r[1,`k']
+ local `++k'
+ }
+ }
+ }
+
+ local k = 1
+ forvalues c = 1/`P' {
+ matrix c[`c',`c']=var[`k',1]
+ local `++k'
+ }
+
+ matrix rownames c = $scorename
+ matrix colnames c = $scorename
+ }
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") {
+ local stoprmsea = 0
+ local stopcfi = 0
+ if "`cfarmsea'"!="" {
+ qui estat gof
+ di "rmsea =" round(r(rmsea),0.001)
+ if r(rmsea)<=`cfarmsea' {
+ local stoprmsea = 1
+ }
+ //else local stoprmsea = 0
+ }
+ else local stoprmsea = 1
+ if "`cfacfi'"!="" {
+ qui estat gof
+ di "cfi =" round(r(cfi),0.001)
+ if r(cfi)>=`cfacfi' {
+ local stopcfi = 1
+ }
+ //else local stopcfi = 0
+ }
+ else local stopcfi = 1
+
+
+
+ /* OR */
+ if "`cfaor'"!="" {
+ if `stoprmsea'==1 | `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ /* AND */
+ if "`cfaor'"=="" {
+ if `stoprmsea'==1 & `stopcfi'==1 {
+ local stop = 1
+ }
+ }
+ }
+
+
+ if ("`cfarmsea'"!="" | "`cfacfi'"!="") & `stop'!=1 {
+ qui estat mindices, showpclass(mcons merrvar)
+ tempname mm nomcol
+ mat `mm' = r(mindices)
+
+ svmat2 `mm' , r(`nomcol') full
+ gsort - `mm'1
+
+ local nrows = rowsof(`mm')
+
+ local y = 1
+ local i = 0
+ foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues w = `y'/`s' {
+ local class_`var`w'' = `i'
+ }
+ local y = `s'+1
+ }
+
+
+ forvalues i = 1/`nrows' {
+ local tmp3=`nomcol'[`i']
+ lstrfun e, subinstr("`tmp3'","cov(","",.)
+ lstrfun e, subinstr("`e'",")","",.)
+ lstrfun e, subinstr("`e'",":_cons","",.)
+ lstrfun e, subinstr("`e'",",","*",.)
+
+ lstrfun d, subinstr("`e'",","," ",.)
+ lstrfun d, subinstr("`d'","e.","",.)
+ lstrfun d, subinstr("`d'","*"," ",.)
+
+ qui replace `nomcol' = "`d'" in `i'
+
+ local d = `nomcol'[`i']
+
+ tokenize "`d'"
+ if "`class_`1''" != "`class_`2''" {
+ qui replace `nomcol' = "" in `i'
+ }
+
+ local tmp3=`nomcol'[`i']
+
+ if "`tmp3'" != "" {
+ continue, break
+ }
+ else {
+ local e
+ }
+
+
+ }
+
+
+
+
+ local covsi `e'
+ local covs `covs' `e'
+ drop `mm'1-`nomcol'
+
+ }
+
+ if e(converged) == 0 di in red "Warning : model did not converge after 50 iterations"
+ local `++ii'
+
+}
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+local i = 1
+foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+
+}
+
+local max = 10
+local dec = `max'+5
+
+local max2 = 10
+
+local dec2 = `dec'+`max2'+5
+
+local a = e(N)
+di
+if e(converged) == 0 di in red "Warning : model did not converge after 50 iterations"
+di as result ""
+if "`covs'" != "" {
+ di as result "{bf:Covariances between errors added:} {text:`covs'}"
+ di
+}
+di "{bf:Number of used individuals: } {text:`a'}"
+di
+//di _col(`=`dec2'+17+4') "{bf:Estimation:}"
+
+
+di as result "{bf:Item}" _c
+di _col(`dec') "{bf:Dimension}" _c
+di _col(`dec2') "{bf:Factor}" _c
+di _col(`=`dec2'+14') "{bf:Standard}" _c
+di _col(`=`dec2'+28') "{bf:Intercept}" _c
+di _col(`=`dec2'+43') "{bf:Standard}" _c
+
+if "`cfastand'" == "" {
+ di _col(`=`dec2'+57') "{bf:Error}" _c
+ di _col(`=`dec2'+66') "{bf:Variance of}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+43') "{bf:error}" _c
+ di _col(`=`dec2'+55') "{bf:variance}" _c
+ di _col(`=`dec2'+67') "{bf:dimension}"
+ local h = `dec2'+76
+}
+else {
+ di _col(`=`dec2'+57') "{bf:Error}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+44') "{bf:error}" _c
+ di _col(`=`dec2'+57') "{bf:variance}"
+ local h = `dec2'+62
+}
+
+di "{hline `h'}"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ tokenize `sc'
+ di "{bf:`var`z''}"_c
+ di _col(`dec') "{bf:``i''}" _c
+ local t = a[`z',1]
+ local t : di %7.2f `t'
+ di _col(`dec2') "{text:`t'}" _c
+
+ local t = sef[`z',1]
+ local t : di %8.2f `t'
+ di _col(`=`dec2'+14') "{text:`t'}" _c
+
+ local t = a2[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+28') "{text:`t'}" _c
+
+ local t = sei[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+42') "{text:`t'}" _c
+
+ local t = a3[`z',1]
+ local t : di %11.2f `t'
+
+ if "`cfastand'" == "" & `z' == `y'{
+ di _col(`=`dec2'+52') "{text:`t'}" _c
+ local t = var[`i',1]
+ local t : di %11.2f `t'
+ di _col(`=`dec2'+66') "{text:`t'}"
+ }
+ else di _col(`=`dec2'+52') "{text:`t'}"
+ }
+ di
+ local `i++'
+ local y = `s'+1
+}
+
+qui estat gof, stats(all)
+
+
+if "`cfasb'" != "" {
+ local chi2 = r(chi2sb_ms)
+ local p = r(psb_ms)
+ local ddl = r(df_ms)
+ local ratio = `chi2'/`ddl'
+ local rmsea = r(rmsea_sb)
+ *local lb = r(lb90_rmsea)
+ *local ub = r(ub90_rmsea)
+ local nfi = 1-(r(chi2sb_ms)/r(chi2sb_bs))
+ local rni = 1-(r(chi2sb_ms)-r(df_ms))/(r(chi2sb_bs)-r(df_bs))
+ local cfi = r(cfi_sb)
+ local ifi = (r(chi2sb_bs)-r(chi2sb_ms))/(r(chi2sb_bs)-r(df_ms))
+ local mci = exp(-0.5*((r(chi2sb_ms)-r(df_ms))/(e(N)-1)))
+ local srmr = r(srmr)
+}
+
+else {
+ local chi2 = r(chi2_ms)
+ local p = r(p_ms)
+ local ddl = r(df_ms)
+ local ratio = `chi2'/`ddl'
+ local rmsea = r(rmsea)
+ local lb = r(lb90_rmsea)
+ local ub = r(ub90_rmsea)
+ local nfi = 1-(r(chi2_ms)/r(chi2_bs))
+ local rni = 1-(r(chi2_ms)-r(df_ms))/(r(chi2_bs)-r(df_bs))
+ local cfi = r(cfi)
+ local ifi = (r(chi2_bs)-r(chi2_ms))/(r(chi2_bs)-r(df_ms))
+ local mci = exp(-0.5*((r(chi2_ms)-r(df_ms))/(e(N)-1)))
+ local srmr = r(srmr)
+}
+
+if "`cfanocovdim'" == "" {
+ di
+ di "Covariances between dimensions:"
+ mat li c, nodotz noheader format(%4.2f)
+}
+
+di
+if "`cfasb'" != "" {
+ di "{bf:Goodness of fit (with Satorra-Bentler correction):}"
+}
+else {
+ di "{bf:Goodness of fit:}"
+}
+di
+
+
+
+if "${html}" != "" {
+
+di as result _col(4) "chi2" _c
+di as result _col(20) "df" _c
+di as result _col(28) "chi2/df" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI"
+
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}"
+
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+di as result _col(4) "CFI" _c
+di as result _col(15) "IFI" _c
+di as result _col(26) "MCI"
+local t : di %5.3f `cfi'
+di _col(4) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(15) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(26) "{text:`t'}"
+di as result
+}
+else {
+di as result _col(4) "chi2" _c
+di as result _col(20) "df" _c
+di as result _col(28) "chi2/df" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI" _c
+di as result _col(94) "CFI" _c
+di as result _col(104) "IFI" _c
+di as result _col(114) "MCI"
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}" _c
+local t : di %5.3f `cfi'
+di _col(92) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(102) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(112) "{text:`t'}"
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+
+}
+end
+
+
+/* repet */
+
+capture program drop repet
+program repet,rclass
+syntax varlist, PARTition(numlist integer >0) [t2(varlist) KAPpa ICKAPpa(integer 0)]
+preserve
+
+local nbvars : word count `varlist'
+
+if `ickappa' <= 0 {
+ local ickappa = ""
+}
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local P:word count `partition'
+
+if "$scores2" != "" {
+ local t:word count $scores2'
+ if `P' != `t' {
+ di in red "The number of score names given in scores2() is different from the number of scores defined"
+ exit 119
+ }
+}
+
+if "`t2'" != "" {
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local maxit = 1
+ forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `maxit' local maxit = `len'
+ }
+
+ local decit = `maxit' + 4
+ local colit = `decit'
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ if "$scores2" == "" {
+ foreach sco in $scorename {
+ *local t = "`sco'bis"
+ tempname s
+ local scorename2 `scorename2' `s'
+ }
+
+ qui calcscore `t2', scorename(`scorename2') partition(`partition') compscore(${compscore}) categories($categories)
+
+ }
+
+ else {
+ foreach sco in $scores2 {
+ local scorename2 `scorename2' `sco'
+ }
+ }
+
+ local i = 1
+ foreach var in `varlist' {
+ tokenize `t2'
+ qui kap `var' ``i''
+ local k`i' = r(kappa)
+ if "`ickappa'" != "" {
+ qui kapci `var' ``i'', reps(`ickappa')
+ local lbk`i' = r(lb_bc)
+ local ubk`i' = r(ub_bc)
+ }
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ tokenize `scorename2'
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize `sc'
+ local max = length("dimension")
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+ di "{bf:Dimension}" _c
+ di _col(`=`dec'+2') "{bf:n}" _c
+ local col = `dec'+6
+ di _col(`col') "{bf:Item}" _c
+ local col = `col'+`decit'
+
+ if "`kappa'" != "" {
+ di _col(`col') "{bf:Kappa}" _c
+ local col = `col'+10
+ if "`ickappa'" != "" {
+ di _col(`col') "{bf:95% CI for Kappa}" _c
+ local col = `col'+20
+ }
+
+ }
+
+ di _col(`=`col'+2') "{bf:ICC}" _c
+ local col = `col'+9
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ local zz = 0
+ foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ local z : word count `levels'
+ if `z' > 2 local zz = 1
+ }
+
+ if "`kappa'" != "" & "`ickappa'" != "" & `zz' == 1 {
+ local col = `dec'+`decit'+16
+ di _col(`col') "{bf:(bootstrapped)}"
+ }
+
+
+ if "`ickappa'" != "" local h = `dec'+6+`decit'+10+8+21+12+1
+ else if "`kappa'" != "" local h = `dec'+6+`decit'+10+8+21+12-20
+ else local h = `dec'+6+`decit'+10+8+21+12-29
+ di "{hline `h'}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize `sc'
+ di "{bf:``i''}" _c
+ di _col(`dec') "{text:`n`i''}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+6
+ di _col(`col') "{text:`var`y''}" _c
+
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`y''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`i''
+ local ubk : di %5.2f `ubk`i''
+ local col = `col'+11
+ di _col(`col') "{text:[`lbk' ; `ubk']}" _c
+ local col = `decit'+50
+ }
+
+ else local col = `decit'+30
+ }
+ else local col = `decit'+20
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+8
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ forvalues z = `w'/`s' {
+ local col = `dec'+6
+ di _col(`col') "{text:`var`z''}" _c
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`z''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`z''
+ local ubk : di %5.2f `ubk`z''
+ local col = `col'+11
+ di _col(`col')"{text:[`lbk' ; `ubk']}"
+ }
+ else di
+
+ }
+ else di
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+ }
+}
+
+else {
+ local i = 1
+ foreach s in $scorename {
+ tokenize $scores2
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize $scorename
+ local max = length("dimension")
+
+ local h = 1
+ foreach s in $scorename {
+ local s`h' = abbrev("`s'",10)
+ local sc `sc' `s`h''
+ local `++h'
+ }
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ di "{bf:Dimension}" _c
+ local col = `dec'
+ di _col(`col') "{bf:n}" _c
+
+
+ di _col(`=`col'+6') "{bf:ICC}" _c
+ local col = `col'+14
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ di "{hline 50}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize $scorename
+ di "{bf:``i''}" _c
+ local n : di % 4.0f `n`i''
+ di _col(`=`dec'-3') "{text:`n'}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+4
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+9
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ local `i++'
+ }
+}
+
+end
+
+
+/* kgv */
+
+capture program drop kgv
+program kgv,rclass
+syntax varlist, categ(varlist) [KGVBoxplots KGVGroupboxplots]
+
+foreach c in `categ' {
+ tempname j
+ capture encode `c', generate(`j')
+ capture confirm variable `j'
+ if _rc local j = "`c'"
+ local categ2 `categ2' `j'
+}
+
+local i = 1
+local j = 1
+local k = 0
+local max = 0
+local a : word count `categ'
+local nb:word count `varlist'
+
+di as result "{hline 105}"
+di "{bf:Known-groups validity}"
+di as result "{hline 105}"
+di
+
+foreach sco in `varlist' {
+ foreach cat in `categ2' {
+ local nblev = 0
+ local maxlen`j' = 0
+
+ qui anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ qui kwallis `sco', by(`cat')
+ local p2`i'_`j' = chi2tail(r(df), r(chi2))
+
+
+ /*local inf30 = 0
+ qui tab `cat' if `sco'!=., matcell(x)
+ local r = r(r)
+ forvalues n = 1/`r' {
+ if x[`n',1]<48 {
+ local `++inf30'
+ }
+ }
+ if `inf30' > 0 {
+ //di in red "kw"
+ kwallis `sco', by(`cat')
+ local p2`i'_`j' = chi2tail(r(df), r(chi2))
+ anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+
+ }
+ else {
+ //di in red "aov"
+ anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ }*/
+
+
+ qui levelsof `cat', local(levels)
+ local lbe : value label `cat'
+
+ foreach l of local levels {
+ qui count if `sco' !=. & `cat' == `l'
+ local `++k'
+ local eff`i'_`j'_`k' = r(N)
+
+ if "`lbe'" != "" {
+ local ll`j'_`k' : label `lbe' `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ else {
+ local ll`j'_`k' = `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ qui su `sco' if `cat' == `l'
+ local m`i'_`j'_`k' = r(mean)
+ local s`i'_`j'_`k' = r(sd)
+ local nblev = `nblev' + 1
+ }
+ if `nblev' > `max' local max = `nblev'
+ local `++j'
+ local k = 0
+ }
+ local `++i'
+ local j = 1
+}
+
+local i = 1
+foreach s in `varlist' {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+local maxs = 0
+forvalues j=1/`nb' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `maxs' local maxs = `len`j''
+}
+
+local i = 1
+local k = 0
+local j = 2
+
+foreach cat in `categ'{
+ local `++k'
+ tokenize `categ'
+ local c`k' = "``i'' ``j''"
+ local i = `i' + 2
+ local j = `j' + 2
+}
+
+
+local d = 1
+local f = 2
+forvalues h = 1/`a' {
+ if `f' > `a' local f = `f'-1
+ local j = 1
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`col') "{bf:`cat'}" _c
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+ di
+
+ local j = `d'
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`=`col'+`maxlen`j''+5') "{bf: mean }" _c
+ di "{bf: sd }" _c
+ di "{bf:p-value}" _c
+ //di "{bf:p-value (Kruskal-Wallis)}" _c
+
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+
+ local j = `d'
+ local col = `maxs'+6
+
+ di
+ di
+ local i = 1
+ local col = `maxs'+6
+
+ forvalues g = 1/`nb' {
+
+ di "{bf:`s`g''}" _c
+ forvalues k = 1/`max' {
+ forvalues j = `d'/`f' {
+
+ di _col(`col') "{bf:`ll`j'_`k''} " _c
+ if "`eff`i'_`j'_`k''" != "" di as text "(n=`eff`i'_`j'_`k'')" _c
+ local m : di %6.2f `m`i'_`j'_`k''
+ di _col(`=`col'+`maxlen`j''+10') "{text:`m'} " _c
+
+ local s : di %8.2f `s`i'_`j'_`k''
+ di "{text: `s'} " _c
+
+ if `k' == 1 {
+ local p : di %8.3f `p`i'_`j''
+ local p2 : di %4.3f `p2`i'_`j''
+ di _col(`=`col'+31') "{text:`p'} " _c
+ di _col(`=`col'+35') "{text:(KW: `p2')} " _c
+ }
+ local col = `col' + `maxlen`j'' + 5 + 40
+ }
+ di
+ local col = `maxs'+6
+
+ }
+ di
+
+ local `++i'
+
+ }
+ local d = `d'+2
+ local f = `f'+2
+ if `d' > `a' continue, break
+ di
+}
+
+if "`kgvboxplots'" != "" {
+ local html = "${html}"
+ if "`html'" != "" {
+ di "
"
+ di ""
+ if "`kgvgroupboxplots'" != "" {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") nodraw
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph save `c(tmpdir)'/`html'_kgv`s'.gph, replace
+
+
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv,replace) nodraw"
+ qui gr combine `g', name(kgv,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv.gph
+ qui graph save `c(tmpdir)'/`html'_kgv.gph, replace
+ //di "
"
+
+ }
+ else {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'")
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph save `c(tmpdir)'/`html'_kgv`s'.gph, replace
+ //di "
"
+
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ }
+ di "
"
+ di ""
+
+ }
+ else {
+ if "`kgvgroupboxplots'" != "" {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')") nodraw
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ gr combine `g', name(Known_groups_validity,replace)
+ if ("$filessave"!="") qui graph save ${dirsave}/Known_groups_validity.gph, replace
+
+ }
+ else {
+ local cc = 1
+ foreach c in `categ' {
+ local k = 1
+ foreach s in `varlist' {
+ local pp = round(`p`k'_`cc'',0.001)
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c' (p=`pp')")
+ if ("$filessave"!="") qui graph save ${dirsave}/Known_groups_validity_`c'_`s'.gph, replace
+ local g `g' `s'_`c'
+ local k = `k'+1
+ }
+ local cc = `cc'+1
+ }
+ }
+ }
+}
+
+end
+
+
+/* conc */
+
+capture program drop conc
+program conc,rclass
+syntax varlist, comp(varlist) [tconc(real 0.4)]
+
+di as result "{hline 105}"
+di "{bf:Concurrent validity}"
+di as result "{hline 105}"
+di
+
+local n : word count `varlist'
+local p : word count `comp'
+
+matrix m = J(`n',`p',.)
+matrix rownames m = `varlist'
+matrix colnames m = `comp'
+local r = 1
+
+foreach i in `varlist' {
+ local c = 1
+ foreach j in `comp' {
+ qui corr `i' `j'
+ mat e = r(C)
+ local f = e[2,1]
+ mat m[`r',`c'] = `f'
+ local `++c'
+ }
+ local `++r'
+}
+
+tokenize `varlist'
+local maxv = length("`1'")
+forvalues i=1/`n' {
+ local lenv = length("``i''")
+ if `lenv' > `maxv' local maxv = `lenv'
+}
+
+local decv = `maxv'+6
+
+tokenize `comp'
+local maxc = length("`1'")
+forvalues i=1/`p' {
+ local lenc = length("``i''")
+ if `lenc' > `maxc' local maxc = `lenc'
+}
+
+local decc = `maxc'+4
+
+local col = `decv'
+foreach c in `comp' {
+ di as result _col(`col') "`c'" _c
+ local col = `col'+`decc'
+}
+di
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+forvalues i=1/`n' {
+ di as result "`var`i''" _c
+ local col = `decv'
+ forvalues j=1/`p' {
+ local t = m[`i',`j']
+ if `t' > `tconc' | `t' < -`tconc' {
+ di as result _col(`=`col'-1') %5.2f `t' _c
+ }
+ else di as text _col(`=`col'-1') %5.2f `t' _c
+ local col = `col'+`decc'
+ }
+ di
+}
+
+capture restore, not
+end
+
diff --git a/Modules/ado/personal/v/validscale.dlg b/Modules/ado/personal/v/validscale.dlg
new file mode 100644
index 0000000..48f9654
--- /dev/null
+++ b/Modules/ado/personal/v/validscale.dlg
@@ -0,0 +1,426 @@
+/*
+ valid.dlg
+*/
+
+VERSION 12.1
+
+POSITION . . 590 280
+
+DIALOG main, label("Validation") tabtitle("General")
+BEGIN
+ TEXT tx_var 10 10 250 ., ///
+ label("Items used for calculating score")
+ VARLIST vl_var @ +20 280 ., ///
+ label("Variables")
+
+ TEXT tx_n 10 +28 200 ., ///
+ label("Number of items")
+
+ EDIT ed_n @ +20 40 ., ///
+ label("number") ///
+ numonly
+
+ TEXT tx_score 110 58 180 ., ///
+ label("Name of the dimension (optional)")
+ EDIT ed_score 130 +20 100 ., ///
+ option(scorename) ///
+
+ BUTTON bt_add 260 75 32 22, ///
+ label("Add") ///
+ onpush(script az) ///
+
+ GROUPBOX gb_1 5 120 284 140,
+
+ TEXT tx_v 10 +10 100 ., ///
+ label("Items used")
+ VARLIST ed_v @ +20 250 ., ///
+ label("Items used")
+
+ TEXT tx_p @ +20 100 ., ///
+ label("Partition")
+
+ EDIT ed_p @ +20 150 ., ///
+ label("Partition") ///
+ option(partition) ///
+ tooltip("Defines the number of items in each dimension")
+ TEXT tx_s @ +20 . ., ///
+ label("Names of the dimensions (optional)")
+ EDIT ed_s @ +20 150 ., ///
+ label("Names of the dimensions") ///
+ option(scorename)
+
+
+ GROUPBOX gb_calc 330 13 245 90, ///
+ label("Calculation of scores")
+
+ RADIO rb_mean +10 +20 100 ., first label("Mean") ///
+ default(1)
+
+
+ RADIO rb_sum @ +20 100 ., label("Sum")
+
+
+ RADIO rb_stand @ +20 140 ., last label("Standardized scores") ///
+ tooltip("Set score from 0 to 100")
+
+ GROUPBOX gb_opt 330 120 245 140, ///
+ label("Options")
+
+ CHECKBOX ck_imp +10 +20 -20 ., ///
+ option(imp) ///
+ label("Imputing missing data") ///
+ onclickon(main.ck_nor.enable) ///
+ onclickoff(main.ck_nor.disable) ///
+ default(1)
+
+ CHECKBOX ck_nor +145 @ -20 ., ///
+ option(noround) ///
+ label("Do not round") ///
+ tooltip("Do not round imputed values")
+
+ CHECKBOX ck_desc 340 +28 -20 ., ///
+ option(descitems) ///
+ label("Description of items") ///
+ default(0)
+
+ CHECKBOX ck_graphs 340 +28 -20 ., ///
+ option(graphs) ///
+ label("Display graphs") ///
+ default(0) ///
+ tooltip("Display histogram of items, biplot of dimensions and biplot of items")
+
+ /*
+ CHECKBOX ck_cfa 340 +28 -20 ., ///
+ option(cfa) ///
+ label("Confirmatory factor analysis") ///
+ default(1)
+
+
+ CHECKBOX ck_conv @ +28 +10 ., ///
+ option(conv_div) ///
+ label("Convergent/discriminant validity") ///
+ default(1)
+ */
+
+END
+
+
+DIALOG cfa, tabtitle("Confirmatory factor analysis")
+BEGIN
+
+ CHECKBOX ck_cfa 10 10 200 ., label("Display confirmatory factor analysis") ///
+ option(cfa) ///
+ onclickon(script cfa_ck_cfa_on) ///
+ onclickoff(script cfa_ck_cfa_off)
+
+ GROUPBOX gb_cfa 10 +30 220 90 , ///
+ label("Estimation method:")
+
+ RADIO rb_ml +10 +24 110 ., first label("Maximum likelihood") ///
+ default(1)
+
+ RADIO rb_mlmv @ +20 200 ., label("Maximum likelihood with missing values")
+
+ RADIO rb_adf @ +20 140 ., last label("Asymptotic distribution free")
+
+
+ CHECKBOX ck_stand 14 +34 140 ., label("Standardize coefficients") ///
+ option(cfastand)
+
+END
+
+
+DIALOG conv, tabtitle("Convergent/divergent validity")
+BEGIN
+
+ CHECKBOX ck_conv_div 10 10 220 ., ///
+ label("Display convergent/divergent validity") ///
+ option(convdiv) ///
+ onclickon(script conv_ck_conv_on) ///
+ onclickoff(script conv_ck_conv_off)
+
+ TEXT tx_conv1 10 +26 220 ., ///
+ label("Correlations between item and its own score")
+ TEXT tx_conv2 @ +17 @ ., ///
+ label("below this value will be highlighted")
+ EDIT ed_conv 250 42 35 ., ///
+ default(0.4) ///
+ option(tconvdiv) ///
+ numonly
+
+ CHECKBOX ck_conv 10 +42 170 ., ///
+ option(convdivboxplots) ///
+ label("Display boxplots of correlations") ///
+ default(1)
+
+END
+
+
+DIALOG rel, tabtitle("Reliability")
+BEGIN
+
+ TEXT tx_rel_a 10 10 350 ., ///
+ label("Cronbach's alpha below this value will be highlighted")
+ EDIT ed_rel_a 320 @ 35 ., ///
+ default(0.7) ///
+ option(alpha) ///
+ numonly
+
+ TEXT tx_rel_d 10 +30 350 ., ///
+ label("Ferguson's delta below this value will be highlighted")
+ EDIT ed_rel_d 320 @ 35 ., ///
+ default(0.9) ///
+ option(delta) ///
+ numonly
+
+ TEXT tx_rel_H 10 +30 380 ., ///
+ label("Loevinger's H coefficient below this value will be highlighted")
+ EDIT ed_rel_H 320 @ 35 ., ///
+ default(0.3) ///
+ option(h) ///
+ numonly
+
+ TEXT tx_rel_h 10 +30 380 ., ///
+ label("Loevinger's Hj coefficient below this value will be highlighted")
+ EDIT ed_rel_h 320 @ 35 ., ///
+ default(0.3) ///
+ option(hjmin) ///
+ numonly
+
+END
+
+
+
+DIALOG rep, tabtitle("Reproducibility")
+BEGIN
+
+ TEXT tx_rep 10 10 250 ., ///
+ label("Items used for calculating scores (time 2)")
+ VARLIST vl_rep @ +20 @ ., ///
+ option(repet) ///
+ label("Items time 2")
+
+ CHECKBOX ck_kappa @ +35 100 ., ///
+ label("Kappa statistic") ///
+ option(kappa) ///
+ onclickon(script rep_ck_kappa_on) ///
+ onclickoff(script rep_ck_kappa_off)
+
+ CHECKBOX ck_ickappa @ +25 280 ., ///
+ label("Confidence interval for kappa") ///
+ onclickon(script rep_ck_ickappa_on) ///
+ onclickoff(script rep_ck_ickappa_off)
+
+ TEXT tx_boot @ +25 220 ., ///
+ label("Number of bootstrap replications to estimate")
+
+ TEXT tx_boot2 @ +15 220 ., ///
+ label("confidence interval (if items are polytomous):")
+
+ SPINNER sp_ickappa +220 -7 45 ., ///
+ label("Number of bootstrap replications") min(1) max(1000) ///
+ default(20) ///
+ option(ickappa)
+
+
+END
+
+
+DIALOG kgv, tabtitle("Known-groups validity")
+BEGIN
+ TEXT tx_kgv 10 10 250 ., ///
+ label("Select qualitative variables for known-groups validity")
+ VARLIST vl_kgv @ +28 250 ., ///
+ option(kgv) ///
+ label("kgv")
+
+ CHECKBOX ck_kgv @ +25 150 ., ///
+ label("Display boxplots") ///
+ option(kgvboxplots) ///
+ default(0) ///
+ onclickon(kgv.ck_kgv_group.enable) ///
+ onclickoff(kgv.ck_kgv_group.disable)
+
+ CHECKBOX ck_kgv_group @ +25 190 ., ///
+ label("Group boxplots in one graph") ///
+ option(kgvgroupboxplots) ///
+ default(0)
+
+END
+
+
+DIALOG conc, tabtitle("Concurrent validity")
+BEGIN
+ TEXT tx_conc 10 10 186 ., ///
+ label("Select scores from other scales")
+ VARLIST vl_conc @ +28 250 ., ///
+ option(conc) ///
+ label("conc")
+
+ TEXT tx_t_conc @ +30 350 ., ///
+ label("Correlations above this value will be highlighted (absolute value)")
+
+ EDIT ed_t_conc 320 @ 30 ., ///
+ default(0.4) ///
+ option(tconc) ///
+ numonly
+
+END
+
+
+PROGRAM az
+BEGIN
+ main.ed_score.withvalue main.ed_s.append "@ "
+ main.vl_var.withvalue main.vl_v.append "@ "
+ main.ed_n.withvalue main.ed_p.append "@ "
+
+ main.vl_var.setvalue ""
+ main.ed_n.setvalue ""
+ main.ed_score.setvalue ""
+END
+
+
+
+
+SCRIPT rep_ck_kappa_on
+BEGIN
+ rep.ck_ickappa.enable
+END
+
+SCRIPT rep_ck_kappa_off
+BEGIN
+ rep.ck_ickappa.disable
+ rep.sp_ickappa.disable
+ rep.ck_ickappa.setoff
+END
+
+SCRIPT rep_ck_ickappa_on
+BEGIN
+ rep.sp_ickappa.enable
+ rep.tx_boot.enable
+ rep.tx_boot2.enable
+END
+
+SCRIPT rep_ck_ickappa_off
+BEGIN
+ rep.sp_ickappa.disable
+ rep.sp_ickappa.setdefault 0
+ rep.tx_boot.disable
+ rep.tx_boot2.disable
+END
+
+SCRIPT cfa_ck_cfa_on
+BEGIN
+ cfa.gb_cfa.enable
+ cfa.rb_ml.enable
+ cfa.rb_mlmv.enable
+ cfa.rb_adf.enable
+ cfa.ck_stand.enable
+END
+
+SCRIPT cfa_ck_cfa_off
+BEGIN
+ cfa.gb_cfa.disable
+ cfa.rb_ml.disable
+ cfa.rb_mlmv.disable
+ cfa.rb_adf.disable
+ cfa.ck_stand.disable
+END
+
+SCRIPT conv_ck_conv_on
+BEGIN
+ conv.tx_conv1.enable
+ conv.tx_conv2.enable
+ conv.ed_conv.enable
+ conv.ck_conv.enable
+END
+
+SCRIPT conv_ck_conv_off
+BEGIN
+ conv.tx_conv1.disable
+ conv.tx_conv2.disable
+ conv.ed_conv.disable
+ conv.ck_conv.disable
+END
+
+OK ok1, label("OK")
+CANCEL can1, label("Cancel")
+SUBMIT sub1, label("Submit")
+HELP hlp1, view("help valid")
+RESET res1
+COPY copy1
+
+PROGRAM command
+BEGIN
+ put "valid "
+ require main.ed_v
+ put main.ed_v
+ require main.ed_p
+
+ beginoptions
+ optionarg main.ed_p
+ optionarg main.ed_s
+ option main.ck_imp
+ option main.ck_nor
+ option main.ck_desc
+ option main.ck_graphs
+
+ if main.rb_mean{
+ put " calcmethod("
+ put "mean"
+ put ")"
+ }
+
+ if main.rb_sum{
+ put " calcmethod("
+ put "sum"
+ put ")"
+ }
+
+ if main.rb_stand{
+ put " calcmethod("
+ put "stand"
+ put ")"
+ }
+
+ option cfa.ck_cfa
+
+ if cfa.rb_ml{
+ put " cfamethod("
+ put "ml"
+ put ")"
+ }
+
+ if cfa.rb_mlmv{
+ put " cfamethod("
+ put "mlmv"
+ put ")"
+ }
+
+ if cfa.rb_adf{
+ put " cfamethod("
+ put "adf"
+ put ")"
+ }
+
+ option cfa.ck_stand
+ option conv.ck_conv_div
+ optionarg conv.ed_conv
+ option conv.ck_conv
+ optionarg rel.ed_rel_a
+ optionarg rel.ed_rel_d
+ optionarg rel.ed_rel_H
+ optionarg rel.ed_rel_h
+ optionarg rep.vl_rep
+ option rep.ck_kappa
+ optionarg rep.sp_ickappa
+ optionarg kgv.vl_kgv
+ option kgv.ck_kgv
+ option kgv.ck_kgv_group
+ optionarg conc.vl_conc
+ optionarg conc.ed_t_conc
+
+ endoptions
+
+
+END
diff --git a/Modules/ado/personal/v/validscale.hlp b/Modules/ado/personal/v/validscale.hlp
new file mode 100644
index 0000000..4408bad
--- /dev/null
+++ b/Modules/ado/personal/v/validscale.hlp
@@ -0,0 +1,143 @@
+{smcl}
+{* 2013}{...}
+{hline}
+help for {hi:validscale}{right:Bastien Perrot}
+{hline}
+
+{title:Syntax}
+
+{p 8 14 2}{cmd:validscale} {it:varlist}, {opt part:ition}({it:numlist}) [{it:options}]
+
+{p 4 4 2}{it:varlist} contains the variables (items) used to compute the scores. The first items of {it:varlist} compose the first dimension, the following items define the second dimension, and so on.
+
+{p 4 4 2}{cmd:partition} allows defining in {it:numlist} the number of items in each dimension.
+
+
+{synoptset 20 tabbed}{...}
+{synopthdr}
+{synoptline}
+{syntab:Options}
+{synopt : {opt scoren:ame(string)}}define the names of the dimensions{p_end}
+{synopt : {opt scores(varlist)}}use scores from the dataset{p_end}
+{synopt : {opt mod:alities(numlist)}}define minimum and maximum response categories for the items{p_end}
+{synopt : {opt imp:ute(method)}}impute missing item responses{p_end}
+{synopt : {help validscale##impute_options:{it:impute_options}}}options for imputation of missing data {p_end}
+{synopt : {opt comps:core(method)}}define how scores are computed{p_end}
+{synopt : {opt desc:items}}display a descriptive analysis of items and dimensions{p_end}
+{synopt : {opt graph:s}}display graphs for items description{p_end}
+{synopt : {opt cfa}}assess structural validity of the scale by performing a confirmatory factor analysis (CFA){p_end}
+{synopt : {help validscale##cfa_options:{it:cfa_options}}}options for confirmatory factor analysis (CFA){p_end}
+{synopt : {opt conv:div}}assess convergent and divergent validities assessment{p_end}
+{synopt : {help validscale##convdiv_options:{it:conv_div_options}}}options for convergent and divergent validities{p_end}
+{synopt : {help validscale##reliability_options:{it:reliability_options}}}options for reliability assessment{p_end}
+{synopt : {opt rep:et(varlist)}}assess reproducibility of scores and items{p_end}
+{synopt : {help validscale##repet_options:{it:repet_options}}}options for reproducibility{p_end}
+{synopt : {opt kgv(varlist)}}assess known-groups validity by using qualitative variable(s){p_end}
+{synopt : {help validscale##kgv_options:{it:kgv_options}}}options for known-groups validity assessment{p_end}
+{synopt : {opt conc(varlist)}}assess concurrent validity{p_end}
+{synopt : {help validscale##conc_options:{it:conc_options}}}options for concurrent validity assessment{p_end}
+
+{p2colreset}{...}
+
+
+{title:Description}
+
+{phang}{cmd:validscale} assesses validity and reliability of a multidimensional scale. Elements to provide
+structural validity, convergent and divergent validity, reproducibility, known-groups validity, internal consistency, scalability and sensitivity are computed.
+
+{marker options}{...}
+{title:Options}
+
+{dlgtab:Options}
+
+{phang}{opt scoren:ame(string)} allows defining the names of the dimensions. If the option is not used, the dimensions are named {it:Dim1}, {it:Dim2},... unless {opt scores(varlist)} is used.
+
+{phang}{opt scores(varlist)} allows selecting scores from the dataset. {opt scores(varlist)} and {opt scorename(string)} cannot be used together.
+
+{phang}{opt mod:alities(numlist)} allows specifying the minimum and maximum possible values for items responses. If all the items have the same response
+categories, the user may specify these 2 values in {it:numlist}. If the items response categories differ from a dimension to another, the user must define the possible minimum and maximum values of items responses for each
+dimension. So the number of elements in {it:numlist} must be equal to the number of dimensions times 2. Eventually, the user may specify the minimum and maximum response categories for each item. In this case, the
+number of elements in {it:numlist} must be equal to the number of items times 2. By default, the minimum and maximum values are assumed to be the minimum and maximum for each item.
+
+{phang}{opt imp:ute(method)} imputes missing items responses with Person Mean Substitution ({bf:pms}) or Two-way imputation method applied in each dimension ({bf:mi}). With PMS method, missing data are imputed only if the number of
+missing values in the dimension is less than half the number of items in the dimension.
+
+{marker impute_options}{...}
+{phang}{it:impute_options} allow specifying options for imputation of missing values. By default, imputed values are rounded to the nearest whole number but with the {opt nor:ound} option, imputed values
+are not rounded. If {opt impute} is absent then {opt noround} is ignored.
+
+{phang}{opt comp:score(method)} defines the method used to compute the scores. {it:method} may be either {bf:mean} (default), {bf:sum} or {bf:stand}(set scores from 0 to 100). {opt comp:score(method)} is ignored
+if the {opt scores(varlist)} option is used.
+
+{phang}{opt desc:items} displays a descriptive analysis of the items. This option displays missing data rate per item and distribution of item responses. It also computes for each item the Cronbach's alphas
+obtained by omitting each item in each dimension. Moreover, the option computes Loevinger's Hj coefficients and the number of non-significant Hjk. See {help loevh} for details about Loevinger's coefficients.
+
+{phang}{opt graph:s} displays graphs for items and dimensions descriptive analyses. It provides histograms of scores, a biplot of the scores and a graph showing the correlations between the items.
+
+{phang}{opt cfa} performs a confirmatory factor analysis using {help sem} command. It displays estimations of parameters and several goodness-of-fit indices.
+
+{marker cfa_options}{...}
+{phang}{it:cfa_options} allow specifying options for confirmatory factor analysis (CFA). {opt cfam:ethod}({it:method}) specifies the method to estimate the parameters. {it:method} may be either {bf:ml} (maximum
+likelihood), {bf:mlmv} ({bf:ml} with missing values) or {bf:adf} (asymptotic distribution free). The {opt cfas:tand} option displays standardized coefficients.
+The {opt cfac:ovs} option allows adding covariances between measurement errors. You can look at the examples to see the syntax of this option. The {opt cfaa:uto} option adds automatically the covariances
+of measurement errors found with the {help estat mindices} command. The option only adds the covariances of measurement errors within a dimension.
+
+{phang}{opt conv:div} assesses convergent and divergent validities. The option displays the matrix of correlations between items and rest-scores. If {opt scores(varlist)} is used, then the correlations coefficients are computed between
+items and scores of {opt scores(varlist)}.
+
+{marker convdiv_options}{...}
+{phang}{it:conv_div_options} allow specifying options for convergent and divergent validity. {opt tconv:div(#)} defines a threshold for highlighting some values. # is a real number between 0 and 1 which is equal to 0.4 by
+default. Correlations between items and their own score are displayed
+in red if it is less than #. Moreover, if an item has a smaller correlation coefficient with the score of its own dimension than the correlation coefficient computed with other scores, this coefficient is displayed
+in red. The {opt convdivb:oxplots} option displays boxplots for assessing convergent and divergent validities. The boxes represent the correlation coefficients between the items of a given dimension and all scores. Thus the
+box of correlation coefficients between items of a given dimension and the corresponding score must be higher than other
+boxes. There are as many boxplots as dimensions.
+
+{marker reliability_options}{...}
+{phang}{it:reliability_options} allow defining the thresholds for reliability indices. {opt a:lpha(#)} defines a threshold for Cronbach's alpha (see {help alpha}). # is a real number between 0 and 1 which is equal to 0.7
+by default. Cronbach's alpha coefficients less than # are printed in red. {opt d:elta(#)} defines a threshold for Ferguson's delta coefficient (see {help delta}). Delta coefficients are computed only if {opt compscore}({it:sum}) is used
+and {opt scores}({it:varlist)} is not used. # is a real number between 0 and 1 which is equal to 0.9
+by default. Ferguson's delta coefficients less than # are printed in red. {opt h(#)} defines a threshold for Loevinger's H coefficient (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. Loevinger's H coefficients less than # are printed in red. {opt hj:min(#)}
+defines a threshold for Loevinger's Hj coefficients. The displayed value is the minimal Hj coefficient for a item in the dimension. (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. If the minimal Loevinger's Hj coefficient is less than # then it is printed in red and the corresponding item is displayed.
+
+{phang}{opt rep:et(varlist)} assesses reproducibility of scores by defining in {it:varlist} the variables corresponding to responses at time 2 (in the same order than for time 1). Scores are computed according to
+the {opt partition()} option. Intraclass
+Correlation Coefficients (ICC) for scores and their 95% confidence interval are computed with Stata's {help icc} command.
+
+{marker repet_options}{...}
+{phang}{it:repet_options} display information about reproducibility of items. The {opt kap:pa} option computes kappa statistic for items with Stata's {help kap} command. The {opt ickap:pa(#)} option computes
+confidence intervals for
+kappa statistics using {help kapci}. # is the number of replications for bootstrap used to estimate confidence intervals if items are polytomous. If they are dichotomous, an analytical method is used. See {help kapci} for more details about
+calculation of
+confidence intervals for kappa's
+coefficients. If the {opt kappa} option is absent then the {opt ickappa(#)} option is ignored. {opt scores2}({it:varlist}) allows selecting scores at time 2 from the dataset.
+
+{phang}{opt kgv(varlist)} assesses known-groups validity according to the grouping variables defined in {it:varlist}. The option performs an ANOVA which compares the scores between groups of individuals, constructed with variables in {it:varlist}.
+
+{marker kgv_options}{...}
+{phang}{it:kgv_options} allow displaying graphs for known-groups validity. The {opt kgvb:oxplots} option draws boxplots of the scores split into groups of individuals. The {opt kgvg:roupboxplots} option groups
+all boxplots in one graph. If {opt kgvboxplots} is absent then the {opt kgvgroupboxplots} option is ignored.
+
+{phang}{opt conc(varlist)} assesses concurrent validity with variables precised in {it:varlist}. These variables are scores from one or several other scales.
+
+{marker conc_options}{...}
+{phang}{it:conc_options} allow specifying options for concurrent validity. The {opt tc:onc(#)} option defines a threshold for correlation coefficients between the computed scores and the scores of other scales defined in {it:varlist}. Correlation
+coefficients greater than # (0.4 by default) are displayed in bold.
+
+
+{marker examples}{...}
+{title:Examples}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5)}{p_end}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5) imp graphs cfa cfastand cfacovs(item1*item3 item5*item7 item17*item18) convdiv convdivboxplots kgv(factor_variable) kgvboxplots conc(scoreA-scoreD)}{p_end}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5) imp scores(s1-s4) rep(item1bis-item20bis) scores2(s1bis-s4bis) kappa}{p_end}
+
+
+{marker alsosee}{...}
+{title:Also see}
+
+{p 4 13 2}help for {help alpha}, {help delta}, {help loevh}, {help icc}, {help kapci}.{p_end}
diff --git a/Modules/ado/personal/v/validscale.sthlp b/Modules/ado/personal/v/validscale.sthlp
new file mode 100644
index 0000000..5ad9ca0
--- /dev/null
+++ b/Modules/ado/personal/v/validscale.sthlp
@@ -0,0 +1,207 @@
+{smcl}
+{* 2013}{...}
+{hline}
+help for {hi:validscale}{right:Bastien Perrot}
+{hline}
+
+{title:Syntax}
+
+{p 8 14 2}{cmd:validscale} {it:varlist}, {opt part:ition}({it:numlist}) [{it:options}]
+
+{p 4 4 2}{it:varlist} contains the variables (items) used to compute the scores. The first items of {it:varlist} compose the first dimension, the following items define the second dimension, and so on.
+
+{p 4 4 2}{cmd:partition} allows defining in {it:numlist} the number of items in each dimension.
+
+
+{synoptset 20 tabbed}{...}
+{synopthdr}
+{synoptline}
+{syntab:Options}
+{synopt : {opt scoren:ame(string)}}define the names of the dimensions{p_end}
+{synopt : {opt scores(varlist)}}use scores from the dataset{p_end}
+{synopt : {opt cat:egories(numlist)}}define minimum and maximum response categories for the items{p_end}
+{synopt : {opt imp:ute(method)}}impute missing item responses{p_end}
+{synopt : {help validscale##impute_options:{it:impute_options}}}options for imputation of missing data {p_end}
+{synopt : {opt comps:core(method)}}define how scores are computed{p_end}
+{synopt : {opt desc:items}}display a descriptive analysis of items and dimensions{p_end}
+{synopt : {opt graph:s}}display graphs for items description{p_end}
+{synopt : {opt cfa}}assess structural validity of the scale by performing a confirmatory factor analysis (CFA){p_end}
+{synopt : {help validscale##cfa_options:{it:cfa_options}}}options for confirmatory factor analysis (CFA){p_end}
+{synopt : {opt conv:div}}assess convergent and divergent validities assessment{p_end}
+{synopt : {help validscale##convdiv_options:{it:conv_div_options}}}options for convergent and divergent validities{p_end}
+{synopt : {help validscale##reliability_options:{it:reliability_options}}}options for reliability assessment{p_end}
+{synopt : {opt rep:et(varlist)}}assess reproducibility of scores and items{p_end}
+{synopt : {help validscale##repet_options:{it:repet_options}}}options for reproducibility{p_end}
+{synopt : {opt kgv(varlist)}}assess known-groups validity by using qualitative variable(s){p_end}
+{synopt : {help validscale##kgv_options:{it:kgv_options}}}options for known-groups validity assessment{p_end}
+{synopt : {opt conc(varlist)}}assess concurrent validity{p_end}
+{synopt : {help validscale##conc_options:{it:conc_options}}}options for concurrent validity assessment{p_end}
+{synopt : {opt * }}options from {help sem_estimation_options} command (additional estimation options for {help validscale##cfa_options:{it:cfa_options}}) {p_end}
+
+
+{p2colreset}{...}
+
+
+{title:Description}
+
+{phang}{cmd:validscale} assesses validity and reliability of a multidimensional scale. Elements to provide
+structural validity, convergent and divergent validity, reproducibility, known-groups validity, internal consistency, scalability and sensitivity are computed. {cmd:validscale} can be used with a dialog box by typing {stata db validscale}.
+
+{marker options}{...}
+{title:Options}
+
+{dlgtab:Options}
+
+{phang}{opt scoren:ame(string)} allows defining the names of the dimensions. If the option is not used, the dimensions are named {it:Dim1}, {it:Dim2},... unless {opt scores(varlist)} is used.
+
+{phang}{opt scores(varlist)} allows selecting scores from the dataset. {opt scores(varlist)} and {opt scorename(string)} cannot be used together.
+
+{phang}{opt cat:egories(numlist)} allows specifying the minimum and maximum possible values for items responses. If all the items have the same response
+categories, the user may specify these 2 values in {it:numlist}. If the items response categories differ from a dimension to another, the user must define the possible minimum and maximum values of items responses for each
+dimension. So the number of elements in {it:numlist} must be equal to the number of dimensions times 2. Eventually, the user may specify the minimum and maximum response categories for each item. In this case, the
+number of elements in {it:numlist} must be equal to the number of items times 2. By default, the minimum and maximum values are assumed to be the minimum and maximum for each item.
+
+{marker impute_options}{...}
+{phang}{opt imp:ute(method)} imputes missing items responses with Person Mean Substitution ({bf:pms}) or Two-way imputation method applied in each dimension ({bf:mi}). With PMS method, missing data are imputed only if the number of
+missing values in the dimension is less than half the number of items in the dimension.
+
+{phang2} By default, imputed values are rounded to the nearest whole number but with the {opt nor:ound} option, imputed values are not rounded. If {opt impute} is absent then {opt noround} is ignored.
+
+{phang}{opt comp:score(method)} defines the method used to compute the scores. {it:method} may be either {bf:mean} (default), {bf:sum} or {bf:stand}(set scores from 0 to 100). {opt comp:score(method)} is ignored
+if the {opt scores(varlist)} option is used.
+
+{phang}{opt desc:items} displays a descriptive analysis of the items. This option displays missing data rate per item and distribution of item responses. It also computes for each item the Cronbach's alphas
+obtained by omitting each item in each dimension. Moreover, the option computes Loevinger's Hj coefficients and the number of non-significant Hjk. See {help loevh} for details about Loevinger's coefficients.
+
+{phang}{opt graph:s} displays graphs for items and dimensions descriptive analyses. It provides histograms of scores, a biplot of the scores and a graph showing the correlations between the items.
+
+{marker cfa_options}{...}
+{phang}{opt cfa} performs a Confirmatory Factor Analysis (CFA) using {help sem} command. It displays estimations of parameters and several goodness-of-fit indices.
+
+{phang2} {opt cfam:ethod}({it:method}) specifies the method to estimate the parameters. {it:method} may be either {bf:ml} (maximum
+likelihood), {bf:mlmv} ({bf:ml} with missing values) or {bf:adf} (asymptotic distribution free).
+
+{phang2} {opt cfasb} produces Satorra-Bentler adjusted goodness-of-fit indices using the vce(sbentler) option from sem ({help sem_option_method##vcetype})
+
+{phang2} {opt cfas:tand} displays standardized coefficients.
+
+{phang2} {opt cfanocovd:im} asserts that the latent variables are not correlated.
+
+{phang2} {opt cfac:ovs} option allows adding covariances between measurement errors. The syntax cfacov(item1*item2)
+allows estimating the covariance between the errors of item1 and item3. To specify more than one covariance, the form of the syntax is cfacov(item1*item2 item3*item4).
+
+{phang2} {opt cfar:msea(#)} option allows adding automatically the covariances between measurement errors found
+with the estat mindices command until the RMSEA (Root Mean Square Error
+of Approximation) of the model is less than #. More precisely, the "basic" model
+(without covariances between measurement errors) is estimated then we add the covariance corresponding to the greatest modification index and the model is re-
+estimated with this extra-parameter, and so on. The option only adds the covari-
+ances between measurement errors within a dimension and can be combined with
+cfacov. The specified value # may not be reached if all possible within-dimension
+measurement errors have already been added.
+
+{phang2} {opt cfacf:i(#)} option allows adding automatically the covariances between measurement errors found with
+the estat mindices command until the CFI (Comparative Fit Index) of the model
+is greater than #. More precisely, the "basic" model (without covariances between
+measurement errors) is estimated then we add the covariance corresponding to the
+greatest modification index and the model is re-estimated with this extra-parameter,
+and so on. The option only adds the covariances between measurement errors within
+a dimension and can be combined with cfacov. The specified value # may not
+be reached if all possible within-dimension measurement errors have already been
+added.
+
+{phang2} {opt cfaor} option is useful when both {opt cfar:msea} and {opt cfacf:i} are used. By default, covariances between measurement errors are added and the model is estimated until both RMSEA
+and CFI criteria are met. If cfaor is used, the estimations stop when one of the two
+criteria is met.
+
+{phang2} {opt *} options from {help sem_estimation_options} (e.g. {opt iterate(#)}, {opt vce(vcetype)}, etc.)
+
+{marker convdiv_options}{...}
+{phang}{opt conv:div} assesses convergent and divergent validities. The option displays the matrix of correlations between items and rest-scores. If {opt scores(varlist)} is used, then the correlations coefficients are computed between
+items and scores of {opt scores(varlist)}.
+
+{phang2} {opt tconv:div(#)} defines a threshold for highlighting some values. # is a real number between 0 and 1 which is equal to 0.4 by
+default. Correlations between items and their own score are displayed
+in red if it is less than #. Moreover, if an item has a smaller correlation coefficient with the score of its own dimension than the correlation coefficient computed with other scores, this coefficient is displayed
+in red.
+
+{phang2} {opt convdivb:oxplots} displays boxplots for assessing convergent and divergent validities. The boxes represent the correlation coefficients between the items of a given dimension and all scores. Thus the
+box of correlation coefficients between items of a given dimension and the corresponding score must be higher than other boxes. There are as many boxplots as dimensions.
+
+{marker reliability_options}{...}
+{phang}{it:reliability_options} allow defining the thresholds for reliability and scalability indices.
+
+{phang2} {opt a:lpha(#)} defines a threshold for Cronbach's alpha (see {help alpha}). # is a real number between 0 and 1 which is equal to 0.7
+by default. Cronbach's alpha coefficients less than # are printed in red.
+
+{phang2} {opt d:elta(#)} defines a threshold for Ferguson's delta coefficient (see {help delta}). Delta coefficients are computed only if {opt compscore}({it:sum}) is used
+and {opt scores}({it:varlist)} is not used. # is a real number between 0 and 1 which is equal to 0.9
+by default. Ferguson's delta coefficients less than # are printed in red.
+
+{phang2} {opt h(#)} defines a threshold for Loevinger's H coefficient (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. Loevinger's H coefficients less than # are printed in red.
+
+{phang2} {opt hj:min(#)} defines a threshold for Loevinger's Hj coefficients. The displayed value is the minimal Hj coefficient for a item in the dimension. (see {help loevh}). # is a real number between 0 and 1 which is equal to
+0.3 by default. If the minimal Loevinger's Hj coefficient is less than # then it is printed in red and the corresponding item is displayed.
+
+{marker repet_options}{...}
+{phang}{opt rep:et(varlist)} assesses reproducibility of scores by defining in {it:varlist} the variables corresponding to responses at time 2 (in the same order than for time 1). Scores are computed according to
+the {opt partition()} option. Intraclass
+Correlation Coefficients (ICC) for scores and their 95% confidence interval are computed with Stata's {help icc} command.
+
+{phang2} {opt kap:pa} computes kappa statistic for items with Stata's {help kap} command.
+
+{phang2} {opt ickap:pa(#)} computes confidence intervals for kappa statistics using {help kapci}. # is the number of replications for bootstrap used to estimate confidence intervals if items are polytomous. If they are dichotomous, an analytical method is used. See {help kapci} for more details about
+calculation of confidence intervals for kappa's coefficients. If the {opt kappa} option is absent then {opt ickappa(#)} is ignored.
+
+{phang2} {opt scores2}({it:varlist}) allows selecting scores at time 2 from the dataset.
+
+{phang}{opt kgv(varlist)} assesses known-groups validity according to the grouping variables defined in {it:varlist}. The option performs an ANOVA which compares the scores between groups of individuals, constructed with variables in {it:varlist}. A p-value based on a Kruskal-Wallis test is also given.
+
+{marker kgv_options}{...}
+
+{phang2} {opt kgvb:oxplots} draws boxplots of the scores split into groups of individuals.
+
+{phang2} {opt kgvg:roupboxplots} groups all boxplots into one graph. If {opt kgvboxplots} is absent then the {opt kgvgroupboxplots} option is ignored.
+
+{phang}{opt conc(varlist)} assesses concurrent validity with variables precised in {it:varlist}. These variables are scores from one or several other scales.
+
+{marker conc_options}{...}
+{phang2} {opt tc:onc(#)} defines a threshold for correlation coefficients between the computed scores and the scores of other scales defined in {it:varlist}. Correlation
+coefficients greater than # (0.4 by default) are displayed in bold.
+
+{marker examples}{...}
+{title:Examples}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5)}{p_end}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5) imp graphs cfa cfastand cfacovs(item1*item3 item5*item7 item17*item18) convdiv convdivboxplots kgv(factor_variable) kgvboxplots conc(scoreA-scoreD)}{p_end}
+
+{phang2}{cmd:. validscale item1-item20, part(5 4 6 5) imp scores(s1-s4) rep(item1bis-item20bis) scores2(s1bis-s4bis) kappa}{p_end}
+
+{title:References}
+
+{phang}Blanchette, D. 2010. LSTRFUN: Stata module to modify long local macros. {it:Statistical Software Components}, Boston College Department of Economics.
+
+{phang}Gadelrab, H. 2010. {it:Evaluating the fit of structural equation models: Sensitivity to specification error and descriptive goodness-of-fit indices.} Lambert Academic Publishing.
+
+{phang}Hamel, J.-F. 2014. MI TWOWAY: Stata module for computing scores on questionnaires containing missing item responses. {it:Statistical Software Components}, Boston College Department of Economics.
+
+{phang}Hardouin, J.-B. 2004. LOEVH: Stata module to compute Guttman errors and Loevinger H coeficients. {it:Statistical Software Components}, Boston College Department of Economics.
+
+{phang}Hardouin, J.-B. 2007. DELTA: Stata module to compute the Delta index of scale discrimination. {it:Statistical Software Components}, Boston College Department of Economics.
+
+{phang}Hardouin, J.-B. 2013. IMPUTEITEMS: Stata module to impute missing data of binary items.
+
+{phang}Hardouin, J.-B., A. Bonnaud-Antignac, V. Sbille, et al. 2011. Nonparametric item response theory using Stata. {it:Stata Journal} 11(1): 30.
+
+{phang}Reichenheim, M. E. 2004. Confidence intervals for the kappa statistic. {it:Stata Journal} 4(4): 421{428(8).
+
+{title:Author}
+
+{phang}Bastien Perrot, EA 4275 SPHERE, "methodS in Patient-centered outomes and HEalth ResEarch", University of Nantes, France
+{browse "mailto:bastien.perrot@univ-nantes.fr":bastien.perrot@univ-nantes.fr}{p_end}
+
+{marker alsosee}{...}
+{title:Also see}
+
+{p 4 13 2}help for {help alpha}, {help delta}, {help loevh}, {help icc}, {help kapci}.{p_end}
diff --git a/Modules/ado/personal/v/validscaleXX.ado b/Modules/ado/personal/v/validscaleXX.ado
new file mode 100644
index 0000000..4e41ed0
--- /dev/null
+++ b/Modules/ado/personal/v/validscaleXX.ado
@@ -0,0 +1,2668 @@
+
+*! version 1.2 July 02, 2014
+*! Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine
+*************************************************************************************************************
+* Stata program : validscale
+* Assess validity and reliability of a multidimensional measurement scale using CTT methods
+*
+* Historic:
+* Version 1 (2013-06-20): [Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine]
+* Version 1.1 (2014-05-13) : [Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine] /* Method for IMPUTE option (PMS or Two-way) */
+* Version 1.2 (2014-07-02) : [Bastien Perrot, Jean-Benoit Hardouin, Emmanuelle Anthoine] /* CFA: Standard error for the intercepts, IMPUTE: correction of a bug with MI option, minor corrections*/
+*
+* Required modules :
+* delta
+* loevh
+* kapci
+* mi_twoway
+* detect2
+* imputeitems
+* lstrfun
+*************************************************************************************************************
+
+program define validscale , rclass
+syntax varlist [if], PARTition(numlist integer >0) [HTML(string) MODalities(numlist) SCOREName(string) scores(varlist) IMPute(string) NORound COMPScore(string) DESCitems GRAPHs cfa CFAMethod(string) CFAStand CFACov(string) CFAAuto CONVdiv TCONVdiv(real 0.4) CONVDIVBoxplots Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3) REPet(varlist) scores2(varlist) KAPpa ICKAPpa(integer 0) kgv(varlist) KGVBoxplots KGVGroupboxplots conc(varlist) tconc(real 0.4)]
+preserve
+
+if "`if'"!="" {
+ qui keep `if'
+}
+
+if "`html'" != "" {
+ global html = "`html'"
+ set scheme sj
+ local htmlregion "graphregion(fcolor(white) ifcolor(white))"
+ local xsize=6
+ local ysize=4
+ di in gr ""
+ di "
"
+ di ""
+}
+
+if "`modalities'" == "" {
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ local m `mi' `ma'
+ local modalities `modalities' `m'
+ }
+}
+
+global modalities = "`modalities'"
+global compscore = "`compscore'"
+if "$compscore" == "" global compscore = "mean"
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+if "`repet'" != "" {
+ local b:word count `repet'
+ if `nbvars' != `b' {
+ di in red "The number of items in varlist is different from the number of items in repet"
+ exit 119
+ }
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+local P:word count `partition'
+local S:word count `scorename'
+
+if "`scores'" != "" & "`scorename'" != "" {
+ di in red "scorenames() and scores() cannot be used together"
+ exit 119
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ foreach sco in `scorename' {
+ capture confirm variable `sco', exact
+ if !_rc {
+ di in red "`sco' already defined. You must choose names that do not already exist or use the scores() option if the scores are already defined."
+ exit 119
+ }
+ tokenize `scorename'
+ local g = 0
+ forvalues i = 1/`S' {
+ if "`sco'" == "``i''" {
+ local `++g'
+ }
+ }
+ if `g' > 1 {
+ di in red "2 or more dimensions have the same name"
+ exit 119
+ }
+ }
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') modalities(`modalities')
+ global exist = 0
+ global scorename = "`scorename'"
+}
+
+else if "`scorename'" == "" & "`scores'" == ""{
+
+ local name
+ local nname
+
+ forvalues i = 1/`P' {
+
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+
+ local scorename = "`nname'"
+ global scorename = "`nname'"
+ calcscore `varlist', scorename(`scorename') partition(`partition') compscore(`compscore') modalities(`modalities')
+ global exist = 0
+}
+
+else if "`scores'" != "" {
+ local P:word count `partition'
+ local S2:word count `scores'
+ if `P'!=`S2' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+ else {
+ global scorename = "`scores'"
+ local scorename = "`scores'"
+ global exist = 1
+
+ }
+
+}
+
+local nbm : word count $modalities
+if `nbm' !=2 &`nbm' !=`P'*2 &`nbm' !=`nbvars'*2 {
+ di in red "option modalities() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+}
+
+if `nbm' == 2{
+ tokenize $modalities
+ foreach v in `varlist' {
+ tempvar min
+ tempvar max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ if `min' < `1' {
+ di in red "error in option modalities() : some responses have smaller values than the minimum value in modalities()"
+ exit 119
+ }
+ if `max' > `2' {
+ di in red "error in option modalities() : some responses have greater values than the maximum value in modalities()"
+ exit 119
+ }
+ }
+}
+
+if `nbm' == `nbvars'*2 {
+ local i = 1
+ foreach v in `varlist' {
+ tempvar min max
+ egen `min' = min(`v')
+ egen `max' = max(`v')
+ local mi = `min'
+ local ma = `max'
+ tokenize $modalities
+ if `mi' < ``i'' {
+ di in red "error in option modalities() : some responses have values less than the minimum value specified for the variable in modalities()"
+ exit 119
+ }
+ local `++i'
+ tokenize $modalities
+ if `ma' > ``i'' {
+ di in red "error in option modalities() : some responses have values greater than the maximum value specified for the variable in modalities()"
+ exit 119
+ }
+ local `++i'
+ }
+}
+
+if `nbm' == `P'*2 {
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ //local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+ forvalues w = `y'/`s' {
+ tokenize $modalities
+ tempvar min max
+ egen `min' = min(`var`w'')
+ egen `max' = max(`var`w'')
+ local mi = `min'
+ local ma = `max'
+ if `mi' < ``i'' {
+ di in red "error in option modalities() : some responses have values less than the minimum value specified"
+ exit 119
+ }
+ local j = `i'+1
+ tokenize $modalities
+ if `ma' > ``j'' {
+ di in red "error in option modalities() : some responses have values greater than the maximum value specified"
+ exit 119
+ }
+
+ }
+ local i = `i'+2
+ local y = `s'+1
+ }
+}
+
+if "`cfa'" != "" {
+ if "`cfacov'" != "" {
+ if !strpos("`cfacov'", "*") {
+ di "error in cfacov() option : you must enter covariances between errors as follows: item3*item5 item7*item8 ... "
+ exit 119
+ }
+ local v = subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ }
+}
+
+if "`kgv'" !="" {
+ foreach k in `kgv' {
+ capture confirm variable `k'
+ if _rc!=0 {
+ di in red "`k' does not exist"
+ exit 119
+ }
+ }
+}
+
+if "`conc'" !="" {
+ foreach c in `conc' {
+ capture confirm variable `c'
+ if _rc!=0 {
+ di in red "`c' does not exist"
+ exit 119
+ }
+ }
+}
+
+di as result "Items used to compute the scores"
+di
+
+local i = 1
+local j = 1
+local y = 1
+foreach p in `partition' {
+ tokenize `scorename'
+ di "{bf:``i''} : " _c
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ forvalues z = `y'/`s' {
+ di "{text:`var`z'' }" _c
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+}
+
+di
+di as result "Number of observations: " _c
+di as text _N
+
+qui destring _all, replace
+di
+
+if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+}
+
+
+if "`graphs'" != "" {
+ graphs `varlist', partition(`partition')
+}
+
+
+if "`repet'" != "" {
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+}
+
+if "`impute'" != "" {
+ if "`impute'" != "pms" & "`impute'" !="mi" {
+ di in red "option impute() incorrectly specified. You must specify {hi:pms} or {hi:mi}."
+ error 100
+ }
+ if "`impute'" == "pms" {
+ pms `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (PMS imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ pms `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+ if "`impute'" == "mi" {
+ mitw `varlist', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (mi two-way imputation)"
+ di as result "{hline 105}"
+ di
+ descitems `varlist', partition(`partition')
+ di
+ }
+ if "`repet'" != "" {
+ mitw `repet', partition(`partition') `noround'
+ if "`descitems'" != "" {
+ di as result "{hline 105}"
+ di "Description of items after missing data handling (time 2)"
+ di as result "{hline 105}"
+ di
+ descitems `repet', partition(`partition')
+ di
+ }
+ }
+ }
+}
+
+rel `varlist', scorename(`scorename') partition(`partition') alpha(`alpha') delta(`delta') h(`h') hjmin(`hjmin') modalities(`modalities')
+di
+
+if "`convdiv'" != "" {
+ convdiv `varlist', partition(`partition') tconvdiv(`tconvdiv') `convdivboxplots'
+ di
+}
+
+if "`cfa'" != "" {
+ cfa `varlist', partition(`partition') cfamethod(`cfamethod') `cfastand' cfacov(`cfacov') `cfaauto'
+ di
+}
+
+if "`repet'" != "" | "`scores2'" != "" {
+ global scores2 = "`scores2'"
+ repet `varlist', t2(`repet') partition(`partition') `kappa' ickappa(`ickappa')
+ di
+}
+
+if "`kgv'" != "" {
+ kgv `scorename', categ(`kgv') `kgvboxplots' `kgvgroupboxplots'
+ di
+}
+
+if "`conc'" != "" {
+ conc `scorename', comp(`conc') tconc(`tconc')
+}
+
+
+//capture restore, not
+end
+
+
+/* pms */
+
+capture program drop pms
+program pms
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+tokenize `varlist'
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ local n : word count `liste'
+ if mod(`n',2)!=0 local max = floor(`n'/2)
+ else local max = `n'/2-1
+
+ if "`noround'" != "" {
+ qui imputeitems `liste', method(pms) max(`max') noround
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+ else {
+ qui imputeitems `liste', method(pms) max(`max')
+ foreach var of varlist `liste' {
+ qui replace `var' = imp`var'
+ qui drop imp`var'
+ }
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+end
+
+
+/* mitw */
+
+capture program drop mitw
+program mitw
+syntax varlist, PARTition(numlist integer >0) [NORound]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local i = 1
+local y = 1
+
+
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ qui mi_twoway `liste', scorename(scoretmp) add(1) style(wide) clear
+
+ foreach var of varlist `liste' {
+ qui replace `var' = _1_`var'
+ if "`noround'" == "" {
+ qui replace `var' = round(`var')
+ }
+ /*if `var' > `maxm' {
+ qui replace `var' = `maxm'
+ }
+ if `var' < `minm' {
+ qui replace `var' = `minm'
+ }*/
+ qui drop _1_`var'
+ capture drop scoretmp
+ capture drop _1_scoretmp
+ }
+
+ local `i++'
+ local y = `s'+1
+}
+
+//capture drop _mi_miss
+qui mi unset
+end
+
+
+/* calcscore */
+
+capture program drop calcscore
+program calcscore,rclass
+syntax varlist, PARTition(numlist integer >0) [modalities(numlist) COMPscore(string) SCOrename(string)]
+
+local P:word count `partition'
+local S:word count `scorename'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+if "`scorename'" != "" {
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit 119
+ }
+}
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ tokenize `varlist'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' ``w''
+ }
+
+ tempvar nonmiss
+ qui egen `nonmiss' = rownonmiss(`liste')
+
+ tokenize `scorename'
+ local sc = "``i''"
+
+ if "`compscore'" == "" local compscore = "mean"
+
+ if "`compscore'" != "mean" & "`compscore'" != "sum" & "`compscore'" != "stand" {
+ di in red "option compscore incorrectly specified (choose among mean, sum and stand)"
+ error 198
+ }
+
+ if "`compscore'" == "sum" {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`x'
+
+ }
+
+ else if "`compscore'" == "stand" {
+
+ local nbm:word count `modalities'
+
+ local nbl:word count `liste'
+ tokenize `modalities'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+
+ }
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+ }
+ }
+
+ else {
+ di in red "option modalities() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ qui replace `sc' = `sc'*`nonmiss'
+ qui replace `sc' = (`sc'-`min')/(`max'-`min')*100
+ }
+
+ else {
+ qui egen `sc' = rowmean(`liste') if `nonmiss' >= `x'/2
+ }
+
+local `i++'
+local y = `s'+1
+}
+
+end
+
+
+
+/* rel */
+
+capture program drop rel
+program rel,rclass
+syntax varlist, PARTition(numlist integer >0) [MODalities(numlist) SCOrename(string) Alpha(real 0.7) Delta(real 0.9) h(real 0.3) HJmin(real 0.3)]
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit
+}
+
+local P:word count `partition'
+if "`scorename'" !="" {
+ local S:word count `scorename'
+ if `P'!=`S' {
+ di in red "The number of score names given is different from the number of dimensions in the partition option"
+ exit
+ }
+}
+di as result "{hline 105}"
+di "{bf:Reliability}"
+di as result "{hline 105}"
+di
+
+local y = 1
+local nbitems = 0
+matrix aa = J(`P',4,.)
+
+foreach z in `partition' {
+ local nbitems = `nbitems' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+matrix d = J(`nbitems',2,.)
+
+local i = 1
+local b = 1
+foreach x in `partition' {
+
+ tokenize `scorename'
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ capture alpha `liste', asi item std
+ local al`i' = r(alpha)
+
+ capture qui loevh `liste', pairwise
+ local h`i' = r(loevH)
+ matrix c = r(loevHj)
+ matrix ct = c'
+
+
+ local lister = ""
+ forvalues w = `y'/`s' {
+ tempvar z
+ qui gen `z' = round(`var`w'')
+ local lister `lister' `z'
+ }
+
+ tempvar nbmiss
+ local nbl : word count `lister'
+ egen `nbmiss' = rowmiss(`lister')
+ qui count if `nbmiss'<`nbl'
+ local n`i' = r(N)
+
+
+ // delta
+
+ if ${exist} == 0 & "$compscore" == "sum" {
+
+ local nbm:word count `modalities'
+ tokenize `modalities'
+
+ if `nbm' == 2 {
+ local min = `1'*`nbl'
+ local max = `2'*`nbl'
+ }
+
+ else if `nbm' == `P'*2 {
+ local min = ``b''*`nbl'
+ local max = ``=`b'+1''*`nbl'
+ }
+
+
+ else if `nbm' == `nbvars'*2 {
+ if `y'==1 local yy = 1
+ else local yy = `y'*2-1
+ local bb = `yy'
+ local min = 0
+ local max = 0
+
+ forvalues bb = `yy'(2)`=`s'*2' {
+ local tpmin = ``bb''
+ local tpmax = ``=`bb'+1''
+ local min = `min'+`tpmin'
+ local max = `max'+`tpmax'
+
+ }
+ }
+
+ else {
+ di in red "option modalities() misspecified. You must enter either 2 or `=`nbvars'*2' or `=`P'*2' elements"
+ exit 119
+ }
+
+ capture delta `lister', min(`min') max(`max')
+ local delt`i' = r(delta)
+
+ }
+
+ else local delt`i' = .
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',1] = ct[`k',1]
+ matrix d[`j',2] = `i'
+ }
+
+ matrix aa [`i',1] = `al`i''
+ matrix aa [`i',2] = `delt`i''
+ matrix aa [`i',3] = `h`i''
+
+ local `i++'
+ local y = `s'+1
+
+ local b = `b'+2
+}
+
+matrix rownames d = `varlist'
+local i = 1
+local y = 1
+
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ matrix C = d[`y'..`s',1.]
+ local min`i' = C[1,1]
+ local n : rownames C
+ tokenize `n'
+ local t`i' = "`1'"
+ forvalues j = 1/`x' {
+ local t = "``j''"
+ if C[`j',1] <= `min`i'' {
+ local min`i' = C[`j',1]
+ //di `min`i''
+ local t`i' = "``j''"
+ local itmin`i' = "``j''"
+ //di " `i' : `itmin`i''"
+ }
+ }
+ matrix aa [`i',4] = `min`i''
+ local `i++'
+ local y = `s'+1
+}
+
+matrix colnames aa = "alpha" "delta" "H" "Hj_min"
+
+if "`scorename'"=="" {
+ local i = 1
+ local y = 1
+ local name
+ local nname
+ forvalues i = 1/`P' {
+ local name "Dim`i'"
+ local nname `nname' `name'
+ }
+local scorename = "`nname'"
+}
+
+local maxlen = 0
+foreach sco in `scorename' {
+ local w = length("`sco'")
+ if `w' > `maxlen' local maxlen = `w'
+}
+
+local i = 1
+local j = 1
+local y = 1
+local col = `maxlen'+8
+
+di _col(`col') "{bf:n}" _c
+local col = `col'+6
+di _col(`col') "{bf:alpha}" _c
+local col = `col'+10
+di _col(`col') "{bf:delta}" _c
+local col = `col'+14
+di _col(`col') "{bf:H}" _c
+local col = `col'+5
+di _col(`col') "{bf:Hj_min}"
+
+foreach s in `scorename' {
+ di in blue "{bf:`s'}" _c
+ local col = `maxlen'+3
+
+ local n : di %6.0f `n`i''
+
+ di in blue _col(`col') "{text:`n'}" _c
+ local col = `col'+10
+
+ local a : di %6.2f `al`i''
+ if `a' < `alpha' {
+ di _col(`col') "{error:`a'} " _c
+ }
+ else di _col(`col') "{text:`a'}" _c
+
+ local col = `col'+10
+ local d : di %6.2f `delt`i''
+ if `d' < `delta' {
+ di _col(`col') "{error:`d'} " _c
+ }
+ else di _col(`col') "{text:`d'}" _c
+
+ local col = `col'+10
+ local h : di %6.2f `h`i''
+ if `h' < `h' {
+ di _col(`col') "{error:`h'} " _c
+ }
+ else di _col(`col') "{text:`h'}" _c
+
+ local col = `col'+8
+ local m : di %8.2f `min`i''
+ if `m' < `hjmin' {
+ di _col(`col') "{error:`m'} " _c
+ di "{text:(item `itmin`i'')}" _c
+ }
+ else di _col(`col') "{text:`m'}" _c
+
+ di
+ local `++i'
+}
+
+end
+
+/* descitems */
+
+capture program drop descitems
+program descitems
+syntax varlist, PARTition(numlist integer >0)
+local i = 1
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+
+if `C' != `nbvars' {
+ di in red "The sum of the numbers in the partition option is different from the number of variables precised in varlist"
+ exit 119
+}
+
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+foreach var in `varlist' {
+ qui replace `var' = round(`var')
+}
+
+local lev = ""
+foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ foreach l in `levels' {
+ if strpos("`lev'","`l'") == 0 {
+ local lev `lev' `l'
+ }
+ }
+}
+
+_qsort_index `lev'
+local lev = r(slist1)
+
+local i = 1
+matrix d = J(`nbvars',4,.)
+
+foreach var in `varlist'{
+ qui count if missing(`var')
+ local ct=r(N)
+
+ local tx`i'=`ct'/_N
+ matrix d[`i',1] = `tx`i''
+ local `i++'
+}
+
+matrix rownames d = `varlist'
+matrix colnames d = "missing" "alpha" "Hj"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ qui capture alpha `liste', asi item std
+
+ mat a = r(Alpha)
+ mat at = a'
+
+ qui capture loevh `liste', pairwise
+ matrix e = r(loevHj)
+ matrix et = e'
+ matrix ns = r(nbHjkNS)
+ matrix nst = ns'
+
+ local k = 0
+ forvalues j = `y'/`s' {
+ local k = `k'+1
+ matrix d[`j',2] = at[`k',1]
+ matrix d[`j',3] = et[`k',1]
+ matrix d[`j',4] = nst[`k',1]
+
+ }
+ local `i++'
+ local y = `s'+1
+}
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",8)
+ local `++i'
+}
+
+local dec = 10
+local col = `dec'
+
+tokenize `varlist'
+local minm = `1'
+local maxm = `1'
+foreach mod in $modalities {
+ if `mod' < `minm' local minm = `mod'
+ if `mod' > `maxm' local maxm = `mod'
+}
+
+local b = `maxm'-`minm'+1
+
+local i = 1
+local j = 1
+local y = 1
+
+di in blue _col(`dec') "{bf:Missing}" _c
+local col = `col'+11
+di in blue _col(`=`col'+2') "{bf:N}" _c
+
+local col = `col'+9
+di _col(`col') "{bf:Response categories}" _c
+local col = `dec'+18+8*`b'
+di _col(`col') "{bf:Alpha}" _c
+local col = `col'+9
+di _col(`col') "{bf:Loevinger}" _c
+local col = `col'+12
+di _col(`col') "{bf:Number of}"
+
+local col = `dec'-1
+di _col(`col') "{bf:data rate}" _c
+local col = `dec'+18
+
+forvalues m = `minm'/`maxm' {
+ di _col(`=`col'+2') "`m'" _c
+ local col = `col'+8
+}
+
+di as result _col(`col') "- item" _c
+local col = `col'+10
+di as result _col(`col') "Hj coeff" _c
+local col = `col'+12
+di as result _col(`col') "NS Hjk"
+
+local ch = `dec'+18+8*`b'+29
+di "{hline `ch'}"
+
+local i = 1
+foreach x in `varlist' {
+ local varo`i' = "`x'"
+ local `++i'
+}
+
+local y = 1
+foreach p in `partition' {
+
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ local col = `dec'
+ di "{bf:`var`z''}" _c
+ local t = d[`z',1]
+ local t : di %8.2f `t'*100
+ di _col(`col') "{text:`t'%}" _c
+ qui count if missing(`varo`z'')
+ local m = r(N)
+ local N = _N-`m'
+ local N : di %4.0f `N'
+ local col = `col'+10
+ di _col(`col') "{text:`N'}" _c
+
+ local col = `col'+8
+ forvalues m = `minm'/`maxm' {
+ qui count if round(`varo`z'') == `m'
+ local n = r(N)
+ if `m' == `maxm' & round(`varo`z'')>`maxm' {
+ local n = `n' + 1
+ }
+ if `m' == `minm' & round(`varo`z'')<`minm' {
+ local n = `n' + 1
+ }
+ qui count if `varo`z'' != .
+ local d = r(N)
+ local e = `n'/`d'
+ local e : di %4.2f `e'*100
+ if `e' != 0 di _col(`=`col'-1')"{text:`e'%}" _c
+ else di _col(`=`col'-1')"{text: -}" _c
+ local col = `col'+8
+ }
+ local a = d[`z',2]
+ local a : di %4.2f `a'
+ di _col(`=`col'+1') "{text:`a'}" _c
+ local h = d[`z',3]
+ local h : di %5.2f `h'
+ local col = `col'+10
+ di _col(`=`col'+3') "{text:`h'}" _c
+ local ns = d[`z',4]
+ local ns : di %2.0f `ns'
+ local col = `col'+11
+ di _col(`=`col'+7') "{text:`ns'}"
+
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di "{dup `ch':-}"
+}
+end
+
+
+capture program drop graphs
+program graphs
+syntax varlist, PARTition(numlist integer >0)
+
+//qui set autotabgraphs on
+local P:word count `partition'
+local html = "${html}"
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+if "$compscore" == "stand" local w = 10
+if "$compscore" == "sum" local b = 10
+if "$compscore" == "mean" local w = 0.5
+
+
+
+if "`html'"!="" {
+ //set graphics off
+ foreach s in $scorename {
+ qui local saving "saving(`c(tmpdir)'/`html'_`s',replace) nodraw"
+ qui hist `s', name(`s',replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b') `saving'
+ qui graph use `c(tmpdir)'/`html'_`s'.gph
+ qui graph export `c(tmpdir)'/`html'_`s'.eps, replace
+ //di ""
+
+ }
+ //set graphics on
+
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_group,replace) nodraw"
+ qui gr combine $scorename, name(group,replace) title("Distribution of scores") `saving'
+ qui graph use `c(tmpdir)'/`html'_group.gph
+ qui graph export `c(tmpdir)'/`html'_group.eps, replace
+ di ""
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_scores,replace) nodraw"
+ qui biplot $scorename, name("Biplot_scores",replace) norow std title("Correlations between scores") xtitle("") ytitle("") `saving'
+ qui graph use `c(tmpdir)'/`html'_scores.gph
+ qui graph export `c(tmpdir)'/`html'_scores.eps, replace
+ di ""
+}
+
+else {
+ set graphics off
+ foreach s in $scorename {
+ qui hist `s', name("`s'",replace) percent fcolor(emidblue) lcolor(none) width(`w') bin(`b')
+ }
+ set graphics on
+
+ gr combine $scorename, name("Histograms_scores",replace)
+ capture biplot $scorename, name("Biplot_scores",replace) norow std title("") xtitle("") ytitle("")
+}
+
+
+
+capture biplot `varlist', name("temp",replace) norow std nograph
+
+mat a = r(V)
+
+tempvar a1 a2
+mat colnames a = `a1' `a2'
+svmat a, names(col)
+
+tempvar mina1 mina2 maxa1 maxa2
+egen `mina1' = min(`a1')
+egen `mina2' = min(`a2')
+egen `maxa1' = max(`a1')
+egen `maxa2' = max(`a2')
+local mina1 = `mina1'
+local mina2 = `mina2'
+local maxa1 = `maxa1'+1.4
+local maxa1x = `maxa1'+0.3
+local maxa2 = `maxa2'
+
+local colors = "red blue black green ebblue mint erose orange maroon magenta mint gray teal navy olive sienna"
+local i = 1
+foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+}
+
+local i = 1
+local y = 1
+local c = 1
+local bas = `maxa2'+0.2
+local droite = max(`maxa1',0.2)
+
+foreach x in `partition' {
+ tokenize $scorename
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues j=`y'/`s' {
+ local a = `a1'[`j']
+ local b = `a2'[`j']
+ local call `call' || pcarrowi 0 0 `b' `a' "`var`j''", mlabcolor(`col`i'') color(`col`i'') head
+ }
+ local bas = `bas'-0.2
+ local call `call' text(`bas' `droite' "``i''", size(3) color(`col`i'')) /*`bas' `droite' "``i''", mlabcolor("`r' `g' `b'")*/
+ local `++i'
+ local y = `s'+1
+ local `++c'
+}
+
+
+if "`html'" != "" {
+ qui local saving "saving(`c(tmpdir)'/`html'_items,replace) nodraw"
+ qui twoway `call' name("items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) title("Correlations between items") xtitle("") ytitle("") xsize(`xsize') ysize(`ysize') `saving'
+ qui graph use `c(tmpdir)'/`html'_items.gph
+ qui graph export `c(tmpdir)'/`html'_items.eps, replace
+ di ""
+}
+else {
+ qui twoway `call' name("Biplot_items",replace) legend(off) xscale(range(`mina1' `maxa1x')) yscale(range(`mina2' `maxa2')) xtitle("") ytitle("")
+}
+
+
+
+end
+
+/* convdiv */
+
+capture program drop convdiv
+program convdiv
+syntax varlist, PARTition(numlist integer >0) [TCONVdiv(real 0.4) convdivboxplots]
+preserve
+
+//qui set autotabgraphs on
+
+
+
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local nbvars : word count `varlist'
+local P:word count `partition'
+local cptdiv = 0
+local cptconv = 0
+
+if ${exist} != 1 {
+
+ qui detect2 `varlist', partition(`partition')
+
+ matrix A = r(Corrrestscores)
+ matrix B = r(Corrscores)
+
+ local i = 1
+ local y = 1
+
+ foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ matrix B[`z',`i'] = A[`z',`i']
+ }
+ local `i++'
+ local y = `s'+1
+ }
+
+ matrix colnames B = $scorename
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix}"
+ di "{hline 105}"
+ di
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ /*if "${html}" != "" {
+ di ""
+ di _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di in red _col(`col') "{bf:`t'}" _c
+ //}
+
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{bf:`t'}" _c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{bf:`t'}" _c
+ //}
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ /*if "${html}" != "" {
+ di ""
+ di in red _col(`col') "`t'" _c
+ di ""
+ }*/
+ //else {
+ di in red _col(`col') "`t'" _c
+ //}
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ /*if "${html}" != "" {
+ di ""
+ di as text _col(`col') "{text:`t'}"_c
+ di "
"
+ }*/
+ //else {
+ di as text _col(`col') "{text:`t'}"_c
+ //}
+
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di as text "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+
+}
+
+else if ${exist} == 1 {
+
+ di as result "{hline 105}"
+ di "{bf:Correlation matrix (without rest-scores)}"
+ di "{hline 105}"
+ di
+
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local dec = 10
+ local col = `dec'
+
+ local decit = 14
+ local colit = `decit'
+
+ local col1 = `decit'
+ forvalues i=1/`P' {
+ di _col(`col1') "{bf:`s`i''}" _c
+ local col1 = `col1' + `dec'
+ }
+
+ di
+ local h = (`P'-1)*`dec'+`decit'+4
+ di "{hline `h'}"
+
+ qui corr $scorename `varlist'
+ matrix c = r(C)
+ matrix B = c[`=`P'+1'..`nbvars'+`P',1..`P']
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ foreach p in `partition' {
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues z = `y'/`s' {
+ di as text "{bf:`var`z''}" _c
+ local col = `decit'-1
+
+ local dd = `z' // [count cptdiv (one per item)]
+
+ forvalues k = 1/`P' {
+
+ local t = B[`z',`k']
+ local t : di %6.3f `t'
+ if `k' == `i' {
+ if `t' < `tconvdiv' {
+ di in red _col(`col') "{bf:`t'}" _c
+ local cptconv = `cptconv'+1
+ local col = `col' + `dec'
+ }
+ else {
+ di _col(`col') "{bf:`t'}" _c
+ local col = `col' + `dec'
+ }
+ }
+ else {
+
+ if B[`z',`k'] > B[`z',`i'] {
+ di in red _col(`col') "`t'" _c
+
+ if `dd' == `z' local cptdiv = `cptdiv'+1 // [one per item]
+ local dd = 0
+ local col = `col' + `dec'
+ }
+ else {
+ di as text _col(`col') "{text:`t'}"_c
+ local col = `col' + `dec'
+ }
+ }
+ }
+ di
+ }
+ di "{dup `h':-}"
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ }
+
+ local y = 1
+ local h = 1
+ local np : word count `partition'
+
+ foreach p in `partition' {
+ if `h' == 1 local s = `p'
+ else local s = `s' +`p'
+
+ forvalues j = 1/`np' {
+ mat C_`h'_`j' = B[`y'..`s',`j']
+
+ tempvar tp_`h'_`j'
+ mat colnames C_`h'_`j' = `tp_`h'_`j''
+
+ svmat C_`h'_`j', names(col)
+ }
+
+ local `++h'
+ local y = `s'+1
+ }
+}
+
+if "`convdivboxplots'" != "" {
+
+ if "${html}" != "" {
+ local html = "${html}"
+ di "
"
+ di ""
+
+
+ local colors = "red blue green orange maroon magenta ebblue mint erose gray teal navy olive sienna"
+ local i = 1
+ foreach c in `colors' {
+ local col`i' = "`c'"
+ local `++i'
+ }
+
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`col`j'') lcolor(`col`j'')) marker(`j', mcolor(`col`j''))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_Conv_div_``h'',replace) nodraw"
+ qui graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black)) `saving'
+ qui graph use `c(tmpdir)'/`html'_Conv_div_``h''.gph
+ qui graph export `c(tmpdir)'/`html'_Conv_div_``h''.eps, replace
+
+ di "
"
+
+
+
+ //qui set autotabgraphs on
+ }
+ di "
"
+ di ""
+ }
+
+ else {
+ forvalues h = 1/`np' {
+ tokenize $scorename
+ local call = ""
+ local callbox = ""
+ local callleg = ""
+
+ forvalues j = 1/`np' {
+ local call `call' `tp_`h'_`j''
+ local callbox `callbox' box(`j',fcolor(`color') lcolor(`color')) marker(`j', mcolor(`color'))
+ local lab = "``j''"
+ local lab = `"`lab'"'
+ local callleg `callleg' `j' "`lab'"
+ }
+ graph box `call', name("Conv_div_``h''",replace) `callbox' legend(order(`"`callleg'"') stack rows(1) size(small)) title(Correlations between items of ``h'' and scores) yline(`tconvdiv', lpattern(dot) lcolor(black))
+ qui set autotabgraphs on
+ }
+ }
+}
+
+
+local t : di %5.3f `tconvdiv'
+local p1 = (`nbvars'-`cptconv')/`nbvars'*100
+local p1 : di %4.1f `p1'
+local p2 = (`nbvars'-`cptdiv')/`nbvars'*100
+local p2 : di %4.1f `p2'
+
+di
+di as result "Convergent validity:" _c
+di as text " `=`nbvars'-`cptconv''/`nbvars' items (`p1'%) have a correlation coefficient with the score of "
+di _col(22) "their own dimension greater than `t'"
+di
+di as result "Divergent validity:" _c
+di as text " `=`nbvars'-`cptdiv''/`nbvars' items (`p2'%) have a correlation coefficient with the score"
+di _col(22) "of their own dimension greater than those computed with other scores."
+
+end
+
+/* cfa */
+
+capture program drop cfa
+program cfa,rclass
+syntax varlist, PARTition(numlist integer >0) [CFAMethod(string) CFAStand CFACov(string) CFAAuto]
+preserve
+
+local nbvars:word count `varlist'
+local P:word count `partition'
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+if "`cfaauto'" != "" & "`cfacov'" != "" {
+ di in red "You cannot use both cfacov() and cfaauto"
+ exit 119
+}
+
+if "`cfacov'" != "" {
+
+ lstrfun v, subinstr("`cfacov'","*"," ",.)
+ foreach var in `v' {
+ capture confirm variable `var'
+ if _rc {
+ di in red "error in cfacov() option : `var' is not a variable from the dataset"
+ exit 119
+ }
+ }
+ lstrfun s, subinstr("`cfacov'","* ","*",.)
+ lstrfun s, subinstr("`s'"," *","*",.)
+ lstrfun s, subinstr("`s'","*","*e.",.)
+ lstrfun f, subinstr("`s'"," "," e.",.)
+ local g e.`f'
+ lstrfun g , lower("`g'")
+ local covs `g'
+}
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = lower("`x'")
+ qui rename `x' `var`i''
+ local `++i'
+}
+
+local upscorename = upper("$scorename")
+
+local i = 0
+local y = 1
+tokenize `upscorename'
+foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ local liste = ""
+ forvalues w = `y'/`s' {
+ local liste `liste' `var`w''
+ }
+
+ local a = "(``i'' -> `liste')"
+ local zz `zz' `a'
+
+ local y = `s'+1
+}
+
+if "`cfamethod'" == "" local cfamethod = "ml"
+
+if "`cfamethod'" != "ml" & "`cfamethod'" != "mlmv" & "`cfamethod'" != "adf" {
+ di "`cfamethod'"
+ di in red "option cfamethod incorrectly specified (choose among ml, mlmv and adf)"
+ error 198
+}
+
+if "`cfastand'" != "" local cfastand = "stand"
+
+di as result "{hline 105}"
+di "{bf:Confirmatory factor analysis}"
+di as result "{hline 105}"
+
+local ii = 1
+local s
+
+while `ii' == 1 | "`s'" != "" {
+
+ if "`covs'" != "" & "`cfaauto'" != "" di _n "{bf:step `ii':} {text:`s'}"
+ qui sem `zz', method(`cfamethod') `cfastand' cov(`covs') iterate(50)
+
+ /* factor loadings */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix a = a\b
+ }
+
+ /* standard error factor loadings*/
+
+ matrix r = r(table)
+ matrix r = r[2,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sef = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sef = sef\b
+ }
+
+
+ /* intercepts */
+
+ matrix r = r(table)
+ matrix r = r[1,1...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix a2 = r[2,1]
+ forvalues i=4(2)`n' {
+ matrix b = r[`i',1]
+ matrix a2 = a2\b
+ }
+
+
+ /* standard error intercepts*/
+
+ matrix r = r(table)
+ matrix r = r[2,2...]
+ matrix r = r'
+ local n = `nbvars'*2
+
+ matrix sei = r[1,1]
+ forvalues i=3(2)`n' {
+ matrix b = r[`i',1]
+ matrix sei = sei\b
+ }
+
+ //mat li sei
+ /* error variances */
+
+ local m = `n'+1
+ matrix r = r(table)
+ //mat li r
+ matrix r = r[1,`m'...]
+ matrix r = r'
+
+ matrix a3 = r[1,1]
+ forvalues i=2/`nbvars' {
+ matrix b = r[`i',1]
+ matrix a3 = a3\b
+ }
+
+ /* variance of dimensions*/
+
+ matrix r = r(table)
+ local n = `nbvars'*3+1
+ matrix r = r[1,`n'...]
+ matrix r = r'
+
+ matrix var = r[1,1]
+ forvalues i=2/`P' {
+ matrix b = r[`i',1]
+ matrix var = var\b
+ }
+
+ if "`cfaauto'" != "" {
+ qui estat mindices, showpclass(mcons merrvar)
+ matrix m = r(mindices_pclass)
+ local r : colfullnames m
+ if "`r'" == "c1" local r
+ lstrfun e , subinstr("`r'","cov(","",.)
+ lstrfun d , subinstr("`e'",")","",.)
+ lstrfun d , subinstr("`d'",":_cons","",.)
+ lstrfun d , subinstr("`d'","e.","",.)
+ lstrfun d , subinstr("`d'",","," ",.)
+
+ tokenize "`d'"
+ local y = 1
+ local i = 0
+ foreach x in `partition' {
+ local `i++'
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues w = `y'/`s' {
+ local class_`var`w'' = `i'
+ }
+ local y = `s'+1
+ }
+
+ tokenize "`d'"
+ local i = 1
+ local l : word count ("`d'")
+ forvalues k = 1/`=`l'/2' {
+ local j = `i'+1
+ if "`class_``i'''" != "`class_``j'''" {
+ lstrfun d , subinstr("`d'","``i'' ``j''","",1)
+ lstrfun d , itrim("`d'")
+ }
+ local i = `i'+2
+ }
+ local cfacov = "`d'"
+
+ local s
+ local i = 1
+ tokenize "`d'"
+ foreach k in `d' {
+ local t = mod(`i',2)
+ if `t' == 0 local s `s' e.`k'
+ else local s `s' e.`k'*
+ local `++i'
+ }
+
+ lstrfun s , subinstr("`s'","* ","*",.)
+ local covs `covs' `s'
+ }
+ if e(converged) == 0 di in red "Warning : model did not converge after 50 iterations"
+ local `++ii'
+}
+
+local i = 1
+foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+}
+
+local i = 1
+foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+
+}
+
+local max = 10
+local dec = `max'+5
+
+local max2 = 10
+
+local dec2 = `dec'+`max2'+5
+
+local a = e(N)
+di
+if e(converged) == 0 di in red "Warning : model did not converge after 50 iterations"
+di
+if "`covs'" != "" {
+ di as result "{bf:Covariances between errors added:} {text:`covs'}"
+ di
+}
+di "{bf:Number of used individuals: } {text:`a'}"
+di
+//di _col(`=`dec2'+17+4') "{bf:Estimation:}"
+
+
+di as result "{bf:Item}" _c
+di _col(`dec') "{bf:Dimension}" _c
+di _col(`dec2') "{bf:Factor}" _c
+di _col(`=`dec2'+14') "{bf:Standard}" _c
+di _col(`=`dec2'+28') "{bf:Intercept}" _c
+di _col(`=`dec2'+43') "{bf:Standard}" _c
+
+if "`cfastand'" == "" {
+ di _col(`=`dec2'+57') "{bf:Error}" _c
+ di _col(`=`dec2'+66') "{bf:Variance of}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+43') "{bf:error}" _c
+ di _col(`=`dec2'+55') "{bf:variance}" _c
+ di _col(`=`dec2'+67') "{bf:dimension}"
+ local h = `dec2'+76
+}
+else {
+ di _col(`=`dec2'+57') "{bf:Error}"
+ di _col(`dec2') "{bf:loading}" _c
+ di _col(`=`dec2'+14') "{bf:error}" _c
+ di _col(`=`dec2'+44') "{bf:error}" _c
+ di _col(`=`dec2'+57') "{bf:variance}"
+ local h = `dec2'+62
+}
+
+di "{hline `h'}"
+
+local i = 1
+local y = 1
+foreach x in `partition' {
+ if `i' == 1 local s = `x'
+ else local s = `s' +`x'
+
+ forvalues z = `y'/`s' {
+ tokenize `sc'
+ di "{bf:`var`z''}"_c
+ di _col(`dec') "{bf:``i''}" _c
+ local t = a[`z',1]
+ local t : di %7.2f `t'
+ di _col(`dec2') "{text:`t'}" _c
+
+ local t = sef[`z',1]
+ local t : di %8.2f `t'
+ di _col(`=`dec2'+14') "{text:`t'}" _c
+
+ local t = a2[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+28') "{text:`t'}" _c
+
+ local t = sei[`z',1]
+ local t : di %9.2f `t'
+ di _col(`=`dec2'+42') "{text:`t'}" _c
+
+ local t = a3[`z',1]
+ local t : di %11.2f `t'
+
+ if "`cfastand'" == "" & `z' == `y'{
+ di _col(`=`dec2'+52') "{text:`t'}" _c
+ local t = var[`i',1]
+ local t : di %11.2f `t'
+ di _col(`=`dec2'+66') "{text:`t'}"
+ }
+ else di _col(`=`dec2'+52') "{text:`t'}"
+ }
+ di
+ local `i++'
+ local y = `s'+1
+}
+
+qui estat gof, stats(all)
+
+local chi2 = r(chi2_ms)
+local p = r(p_ms)
+local ddl = r(df_ms)
+local ratio = `chi2'/`ddl'
+local rmsea = r(rmsea)
+local lb = r(lb90_rmsea)
+local ub = r(ub90_rmsea)
+local nfi = 1-(r(chi2_ms)/r(chi2_bs))
+local rni = 1-(r(chi2_ms)-r(df_ms))/(r(chi2_bs)-r(df_bs))
+local cfi = r(cfi)
+local ifi = (r(chi2_bs)-r(chi2_ms))/(r(chi2_bs)-r(df_ms))
+local mci = exp(-0.5*((r(chi2_ms)-r(df_ms))/(e(N)-1)))
+local srmr = r(srmr)
+
+di
+di "{bf:Goodness of fit:}"
+di
+
+
+
+if "${html}" != "" {
+
+di as result _col(4) "chi2" _c
+di as result _col(20) "ddl" _c
+di as result _col(28) "chi2/ddl" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI"
+
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}"
+
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+di as result _col(4) "CFI" _c
+di as result _col(15) "IFI" _c
+di as result _col(26) "MCI"
+local t : di %5.3f `cfi'
+di _col(4) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(15) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(26) "{text:`t'}"
+di as result
+}
+else {
+di as result _col(4) "chi2" _c
+di as result _col(20) "ddl" _c
+di as result _col(28) "chi2/ddl" _c
+di as result _col(42) "RMSEA [90% CI]" _c
+di as result _col(64) "SRMR" _c
+di as result _col(74) "NFI" _c
+di as result _col(84) "RNI" _c
+di as result _col(94) "CFI" _c
+di as result _col(104) "IFI" _c
+di as result _col(114) "MCI"
+
+local t : di %7.2f `chi2'
+di "{text:`t'}" _c
+local t : di %3.0f `ddl'
+di _col(20) "{text:`t'}" _c
+local t : di %7.1f `ratio'
+di _col(29) "{text:`t'}" _c
+local t : di %5.3f `rmsea'
+local l : di %5.3f `lb'
+local u : di %5.3f `ub'
+di _col(40) "{text:`t' [`l' ; `u']}" _c
+local t : di %5.3f `srmr'
+di _col(63) "{text:`t'}" _c
+local t : di %5.3f `nfi'
+di _col(72) "{text:`t'}" _c
+local t : di %5.3f `rni'
+di _col(82) "{text:`t'}" _c
+local t : di %5.3f `cfi'
+di _col(92) "{text:`t'}" _c
+local t : di %5.3f `ifi'
+di _col(102) "{text:`t'}" _c
+local t : di %5.3f `mci'
+di _col(112) "{text:`t'}"
+local p : di %5.3f `p'
+di "{text:(p-value = `p')}"
+di as result
+
+}
+end
+
+/* repet */
+
+capture program drop repet
+program repet,rclass
+syntax varlist, PARTition(numlist integer >0) [t2(varlist) KAPpa ICKAPpa(integer 0)]
+preserve
+
+local nbvars : word count `varlist'
+
+if `ickappa' <= 0 {
+ local ickappa = ""
+}
+
+local C = 0
+foreach z in `partition' {
+ local C = `C' + `z'
+}
+
+local P:word count `partition'
+
+if "$scores2" != "" {
+ local t:word count $scores2'
+ if `P' != `t' {
+ di in red "The number of score names given in scores2() is different from the number of scores defined"
+ exit 119
+ }
+}
+
+if "`t2'" != "" {
+
+ local i = 1
+ foreach s in $scorename {
+ local s`i' = abbrev("`s'",10)
+ local sc `sc' `s`i''
+ local `++i'
+ }
+
+ local i = 1
+ foreach v in `varlist' {
+ local var`i' = abbrev("`v'",10)
+ local `++i'
+ }
+
+ local maxit = 1
+ forvalues i=1/`nbvars' {
+ local len = length("`var`i''")
+ if `len' > `maxit' local maxit = `len'
+ }
+
+ local decit = `maxit' + 4
+ local colit = `decit'
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ if "$scores2" == "" {
+ foreach sco in $scorename {
+ *local t = "`sco'bis"
+ tempname s
+ local scorename2 `scorename2' `s'
+ }
+
+ qui calcscore `t2', scorename(`scorename2') partition(`partition') compscore(${compscore}) modalities($modalities)
+
+ }
+
+ else {
+ foreach sco in $scores2 {
+ local scorename2 `scorename2' `sco'
+ }
+ }
+
+ local i = 1
+ foreach var in `varlist' {
+ tokenize `t2'
+ qui kap `var' ``i''
+ local k`i' = r(kappa)
+ if "`ickappa'" != "" {
+ qui kapci `var' ``i'', reps(`ickappa')
+ local lbk`i' = r(lb_bc)
+ local ubk`i' = r(ub_bc)
+ }
+ local `++i'
+ }
+
+ local i = 1
+ foreach s in $scorename {
+ tokenize `scorename2'
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize `sc'
+ local max = length("dimension")
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+ di "{bf:Dimension}" _c
+ di _col(`=`dec'+2') "{bf:n}" _c
+ local col = `dec'+6
+ di _col(`col') "{bf:Item}" _c
+ local col = `col'+`decit'
+
+ if "`kappa'" != "" {
+ di _col(`col') "{bf:Kappa}" _c
+ local col = `col'+10
+ if "`ickappa'" != "" {
+ di _col(`col') "{bf:95% CI for Kappa}" _c
+ local col = `col'+20
+ }
+
+ }
+
+ di _col(`=`col'+2') "{bf:ICC}" _c
+ local col = `col'+9
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ local zz = 0
+ foreach var in `varlist' {
+ qui levelsof `var', local(levels)
+ local z : word count `levels'
+ if `z' > 2 local zz = 1
+ }
+
+ if "`kappa'" != "" & "`ickappa'" != "" & `zz' == 1 {
+ local col = `dec'+`decit'+16
+ di _col(`col') "{bf:(bootstrapped)}"
+ }
+
+
+ if "`ickappa'" != "" local h = `dec'+6+`decit'+10+8+21+12+1
+ else if "`kappa'" != "" local h = `dec'+6+`decit'+10+8+21+12-20
+ else local h = `dec'+6+`decit'+10+8+21+12-29
+ di "{hline `h'}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize `sc'
+ di "{bf:``i''}" _c
+ di _col(`dec') "{text:`n`i''}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+6
+ di _col(`col') "{text:`var`y''}" _c
+
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`y''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`i''
+ local ubk : di %5.2f `ubk`i''
+ local col = `col'+11
+ di _col(`col') "{text:[`lbk' ; `ubk']}" _c
+ local col = `decit'+50
+ }
+
+ else local col = `decit'+30
+ }
+ else local col = `decit'+20
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+8
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ forvalues z = `w'/`s' {
+ local col = `dec'+6
+ di _col(`col') "{text:`var`z''}" _c
+ if "`kappa'" != "" {
+ local k : di %5.2f `k`z''
+ local col = `col'+`decit'
+ di _col(`col') "{text:`k'}" _c
+ if "`ickappa'" != "" {
+ local lbk : di %5.2f `lbk`z''
+ local ubk : di %5.2f `ubk`z''
+ local col = `col'+11
+ di _col(`col')"{text:[`lbk' ; `ubk']}"
+ }
+ else di
+
+ }
+ else di
+ }
+ local `i++'
+ local `j++'
+ local y = `s'+1
+ di
+ }
+}
+
+else {
+ local i = 1
+ foreach s in $scorename {
+ tokenize $scores2
+ tempname score id temps
+ qui gen `id' = _n
+ qui gen `score'_1 = `s'
+ qui gen `score'_2 = ``i'' if ``i''!=.
+ qui reshape long `score'_, i(`id') j(`temps')
+ qui icc `score'_ `id'
+ local n`i' = r(N_target)
+ local icc`i' = r(icc_i)
+ local lb`i' = r(icc_i_lb)
+ local ub`i' = r(icc_i_ub)
+ qui sort `id'
+ qui duplicates drop `id', force
+ local `++i'
+ }
+
+ tokenize $scorename
+ local max = length("dimension")
+
+ local h = 1
+ foreach s in $scorename {
+ local s`h' = abbrev("`s'",10)
+ local sc `sc' `s`h''
+ local `++h'
+ }
+
+ forvalues j=1/`P' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `max' local max = `len`j''
+ }
+
+ local dec = `max' + 5
+
+ local i = 1
+ local j = 1
+ local y = 1
+
+ di as result "{hline 105}"
+ di as result "{bf:Reproducibility}"
+ di as result "{hline 105}"
+ di
+
+ di "{bf:Dimension}" _c
+ local col = `dec'
+ di _col(`col') "{bf:n}" _c
+
+
+ di _col(`=`col'+6') "{bf:ICC}" _c
+ local col = `col'+14
+ di _col(`col') "{bf:95% CI for ICC}"
+
+ di "{hline 50}"
+
+ local i = 1
+ foreach p in `partition' {
+ tokenize $scorename
+ di "{bf:``i''}" _c
+ local n : di % 4.0f `n`i''
+ di _col(`=`dec'-3') "{text:`n'}" _c
+ if `j' == 1 local s = `p'
+ else local s = `s' +`p'
+ local col = `dec'+4
+
+ local icc : di %5.2f `icc`i''
+ di _col(`col') "{text:`icc'}" _c
+ local lb : di %5.2f `lb`i''
+ local ub : di %5.2f `ub`i''
+ local col = `col'+9
+ di _col(`col')"{text:[`lb' ; `ub']}"
+ local w = `y'+1
+
+ local `i++'
+ }
+}
+
+end
+
+
+/* kgv */
+
+capture program drop kgv
+program kgv,rclass
+syntax varlist, categ(varlist) [KGVBoxplots KGVGroupboxplots]
+
+foreach c in `categ' {
+ tempname j
+ capture encode `c', generate(`j')
+ capture confirm variable `j'
+ if _rc local j = "`c'"
+ local categ2 `categ2' `j'
+}
+
+local i = 1
+local j = 1
+local k = 0
+local max = 0
+local a : word count `categ'
+local nb:word count `varlist'
+
+di as result "{hline 105}"
+di "{bf:Known-groups validity}"
+di as result "{hline 105}"
+di
+
+foreach sco in `varlist' {
+ foreach cat in `categ2' {
+ local nblev = 0
+ local maxlen`j' = 0
+ qui anova `sco' `cat'
+ local p`i'_`j' = Ftail(e(df_m), e(df_r), e(F))
+ qui levelsof `cat', local(levels)
+ local lbe : value label `cat'
+
+ foreach l of local levels {
+ qui count if `sco' !=. & `cat' == `l'
+ local `++k'
+ local eff`i'_`j'_`k' = r(N)
+
+ if "`lbe'" != "" {
+ local ll`j'_`k' : label `lbe' `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ else {
+ local ll`j'_`k' = `l'
+ local len = length("`ll`j'_`k''")
+ if `len' > 10 {
+ local c = substr("`ll`j'_`k''",1,9)
+ local d = substr("`ll`j'_`k''",-1,1)
+ local ll`j'_`k' "`c'" "~" "`d'"
+ }
+ local w = length("`ll`j'_`k''")
+ if `w' > `maxlen`j'' local maxlen`j' = `w'
+ }
+ qui su `sco' if `cat' == `l'
+ local m`i'_`j'_`k' = r(mean)
+ local s`i'_`j'_`k' = r(sd)
+ local nblev = `nblev' + 1
+ }
+ if `nblev' > `max' local max = `nblev'
+ local `++j'
+ local k = 0
+ }
+ local `++i'
+ local j = 1
+}
+
+local i = 1
+foreach s in `varlist' {
+ local s`i' = abbrev("`s'",7)
+ local sc `sc' `s`i''
+ local `++i'
+}
+
+local maxs = 0
+forvalues j=1/`nb' {
+ local len`j' = length("`s`j''")
+ if `len`j'' > `maxs' local maxs = `len`j''
+}
+
+local i = 1
+local k = 0
+local j = 2
+
+foreach cat in `categ'{
+ local `++k'
+ tokenize `categ'
+ local c`k' = "``i'' ``j''"
+ local i = `i' + 2
+ local j = `j' + 2
+}
+
+
+local d = 1
+local f = 2
+forvalues h = 1/`a' {
+ if `f' > `a' local f = `f'-1
+ local j = 1
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`col') "{bf:`cat'}" _c
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+ di
+
+ local j = `d'
+ local col = `maxs'+6
+ foreach cat in `c`h'' {
+ di _col(`=`col'+`maxlen`j''+5') "{bf: mean }" _c
+ di "{bf: sd }" _c
+ di "{bf:p-value}" _c
+
+ local col = `col' + `maxlen`j'' + 5 + 40
+ local `++j'
+ }
+
+ local j = `d'
+ local col = `maxs'+6
+
+ di
+ di
+ local i = 1
+ local col = `maxs'+6
+
+ forvalues g = 1/`nb' {
+
+ di "{bf:`s`g''}" _c
+ forvalues k = 1/`max' {
+ forvalues j = `d'/`f' {
+
+ di _col(`col') "{bf:`ll`j'_`k''} " _c
+ if "`eff`i'_`j'_`k''" != "" di as text "(n=`eff`i'_`j'_`k'')" _c
+ local m : di %6.2f `m`i'_`j'_`k''
+ di _col(`=`col'+`maxlen`j''+10') "{text:`m'} " _c
+
+ local s : di %8.2f `s`i'_`j'_`k''
+ di "{text: `s'} " _c
+
+ if `k' == 1 {
+ local p : di %8.3f `p`i'_`j''
+ di _col(`=`col'+31') "{text:`p'} " _c
+ }
+ local col = `col' + `maxlen`j'' + 5 + 40
+ }
+ di
+ local col = `maxs'+6
+
+ }
+ di
+
+ local `++i'
+
+ }
+ local d = `d'+2
+ local f = `f'+2
+ if `d' > `a' continue, break
+ di
+}
+
+if "`kgvboxplots'" != "" {
+ local html = "${html}"
+ if "`html'" != "" {
+ di "
"
+ di ""
+ if "`kgvgroupboxplots'" != "" {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") nodraw
+
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph export `c(tmpdir)'/`html'_kgv`s'.eps, replace
+
+
+ local g `g' `s'_`c'
+ }
+ }
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv,replace) nodraw"
+ qui gr combine `g', name(kgv,replace) `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv.gph
+ qui graph export `c(tmpdir)'/`html'_kgv.eps, replace
+ di "
"
+
+ }
+ else {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ //graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'")
+
+ qui local saving "saving(`c(tmpdir)'/`html'_kgv`s',replace) nodraw"
+ qui graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") `saving'
+ qui graph use `c(tmpdir)'/`html'_kgv`s'.gph
+ qui graph export `c(tmpdir)'/`html'_kgv`s'.eps, replace
+ di "
"
+
+ local g `g' `s'_`c'
+ }
+ }
+ }
+ di "
"
+ di ""
+
+ }
+ else {
+ if "`kgvgroupboxplots'" != "" {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'") nodraw
+ local g `g' `s'_`c'
+ }
+ }
+ gr combine `g', name(Known_groups_validity,replace)
+ }
+ else {
+ foreach c in `categ' {
+ foreach s in `varlist' {
+ graph box `s', over(`c') name("`s'_`c'",replace) b1title("`c'")
+ local g `g' `s'_`c'
+ }
+ }
+ }
+ }
+}
+
+end
+
+
+/* conc */
+
+capture program drop conc
+program conc,rclass
+syntax varlist, comp(varlist) [tconc(real 0.4)]
+
+di as result "{hline 105}"
+di "{bf:Concurrent validity}"
+di as result "{hline 105}"
+di
+
+local n : word count `varlist'
+local p : word count `comp'
+
+matrix m = J(`n',`p',.)
+matrix rownames m = `varlist'
+matrix colnames m = `comp'
+local r = 1
+
+foreach i in `varlist' {
+ local c = 1
+ foreach j in `comp' {
+ qui corr `i' `j'
+ mat e = r(C)
+ local f = e[2,1]
+ mat m[`r',`c'] = `f'
+ local `++c'
+ }
+ local `++r'
+}
+
+tokenize `varlist'
+local maxv = length("`1'")
+forvalues i=1/`n' {
+ local lenv = length("``i''")
+ if `lenv' > `maxv' local maxv = `lenv'
+}
+
+local decv = `maxv'+6
+
+tokenize `comp'
+local maxc = length("`1'")
+forvalues i=1/`p' {
+ local lenc = length("``i''")
+ if `lenc' > `maxc' local maxc = `lenc'
+}
+
+local decc = `maxc'+4
+
+local col = `decv'
+foreach c in `comp' {
+ di as result _col(`col') "`c'" _c
+ local col = `col'+`decc'
+}
+di
+
+local i = 1
+foreach x in `varlist' {
+ local var`i' = "`x'"
+ local `++i'
+}
+
+forvalues i=1/`n' {
+ di as result "`var`i''" _c
+ local col = `decv'
+ forvalues j=1/`p' {
+ local t = m[`i',`j']
+ if `t' > `tconc' | `t' < -`tconc' {
+ di as result _col(`=`col'-1') %5.2f `t' _c
+ }
+ else di as text _col(`=`col'-1') %5.2f `t' _c
+ local col = `col'+`decc'
+ }
+ di
+}
+
+capture restore, not
+end
+
diff --git a/Modules/ado/personal/w/whist.ado b/Modules/ado/personal/w/whist.ado
new file mode 100644
index 0000000..c5d1f77
--- /dev/null
+++ b/Modules/ado/personal/w/whist.ado
@@ -0,0 +1,12 @@
+program define whist, rclass
+version 9 /* si chgt version*/
+syntax varname [aweight iweight fweight pweight/] [,title(string)] /*pond posssibles*/
+di "varname :`varlist'"
+tempname varpond
+qui su `exp' if `varlist'!=.
+qui gen `varpond'=`exp'/r(sum)*100
+label variable `varpond' "fréquence"
+label variable `varlist' "`varlist'"
+graph bar (sum) `varpond', over(`varlist') blabel(bar, format (%4.1f)) title(`title') ytitle(pourcentage) b1title(`varlist')
+end
+
diff --git a/Modules/ado/personal/zip/backrasch2.zip b/Modules/ado/personal/zip/backrasch2.zip
new file mode 100644
index 0000000..4285fd3
Binary files /dev/null and b/Modules/ado/personal/zip/backrasch2.zip differ
diff --git a/Modules/ado/personal/zip/clv214.zip b/Modules/ado/personal/zip/clv214.zip
new file mode 100644
index 0000000..7062047
Binary files /dev/null and b/Modules/ado/personal/zip/clv214.zip differ
diff --git a/Modules/ado/personal/zip/detect31.zip b/Modules/ado/personal/zip/detect31.zip
new file mode 100644
index 0000000..88a2be4
Binary files /dev/null and b/Modules/ado/personal/zip/detect31.zip differ
diff --git a/Modules/ado/personal/zip/gammasym.zip b/Modules/ado/personal/zip/gammasym.zip
new file mode 100644
index 0000000..7d38697
Binary files /dev/null and b/Modules/ado/personal/zip/gammasym.zip differ
diff --git a/Modules/ado/personal/zip/gammasym22.zip b/Modules/ado/personal/zip/gammasym22.zip
new file mode 100644
index 0000000..b4fb485
Binary files /dev/null and b/Modules/ado/personal/zip/gammasym22.zip differ
diff --git a/Modules/ado/personal/zip/gausshermite1.zip b/Modules/ado/personal/zip/gausshermite1.zip
new file mode 100644
index 0000000..025b0a4
Binary files /dev/null and b/Modules/ado/personal/zip/gausshermite1.zip differ
diff --git a/Modules/ado/personal/zip/geekel2d43.zip b/Modules/ado/personal/zip/geekel2d43.zip
new file mode 100644
index 0000000..7222720
Binary files /dev/null and b/Modules/ado/personal/zip/geekel2d43.zip differ
diff --git a/Modules/ado/personal/zip/gengroup12.zip b/Modules/ado/personal/zip/gengroup12.zip
new file mode 100644
index 0000000..c3896df
Binary files /dev/null and b/Modules/ado/personal/zip/gengroup12.zip differ
diff --git a/Modules/ado/personal/zip/hcavar32.zip b/Modules/ado/personal/zip/hcavar32.zip
new file mode 100644
index 0000000..e72848b
Binary files /dev/null and b/Modules/ado/personal/zip/hcavar32.zip differ
diff --git a/Modules/ado/personal/zip/imputeitems.zip b/Modules/ado/personal/zip/imputeitems.zip
new file mode 100644
index 0000000..d7b6b87
Binary files /dev/null and b/Modules/ado/personal/zip/imputeitems.zip differ
diff --git a/Modules/ado/personal/zip/imputeitems24.zip b/Modules/ado/personal/zip/imputeitems24.zip
new file mode 100644
index 0000000..53d50d2
Binary files /dev/null and b/Modules/ado/personal/zip/imputeitems24.zip differ
diff --git a/Modules/ado/personal/zip/imputemok21.zip b/Modules/ado/personal/zip/imputemok21.zip
new file mode 100644
index 0000000..5cd69a5
Binary files /dev/null and b/Modules/ado/personal/zip/imputemok21.zip differ
diff --git a/Modules/ado/personal/zip/imputerasch2.zip b/Modules/ado/personal/zip/imputerasch2.zip
new file mode 100644
index 0000000..c587400
Binary files /dev/null and b/Modules/ado/personal/zip/imputerasch2.zip differ
diff --git a/Modules/ado/personal/zip/loevH.zip b/Modules/ado/personal/zip/loevH.zip
new file mode 100644
index 0000000..21c92bd
Binary files /dev/null and b/Modules/ado/personal/zip/loevH.zip differ
diff --git a/Modules/ado/personal/zip/loevh8.zip b/Modules/ado/personal/zip/loevh8.zip
new file mode 100644
index 0000000..9e20e9c
Binary files /dev/null and b/Modules/ado/personal/zip/loevh8.zip differ
diff --git a/Modules/ado/personal/zip/mmsrm4.zip b/Modules/ado/personal/zip/mmsrm4.zip
new file mode 100644
index 0000000..269ee86
Binary files /dev/null and b/Modules/ado/personal/zip/mmsrm4.zip differ
diff --git a/Modules/ado/personal/zip/mohand.zip b/Modules/ado/personal/zip/mohand.zip
new file mode 100644
index 0000000..86b3215
Binary files /dev/null and b/Modules/ado/personal/zip/mohand.zip differ
diff --git a/Modules/ado/personal/zip/msp.zip b/Modules/ado/personal/zip/msp.zip
new file mode 100644
index 0000000..7b9daf1
Binary files /dev/null and b/Modules/ado/personal/zip/msp.zip differ
diff --git a/Modules/ado/personal/zip/msp81.zip b/Modules/ado/personal/zip/msp81.zip
new file mode 100644
index 0000000..1ef8655
Binary files /dev/null and b/Modules/ado/personal/zip/msp81.zip differ
diff --git a/Modules/ado/personal/zip/npirt.zip b/Modules/ado/personal/zip/npirt.zip
new file mode 100644
index 0000000..ff6557a
Binary files /dev/null and b/Modules/ado/personal/zip/npirt.zip differ
diff --git a/Modules/ado/personal/zip/raschfit4.zip b/Modules/ado/personal/zip/raschfit4.zip
new file mode 100644
index 0000000..e95b8ae
Binary files /dev/null and b/Modules/ado/personal/zip/raschfit4.zip differ
diff --git a/Modules/ado/personal/zip/raschpower1.4.zip b/Modules/ado/personal/zip/raschpower1.4.zip
new file mode 100644
index 0000000..1799c5c
Binary files /dev/null and b/Modules/ado/personal/zip/raschpower1.4.zip differ
diff --git a/Modules/ado/personal/zip/raschpower1.5.zip b/Modules/ado/personal/zip/raschpower1.5.zip
new file mode 100644
index 0000000..632cb8f
Binary files /dev/null and b/Modules/ado/personal/zip/raschpower1.5.zip differ
diff --git a/Modules/ado/personal/zip/raschpower1.zip b/Modules/ado/personal/zip/raschpower1.zip
new file mode 100644
index 0000000..1fb85bb
Binary files /dev/null and b/Modules/ado/personal/zip/raschpower1.zip differ
diff --git a/Modules/ado/personal/zip/raschpower2.zip b/Modules/ado/personal/zip/raschpower2.zip
new file mode 100644
index 0000000..27489c2
Binary files /dev/null and b/Modules/ado/personal/zip/raschpower2.zip differ
diff --git a/Modules/ado/personal/zip/raschpower32.zip b/Modules/ado/personal/zip/raschpower32.zip
new file mode 100644
index 0000000..04a340c
Binary files /dev/null and b/Modules/ado/personal/zip/raschpower32.zip differ
diff --git a/Modules/ado/personal/zip/raschtest.zip b/Modules/ado/personal/zip/raschtest.zip
new file mode 100644
index 0000000..245c6fd
Binary files /dev/null and b/Modules/ado/personal/zip/raschtest.zip differ
diff --git a/Modules/ado/personal/zip/raschtest8.zip b/Modules/ado/personal/zip/raschtest8.zip
new file mode 100644
index 0000000..18defd7
Binary files /dev/null and b/Modules/ado/personal/zip/raschtest8.zip differ
diff --git a/Modules/ado/personal/zip/raschtest86.zip b/Modules/ado/personal/zip/raschtest86.zip
new file mode 100644
index 0000000..a18572a
Binary files /dev/null and b/Modules/ado/personal/zip/raschtest86.zip differ
diff --git a/Modules/ado/personal/zip/raschtest87.zip b/Modules/ado/personal/zip/raschtest87.zip
new file mode 100644
index 0000000..ba49c50
Binary files /dev/null and b/Modules/ado/personal/zip/raschtest87.zip differ
diff --git a/Modules/ado/personal/zip/raschtestv7.zip b/Modules/ado/personal/zip/raschtestv7.zip
new file mode 100644
index 0000000..829355b
Binary files /dev/null and b/Modules/ado/personal/zip/raschtestv7.zip differ
diff --git a/Modules/ado/personal/zip/sf36fr13.zip b/Modules/ado/personal/zip/sf36fr13.zip
new file mode 100644
index 0000000..c2f992b
Binary files /dev/null and b/Modules/ado/personal/zip/sf36fr13.zip differ
diff --git a/Modules/ado/personal/zip/simirt.zip b/Modules/ado/personal/zip/simirt.zip
new file mode 100644
index 0000000..299bb45
Binary files /dev/null and b/Modules/ado/personal/zip/simirt.zip differ
diff --git a/Modules/ado/personal/zip/simirt34.zip b/Modules/ado/personal/zip/simirt34.zip
new file mode 100644
index 0000000..a07bc1f
Binary files /dev/null and b/Modules/ado/personal/zip/simirt34.zip differ
diff --git a/Modules/ado/personal/zip/simirt35.zip b/Modules/ado/personal/zip/simirt35.zip
new file mode 100644
index 0000000..6f955a8
Binary files /dev/null and b/Modules/ado/personal/zip/simirt35.zip differ
diff --git a/Modules/ado/personal/zip/traces33.zip b/Modules/ado/personal/zip/traces33.zip
new file mode 100644
index 0000000..c7dc2e1
Binary files /dev/null and b/Modules/ado/personal/zip/traces33.zip differ
diff --git a/Modules/ado/plus/_/_eststo.ado b/Modules/ado/plus/_/_eststo.ado
new file mode 100644
index 0000000..ce97524
--- /dev/null
+++ b/Modules/ado/plus/_/_eststo.ado
@@ -0,0 +1,28 @@
+*! version 1.0.4 09nov2007 Ben Jann
+
+program define _eststo, byable(onecall)
+ local caller : di _caller()
+ version 8.2
+ if "`_byvars'"!="" local by "by `_byvars'`_byrc0' : "
+ if inlist(`"`1'"',"clear","dir","drop") {
+ version `caller': `by'eststo `0'
+ }
+ else {
+ capt _on_colon_parse `0'
+ if !_rc {
+ local command `"`s(after)'"'
+ if `"`command'"'!="" {
+ local command `":`command'"'
+ }
+ local 0 `"`s(before)'"'
+ }
+ syntax [anything] [, Esample * ]
+ if `"`esample'"'=="" {
+ local options `"noesample `options'"'
+ }
+ if `"`options'"'!="" {
+ local options `", `options'"'
+ }
+ version `caller': `by'eststo `anything'`options' `command'
+ }
+end
diff --git a/Modules/ado/plus/_/_eststo.hlp b/Modules/ado/plus/_/_eststo.hlp
new file mode 100644
index 0000000..acde74f
--- /dev/null
+++ b/Modules/ado/plus/_/_eststo.hlp
@@ -0,0 +1 @@
+.h eststo
diff --git a/Modules/ado/plus/_/_get_mlogit_bv.ado b/Modules/ado/plus/_/_get_mlogit_bv.ado
new file mode 100644
index 0000000..49e581b
--- /dev/null
+++ b/Modules/ado/plus/_/_get_mlogit_bv.ado
@@ -0,0 +1,86 @@
+*! version 1.0.2 07oct2009 Ben Jann
+* - name change; restructured; new reshape algorithm
+* version 1.0.1 15sep2009 Scott Long
+* - reshape b to Stata 5 format
+* version 1.0.0 15sep2009 Ben Jann
+
+* get stata e(b) and e(V) from -mlogit- and reshape
+* to the format used by SPost based on Stata 5
+
+capture program drop _get_mlogit_bv
+capture program drop _remove_baseeq
+program _get_mlogit_bv
+ version 9
+ args b v
+ if `"`b'"'=="" | `"`v'"'=="" {
+ di as err "_get_mlogit_bv: names for b and v must be specified"
+ exit 198
+ }
+ if `"`e(cmd)'"'!="mlogit" {
+ di as err "_get_mlogit_bv: model not mlogit"
+ exit 498
+ }
+
+ // get copy of e(b) and e(V)
+ matrix `b' = e(b)
+ matrix `v' = e(V)
+
+ // remove base eq if mlogit v11
+ _remove_baseeq `b' `v'
+
+ // reshape b to (ncat-1) rows by (nvars + 1) columns
+ // this is the stata 5 format used in SPost
+ local eqs: coleq `b', quoted
+ local eqs: list uniq eqs
+ tempname tmp bnew
+ local r 0
+ foreach eq of local eqs {
+ local ++r
+ mat `tmp' = `b'[1, `"`eq':"']
+ mat rown `tmp' = y`r'
+ mat `bnew' = nullmat(`bnew') \ `tmp'
+ }
+ mat coleq `bnew' = :
+ mat drop `b'
+ mat rename `bnew' `b'
+end
+
+program _remove_baseeq
+ args b v
+ if `"`b'"'=="" | `"`v'"'=="" {
+ di as err "_remove_baseeq: b and v must be specified"
+ exit 198
+ }
+ if c(stata_version) < 11 exit // Stata 11 (or newer) only
+ if `"`e(cmd)'"'!="mlogit" exit // mlogit only
+ local ibase = e(k_eq_base) // get base equation number
+ capt confirm integer number `ibase' // check validity of ibase
+ if _rc exit
+ if `ibase'>=. | `ibase'<1 exit
+ _ms_eq_info, matrix(`b') // get equations info
+ local l = 0 // determine subscripts to
+ forv i = 1/`r(k_eq)' { // remove base equation:
+ if `i' == `ibase' continue, break // l = last element before
+ local l = `l' + r(k`i') // base eq, or 0
+ } // r = first element after
+ local i = `l' // base eq, or .
+ while (`++i' <= r(k`ibase')) { // make sure that base eq is,
+ if `b'[1,`i']!=0 exit // in fact, a base eq (all 0)
+ }
+ local r = cond(`ibase' >= r(k_eq), ., `l' + r(k`ibase') + 1)
+ if `l' > 0 & `r' < . { // base eq within
+ mat `b' = `b'[1..., 1..`l'] , `b'[1..., `r'...]
+ mat `v' = `v'[1..., 1..`l'] , `v'[1..., `r'...]
+ mat `v' = `v'[1..`l', 1...] \ `v'[`r'..., 1...]
+ }
+ else if `r' < . { // base eq at beginning
+ mat `b' = `b'[1..., `r'...]
+ mat `v' = `v'[1..., `r'...]
+ mat `v' = `v'[`r'..., 1...]
+ }
+ else if `l' > 0 { // base eq at end
+ mat `b' = `b'[1..., 1..`l']
+ mat `v' = `v'[1..., 1..`l']
+ mat `v' = `v'[1..`l', 1...]
+ }
+end
diff --git a/Modules/ado/plus/_/_get_mlogit_bvecv.ado b/Modules/ado/plus/_/_get_mlogit_bvecv.ado
new file mode 100644
index 0000000..21724c8
--- /dev/null
+++ b/Modules/ado/plus/_/_get_mlogit_bvecv.ado
@@ -0,0 +1,85 @@
+*! version 1.0.0 2009-10-21 jsl
+* - based on _get_mlogit_bv but leave b as vector
+
+* get stata e(b) and e(V) from -mlogit- and reshape
+* to the format used by SPost based on Stata 9
+
+capture program drop _get_mlogit_bvecv
+capture program drop _remove_baseeq
+program _get_mlogit_bvecv
+ version 9
+ args b v
+ if `"`b'"'=="" | `"`v'"'=="" {
+ di as err "_get_mlogit_bv: names for b and v must be specified"
+ exit 198
+ }
+ if `"`e(cmd)'"'!="mlogit" {
+ di as err "_get_mlogit_bv: model not mlogit"
+ exit 498
+ }
+
+ // get copy of e(b) and e(V)
+ matrix `b' = e(b)
+ matrix `v' = e(V)
+
+ // remove base eq if mlogit v11
+ _remove_baseeq `b' `v'
+
+/*
+ // reshape b to (ncat-1) rows by (nvars + 1) columns
+ // this is the stata 5 format used in SPost
+ local eqs: coleq `b', quoted
+ local eqs: list uniq eqs
+ tempname tmp bnew
+ local r 0
+ foreach eq of local eqs {
+ local ++r
+ mat `tmp' = `b'[1, `"`eq':"']
+ mat rown `tmp' = y`r'
+ mat `bnew' = nullmat(`bnew') \ `tmp'
+ }
+ mat coleq `bnew' = :
+ mat drop `b'
+ mat rename `bnew' `b'
+*/
+end
+
+program _remove_baseeq
+ args b v
+ if `"`b'"'=="" | `"`v'"'=="" {
+ di as err "_remove_baseeq: b and v must be specified"
+ exit 198
+ }
+ if c(stata_version) < 11 exit // Stata 11 (or newer) only
+ if `"`e(cmd)'"'!="mlogit" exit // mlogit only
+ local ibase = e(k_eq_base) // get base equation number
+ capt confirm integer number `ibase' // check validity of ibase
+ if _rc exit
+ if `ibase'>=. | `ibase'<1 exit
+ _ms_eq_info, matrix(`b') // get equations info
+ local l = 0 // determine subscripts to
+ forv i = 1/`r(k_eq)' { // remove base equation:
+ if `i' == `ibase' continue, break // l = last element before
+ local l = `l' + r(k`i') // base eq, or 0
+ } // r = first element after
+ local i = `l' // base eq, or .
+ while (`++i' <= r(k`ibase')) { // make sure that base eq is,
+ if `b'[1,`i']!=0 exit // in fact, a base eq (all 0)
+ }
+ local r = cond(`ibase' >= r(k_eq), ., `l' + r(k`ibase') + 1)
+ if `l' > 0 & `r' < . { // base eq within
+ mat `b' = `b'[1..., 1..`l'] , `b'[1..., `r'...]
+ mat `v' = `v'[1..., 1..`l'] , `v'[1..., `r'...]
+ mat `v' = `v'[1..`l', 1...] \ `v'[`r'..., 1...]
+ }
+ else if `r' < . { // base eq at beginning
+ mat `b' = `b'[1..., `r'...]
+ mat `v' = `v'[1..., `r'...]
+ mat `v' = `v'[`r'..., 1...]
+ }
+ else if `l' > 0 { // base eq at end
+ mat `b' = `b'[1..., 1..`l']
+ mat `v' = `v'[1..., 1..`l']
+ mat `v' = `v'[1..`l', 1...]
+ }
+end
diff --git a/Modules/ado/plus/_/_peabbv.ado b/Modules/ado/plus/_/_peabbv.ado
new file mode 100644
index 0000000..9207630
--- /dev/null
+++ b/Modules/ado/plus/_/_peabbv.ado
@@ -0,0 +1,17 @@
+*! version 1.6.0 3/29/01
+
+capture program drop _peabbv
+program define _peabbv
+ cap version 7
+ if _rc == 0 {
+ local matnm "`1'"
+ local nms : colnames `matnm'
+ tokenize `nms'
+ while "`1'"!="" {
+ local x = abbrev("`1'", 12)
+ local newnms "`newnms'`x' "
+ macro shift
+ }
+ mat colnames `matnm' = `newnms'
+ }
+end
diff --git a/Modules/ado/plus/_/_pebase.ado b/Modules/ado/plus/_/_pebase.ado
new file mode 100644
index 0000000..a2a8370
--- /dev/null
+++ b/Modules/ado/plus/_/_pebase.ado
@@ -0,0 +1,342 @@
+*! version 1.6.5 2007-02-08 - rest(zero)
+
+capture program drop _pebase
+program define _pebase, rclass
+ version 6.0
+ tempvar tmp input tmp2 peb2 xmin xmax chtest mark
+ tempname tobase tobase2 b min max mean median min2 max2 mean2 median2 prev prev2
+
+ if "`e(cmd)'"=="ztp" { local flags "none" }
+ if "`e(cmd)'"=="ztnb" { local flags "none" }
+ if "`e(cmd)'"=="logit" { local flags "none" }
+ if "`e(cmd)'"=="logistic" { local flags "none" }
+ if "`e(cmd)'"=="probit" { local flags "none" }
+ if "`e(cmd)'"=="cloglog" { local flags "none" }
+ if "`e(cmd)'"=="ologit" { local flags "none" }
+ if "`e(cmd)'"=="oprobit" { local flags "none" }
+ if "`e(cmd)'"=="gologit" { local flags "noupper" }
+ if "`e(cmd)'"=="mlogit" { local flags "noupper" }
+ if "`e(cmd)'"=="mprobit" { local flags "noupper" }
+ if "`e(cmd)'"=="slogit" { local flags "noupper" }
+ if "`e(cmd)'"=="clogit" { local flags "noupper" }
+ if "`e(cmd)'"=="poisson" { local flags "none" }
+ if "`e(cmd)'"=="nbreg" { local flags "none" }
+ if "`e(cmd)'"=="zip" { local flags "twoeq noupper" }
+ if "`e(cmd)'"=="zinb" { local flags "twoeq noupper" }
+ if "`e(cmd)'"=="tobit" { local flags "none" }
+ if "`e(cmd)'"=="intreg" { local flags "none" }
+ if "`e(cmd)'"=="cnreg" { local flags "none" }
+ if "`e(cmd)'"=="fit" { local flags "none" }
+ if "`e(cmd)'"=="regress" { local flags "none" }
+ if "`flags'"=="" {
+ di in r "_pebase does not work with `e(cmd)'"
+ exit 198
+ }
+
+*-> unpack flags: define relevant special features of different models
+
+ *flag twoeq -- 2 equation model like zip or zinb
+ if index("`flags'", "twoeq") == 0 { local twoeq "no" }
+ else { local twoeq "yes" }
+ *flag noupper -- do not allow upper and lower for rest()
+ if index("`flags'", "noupper") == 0 { local noupper "no" }
+ else { local noupper "yes" }
+
+* options:
+* x: specified x variable values
+* rest: what to set remaining values to
+* choices: choices after clogit
+* all
+
+ syntax [if] [in] [, x(passthru) rest(string) choices(varlist) all]
+
+ *set flag because so many if zip | zinb statements
+ local twoeq "no"
+ if "`e(cmd)'"=="zip" | "`e(cmd)'"=="zinb" {
+ local twoeq "yes"
+ }
+
+ * get names of rhs variables in models
+ _perhs
+ local rhsnms "`r(rhsnms)'"
+ local nrhs = `r(nrhs)'
+ if "`twoeq'"=="yes" {
+ local rhsnms2 "`r(rhsnms2)'"
+ local nrhs2 = `r(nrhs2)'
+ }
+
+ *go to _peife to see if you need to restrict the sample
+ _peife `if', `all'
+ local if "`r(if)'"
+
+ * get summary statistics for models (both if zip/zinb)
+ quietly _pesum `if' `in', median
+ mat `min' = r(Smin)
+ mat `min' = `min'[1, 2...]
+ mat `max' = r(Smax)
+ mat `max' = `max'[1, 2...]
+ mat `mean' = r(Smean)
+ mat `mean' = `mean'[1, 2...]
+ mat `median' = r(Smedian)
+ mat `median' = `median'[1, 2...]
+*! version 1.6.5 2007-02-08 - rest(zero)
+tempname zero
+mat `zero' = 0*`mean'
+ if "`twoeq'"=="yes" {
+ quietly _pesum `if' `in', median two
+ mat `min2' = r(Smin)
+ mat `min2' = `min2'[1, 2...]
+ mat `max2' = r(Smax)
+ mat `max2' = `max2'[1, 2...]
+ mat `mean2' = r(Smean)
+ mat `mean2' = `mean2'[1, 2...]
+*! version 1.6.5 2007-02-08 - rest(zero)
+tempname zero2
+mat `zero2' = 0*`mean2'
+ mat `median2' = r(Smedian)
+ mat `median2' = `median2'[1, 2...]
+ }
+
+ * get matrix of previous values if it exists
+ local oldpe = "yes"
+ local pematch = "yes"
+ capture mat `prev' = PE_base
+ if _rc != 0 { local oldpe "no" }
+ else {
+ local test1 : colnames(`prev')
+ local test2 : colnames(`mean')
+ if "`test1'" != "`test2'" {
+ local pematch "no"
+ }
+ if "`twoeq'"=="yes" {
+ capture mat `prev2' = PE_base2
+ if _rc != 0 { local oldpe "no" }
+ else {
+ local test1 : colnames(`prev2')
+ local test2 : colnames(`mean2')
+ if "`test1'" != "`test2'" {
+ local pematch "no"
+ }
+ } /* else */
+ } /* if "`twoeq'"=="yes" */
+ } /* else */
+ if "`oldpe'"=="no" { local pematch = "no" }
+
+*=> decode x()
+* tokenize `x', parse(" =")
+ tokenize `x', parse("()")
+ local x "`3'"
+ tokenize `x', parse(" =")
+
+ local allnums = "yes"
+ local xchngs = 0 /* number of x changes proposed */
+ while "`1'" != "" {
+ while "`2'"=="=" | "`2'"=="==" {
+ local temp1 "`1'"
+ macro shift
+ local 1 "`temp1'"
+ }
+ if "`2'"=="" {
+ di _newline in red "Odd number of arguments in x()"
+ error 198
+ }
+ local xchngs = `xchngs' + 1
+ local cvar`xchngs' "`1'"
+ *make sure variable is rhs variable
+ local found "no"
+ local i2 = 1
+ while `i2' <= `nrhs' {
+ local rhschk : word `i2' of `rhsnms'
+ unab 1 : `1', max(1)
+ if "`1'"=="`rhschk'" {
+ local found "yes"
+ local cvno`xchngs' `i2'
+ local i2 = `nrhs'
+ }
+ local i2 = `i2' + 1
+ }
+ *check in binary equation if zip/zinb
+ if "`twoeq'"=="yes" {
+ local i3 = 1
+ while `i3' <= `nrhs2' {
+ local rhschk : word `i3' of `rhsnms2'
+ if "`1'"=="`rhschk'" {
+ local found "yes"
+ local cvn2`xchngs' `i3'
+ local i3 = `nrhs2'
+ }
+ local i3 = `i3' + 1
+ }
+ }
+ if "`found'"=="no" {
+ di in r "`1' not rhs variable"
+ error 198
+ }
+ *make sure value is legal
+ local cval`xchngs' "`2'"
+ if "`2'"=="mean" | "`2'"=="median" | "`2'"=="min" | /*
+ */ "`2'"=="max" | "`2'"=="grmean" | "`2'"=="grmedian" | /*
+ */ "`2'"=="grmin" | "`2'"=="grmax" | "`2'"=="upper" | /*
+ */ "`2'"=="lower" | "`2'"=="previous" | "`2'"=="old" {
+ local allnums = "no"
+ }
+ else {
+ confirm number `2'
+ local cexp`xchngs' "`cvar`xchngs'' == `cval`xchngs''"
+ }
+ macro shift 2
+ } /* while `1' != "" { */
+
+ *set matrix to 'rest' values
+ *rest default is mean
+ if "`rest'" == "" {
+ local rest = "mean"
+ }
+
+ if "`rest'"=="previous" | "`rest'"=="old" {
+ mat `tobase' = `prev'
+ if "`twoeq'"=="yes" {
+ mat `tobase2' = `prev'
+ }
+ }
+
+*! version 1.6.5 2007-02-08 - rest(zero)
+ else if "`rest'"=="mean" | "`rest'"=="max" | "`rest'"=="min" | ///
+ "`rest'"=="median" | "`rest'"=="zero" {
+ mat `tobase' = ``rest''
+ if "`twoeq'"=="yes" {
+ mat `tobase2' = ``rest'2'
+ }
+ }
+
+
+ else if "`rest'"=="grmean" | "`rest'"=="grmax" | "`rest'"=="grmin" | "`rest'"=="grmedian" {
+ if "`allnums'"!="yes" {
+ di in r "`rest' not allowed if x() values not all real numbers"
+ exit 198
+ } /* if "`allnums'"!="yes" */
+ qui gen `mark' = 1 `if'
+ local i = 1
+ while `i' <= `xchngs' {
+ qui replace `mark' = . if ~(`cexp`i'')
+ local i = `i' + 1
+ } /* while i <= `xchngs' */
+
+ _pesum if `mark' == 1, median
+ if "`rest'"=="grmean" { mat `tobase' = r(Smean) }
+ if "`rest'"=="grmax" { mat `tobase' = r(Smax) }
+ if "`rest'"=="grmin" { mat `tobase' = r(Smin) }
+ if "`rest'"=="grmedian" { mat `tobase' = r(Smedian) }
+ mat `tobase' = `tobase'[1, 2...]
+ if "`twoeq'"=="yes" {
+ _pesum if `mark' == 1, median two
+ if "`rest'"=="grmean" { mat `tobase2' = r(Smean) }
+ if "`rest'"=="grmax" { mat `tobase2' = r(Smax) }
+ if "`rest'"=="grmin" { mat `tobase2' = r(Smin) }
+ if "`rest'"=="grmedian" { mat `tobase2' = r(Smedian) }
+ mat `tobase2' = `tobase2'[1, 2...]
+ } /* if "`twoeq'"=="yes" */
+ } /* else if "`rest'"=="grmean"... */
+
+ else if "`rest'"=="upper" | "`rest'"=="lower" {
+ if "`noupper'"=="yes" {
+ di in r "rest(`rest') not permitted after `e(cmd)'"
+ exit 198
+ } /* if "`noupper'"=="yes" */
+ capture matrix `b' = e(b)
+ mat `tobase' = r(Smax)
+ mat `tobase' = `tobase'[1, 2...]
+ mat `xmin' = r(Smin)
+ mat `xmin' = `xmin'[1, 2...]
+ local nvars = colsof(`tobase')
+ local i = 1
+ while `i' <= `nvars' {
+ if "`rest'"=="upper" & `b'[1,`i']<0 {
+ mat `tobase'[1, `i'] == `xmin'[1, `i']
+ }
+ if "`rest'"=="lower" & `b'[1,`i']>0 {
+ mat `tobase'[1, `i'] == `xmin'[1, `i']
+ }
+ local i = `i' + 1
+ } /* while `i' <= `nvars' */
+
+ }
+ else {
+ di in red "rest(`rest') not allowed"
+ error 999
+ }
+
+ * set specific values of tobase and tobase2...
+ local i = 1
+ while `i' <= `xchngs' {
+ if "`cvno`i''"!="" {
+ if "`cval`i''"=="mean" | "`cval`i''"=="median" | /*
+ */ "`cval`i''"=="min" | "`cval`i''"=="max" {
+ mat `tobase'[1, `cvno`i''] = ``cval`i'''[1, `cvno`i'']
+ }
+ else if "`cval`i''"=="previous" {
+ mat `tobase'[1, `cvno`i''] = `prev'[1, `cvno`i'']
+ }
+ else if "`cval`i''"=="upper" | "`cval`i''"=="lower" {
+ if "`noupper'"=="yes" {
+ di in r "`rest' not permitted in x() after `e(cmd)'"
+ exit 198
+ } /* if "`noupper'"=="yes" */
+ capture matrix `b' = e(b)
+ if "`cval`i''"=="upper" {
+ if `b'[1,`cvno`i'']<0 {
+ mat `tobase'[1, `cvno`i''] == `min'[1, `cvno`i'']
+ }
+ else {
+ mat `tobase'[1, `cvno`i''] == `max'[1, `cvno`i'']
+ }
+ }
+ if "`cval`i''"=="lower" {
+ if `b'[1,`cvno`i'']>0 {
+ mat `tobase'[1, `cvno`i''] == `min'[1, `cvno`i'']
+ }
+ else {
+ mat `tobase'[1, `cvno`i''] == `max'[1, `cvno`i'']
+ }
+ }
+ } /* if "`cval`i''"=="upper" | "`cval`i''"=="lower" */
+ else { mat `tobase'[1, `cvno`i''] = `cval`i'' }
+ } /* if "`cvno`i'"!="" */
+
+ if "`cvn2`i''"!="" {
+ if "`cval`i''"=="mean" | "`cval`i''"=="median" /*
+ */ | "`cval`i''"=="min" | "`cval`i''"=="max" {
+ mat `tobase2'[1, `cvn2`i''] = ``cval`i'''[1, `cvn2`i'']
+ }
+ else if "`cval`i''"=="previous" {
+ mat `tobase2'[1, `cvn2`i''] = `prev'[1, `cvn2`i'']
+ }
+ else { mat `tobase2'[1, `cvn2`i''] = `cval`i'' }
+ } /* if "`cvn2`i'"!="" */
+
+ local i = `i' + 1
+ } /* while i <= `xchngs' */
+
+ if "`choices'"!="" { return local choices `choices' }
+ mat rownames `tobase' = x
+ mat PE_base = `tobase'
+ return matrix pebase `tobase'
+ return local nrhs "`nrhs'"
+ return local rhsnms "`rhsnms'"
+ if "`twoeq'"=="yes" {
+ mat rownames `tobase2' = x_eq2
+ mat PE_base2 = `tobase2'
+ return matrix pebase2 `tobase2'
+ return local nrhs2 "`nrhs2'"
+ return local rhsnms2 "`rhsnms2'"
+ }
+end
+
+exit
+
+*History
+* version 1.6.4 13Apr2005
+* version 1.6.3 27Mar2005 slogit
+* version 1.6.2 28Feb2005 mprobit
+* version 1.6.1 18Feb2005 ztp & ztnb
+* version 1.6.0 3/29/01
diff --git a/Modules/ado/plus/_/_pebase.hlp b/Modules/ado/plus/_/_pebase.hlp
new file mode 100644
index 0000000..b7bd5f2
--- /dev/null
+++ b/Modules/ado/plus/_/_pebase.hlp
@@ -0,0 +1,54 @@
+.-
+help for ^_pebase^ - 1.6.5 2007-02-08
+.-
+
+ _pebase [if] [in] [, x(variables_and_values) rest(stat) all]
+
+ where
+
+ ^variables_and_values^ is an alternating list of variables and either
+ numeric values or mean, median, min, max, upper, lower, previous
+
+ ^stat^ is either mean, median, min, max, upper, lower, previous, zero,
+ grmean (group mean), grmedian, grmin, grmax
+
+
+^_pebase^ is a utility command for programming commands that require the user
+to set specific values for the independent variables in regression.
+
+Values of the independent variables are set using the ^x()^, ^rest()^, and ^all^
+options. These can be passed directly from the user input for the
+programmer's command to ^_pebase^.
+
+Options
+-------
+
+^x()^ sets the values of independent variables for calculating predicted
+ values. The list must alternate variable names and either numeric values
+ or types of ^stat^.
+
+^rest()^ sets the independent variables not specified in x() to one of the
+ types of ^stat^. Type ^help prstar^ for more details about using ^x()^ and
+ ^rest^.
+
+^all^ specifies that any calculations of means, medians, etc., should use
+ the entire sample instead of the sample used to estimate the model.
+
+Output of _pebase
+-----------------
+
+PE_base: global matrix containing set values of independent variables
+
+r(pebase): r() class matrix containing set values of independent variables
+
+r(nrhs): r() class macro containing number of independent variables
+
+r(rhsnms): r() class macro containing names of independent variables
+
+PE_base2, r(pebase2), r(nrhs2), r(rhsnms): same as above but for the
+ second equation of two-equation commands like ^zip^ and ^zinb^.
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
diff --git a/Modules/ado/plus/_/_pecats.ado b/Modules/ado/plus/_/_pecats.ado
new file mode 100644
index 0000000..cbd2a74
--- /dev/null
+++ b/Modules/ado/plus/_/_pecats.ado
@@ -0,0 +1,172 @@
+*! version 1.7.3 2007-06-29 Stata 10 fix for categories
+
+capture program drop _pecats
+program define _pecats, rclass
+ version 6.0
+ tempname refval valnum rcount
+ scalar `refval' = -999
+ syntax [varlist(max=1 default=none)] [if] [in]
+
+* only return values for models with categorical outcomes
+ if "`varlist'" == "" & ( /*
+ */ "`e(cmd)'"!="logit" & /*
+ */ "`e(cmd)'"!="logistic" & /*
+ */ "`e(cmd)'"!="probit" & /*
+ */ "`e(cmd)'"!="cloglog" & /*
+ */ "`e(cmd)'"!="ologit" & /*
+ */ "`e(cmd)'"!="oprobit" & /*
+ */ "`e(cmd)'"!="mlogit" & /*
+ */ "`e(cmd)'"!="mprobit" & /*
+ */ "`e(cmd)'"!="gologit" & /*
+ */ "`e(cmd)'"!="clogit" & /*
+ */ "`e(cmd)'"!="slogit" & /*
+ */ ) {
+ if "`e(cmd)'"=="tobit" /*
+ */ | "`e(cmd)'"=="intreg" /*
+ */ | "`e(cmd)'"=="cnreg" /*
+ */ | "`e(cmd)'"=="regress" /*
+ */ | "`e(cmd)'"!="poisson" /*
+ */ | "`e(cmd)'"!="nbreg" /*
+ */ | "`e(cmd)'"!="ztp" /*
+ */ | "`e(cmd)'"!="ztnb" /*
+ */ | "`e(cmd)'"!="zip" /*
+ */ | "`e(cmd)'"!="zinb" {
+ return scalar numcats = 2
+ }
+ exit
+ }
+
+ * numeric value of reference category of mlogit
+* 2007-06-29 stata 10 fix
+if c(stata_version) < 10 {
+
+ if "`e(cmd)'"=="mlogit" { scalar `refval' = e(basecat) }
+ if "`e(cmd)'"=="mprobit" { scalar `refval' = e(i_base) }
+}
+else {
+ if "`e(cmd)'"=="mlogit" { scalar `refval' = e(baseout) }
+ if "`e(cmd)'"=="mprobit" { scalar `refval' = e(i_base) }
+}
+
+ * determine names and values of outcome categories
+ local catnms ""
+ if "`varlist'" != "" {
+ local lhs `varlist'
+ quietly tabulate `1' `if' `in', matrow(`valnum') matcell(`rcount')
+ }
+ if "`varlist'" == "" {
+ local lhs "`e(depvar)'"
+ quietly tabulate `e(depvar)' if e(sample)==1, matrow(`valnum') matcell(`rcount')
+ }
+ local nrows = rowsof(`valnum')
+
+ * grab value labels
+ local vallbl : value label `lhs'
+ local i = 1
+ while `i' <= `nrows' {
+ local vali = `valnum'[`i',1]
+
+ * if value labels have been declared
+ if "`vallbl'" != "" {
+ local valnm : label `vallbl' `vali'
+ if "`valnm'" == "" { local valnm = `vali' }
+ * change blanks to _'s
+ local valnm = trim("`valnm'")
+ local bloc = index("`valnm'"," ")
+ while `bloc' != 0 {
+ local bloc = `bloc' - 1
+ local bloc2 = `bloc' + 2
+ local valnm = trim(substr("`valnm'",1,`bloc') /*
+ */ + "_" + substr("`valnm'",`bloc2',.))
+ local bloc = index("`valnm'"," ")
+ }
+ * change :'s to _'s
+ local bloc = index("`valnm'",":")
+ while `bloc' != 0 {
+ local bloc = `bloc' - 1
+ local bloc2 = `bloc' + 2
+ local valnm = trim(substr("`valnm'",1,`bloc') /*
+ */ + "_" + substr("`valnm'",`bloc2',.))
+ local bloc = index("`valnm'",":")
+ }
+ * change {'s to _'s
+ local bloc = index("`valnm'","{")
+ while `bloc' != 0 {
+ local bloc = `bloc' - 1
+ local bloc2 = `bloc' + 2
+ local valnm = trim(substr("`valnm'",1,`bloc') /*
+ */ + "_" + substr("`valnm'",`bloc2',.))
+ local bloc = index("`valnm'","{")
+ }
+
+ }
+
+ * if no value labels, then use value numbers
+ else { local valnm `vali' }
+
+ * change .'s to _'s
+ local bloc = index("`valnm'",".")
+ while `bloc' != 0 {
+ local bloc = `bloc' - 1
+ local bloc2 = `bloc' + 2
+ local valnm = trim(substr("`valnm'",1,`bloc') /*
+ */ + "_" + substr("`valnm'",`bloc2',.))
+ local bloc = index("`valnm'",".")
+ }
+
+
+ * if current value is refernce value, store it
+ if `vali'==`refval' {
+ local refnm `valnm'
+ local refval `vali'
+ }
+ else {
+ local catnms `catnms' `valnm'
+ local catvals `catvals' `vali'
+
+ *handle long label names for catnms8
+ if length("`valnm'") > 8 { local valnm = substr("`valnm'", 1, 8) }
+ local catnms8 `catnms8' `valnm'
+ }
+ local i = `i' + 1
+ }
+
+ * place reference value at end for mlogit
+ if `refval'!=-999 {
+ local catnms `catnms' `refnm'
+ local catvals `catvals' `refval'
+
+ *handle long label names for catnms8
+ if length("`refnm'") > 8 { local refnm = substr("`refnm'", 1, 8) }
+ local catnms8 `catnms8' `refnm'
+ }
+
+ * logit probit clogit for case of 0 vs > 0
+ if "`varlist'"=="" & /*
+ */ ("`e(cmd)'"=="logit" | "`e(cmd)'"=="probit" | "`e(cmd)'"== "clogit" | "`e(cmd)'"=="cloglog" ) /*
+ */ & `nrows'~=2 {
+ local catnms 0 ~0
+ local catvals 0 ~0
+ local catnms8 0 ~0
+ }
+
+ *number of categories as catnum
+ local numcats : word count `catnms'
+
+ *return information about reference category if mlogit
+ if "`varlist'"=="" & "`e(cmd)'" == "mlogit" {
+ return scalar refval =`refval'
+ return local refnm "`refnm'"
+ }
+
+ return local catnms "`catnms'"
+ return local catvals "`catvals'"
+ return local catnms8 "`catnms8'"
+ return scalar numcats = `numcats'
+
+end
+exit
+* version 1.7.2 13Apr2005
+* version 1.7.1 27Mar2005 slogit
+* version 1.7.0 28Feb2005 mprobit
+* version 1.6.9 18Feb2005 ztp and ztnb
diff --git a/Modules/ado/plus/_/_pecats.hlp b/Modules/ado/plus/_/_pecats.hlp
new file mode 100644
index 0000000..9af0919
--- /dev/null
+++ b/Modules/ado/plus/_/_pecats.hlp
@@ -0,0 +1,61 @@
+.-
+help for ^_pecats^ - 1.6.6 - 3/4/00
+.-
+
+Utility to determine names and values of categories of dependent variable
+-------------------------------------------------------------------------
+
+ ^_pecats^ [varname] [^if^ exp] [^in^ range]
+
+Description
+-----------
+
+^_pecats^ returns the names and values of the categories for models with
+ordinal, nominal, or binary outcomes. For ^mlogit^ it indicates the value
+of the reference category.
+
+NOTE: If no variable name is specified, _pecats will use the dependent
+variable retrieved from `e(depvar)' and will restrict the sample according
+to e(sample)
+
+Returns
+-------
+
+r(numcats): scalar value containing number of categories of depvar.
+
+r(refval): scalar value of the reference category for ^mlogit^.
+
+r(refnm): local macro with name of the reference category for ^mlogit^.
+
+r(catnms): local macro with names of categories of the dependent variable.
+ For ^mlogit^ the reference category is given last.
+
+r(catnms): local macro with names of categories of the dependent variable.
+ For ^mlogit^ the reference category is given last.
+
+r(catnms8): local macro with names of categories of the dependent variable.
+ Value labels longer than 8 characters are truncated to 8
+ characters so they can be used as matrix row/column names. For
+ ^mlogit^ the reference category is given last.
+
+r(catvals): local macro with values of categories of the dependent variable.
+ For ^mlogit^ the reference value is given last.
+
+Examples within a program
+-------------------------
+
+ ...
+ * `if' is the curret if condition
+ _peife `if'
+ * the new condition includes "& e(sample)
+ local eif "`r(if)'"
+ _pecats `e(depvar)' `eif' `in'
+ local cnames r(catnms)
+ local cvals r(catvals)
+ local refval r(refval)
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_peciboot.ado b/Modules/ado/plus/_/_peciboot.ado
new file mode 100644
index 0000000..4c4d6d0
--- /dev/null
+++ b/Modules/ado/plus/_/_peciboot.ado
@@ -0,0 +1,629 @@
+*! version 1.0.0 2009-10-28 jsl
+* - stata 11 fix
+
+// bootstrap for prvalue
+capture program drop _peciboot
+program define _peciboot, rclass
+
+ version 8.0
+ syntax [if] [in] [, x(passthru) rest(passthru) all ///
+ save diff ///
+ Reps(int 1000) SIze(int -9) dots ///
+ ITERate(passthru) match SAving(string)]
+
+ tempname post_name lastest p_obsmat pdif_obsmat pci_mat pdifci_mat ///
+ probs1 probs2 probsdif ///
+ tempbase tempbase2
+ tempname mu_obs mudif_obs mu mudif ///
+ all0_obs all0dif_obs all0 all0dif
+ tempname p_obs p_avg p_std p_normlo p_normup ///
+ pdif_obs pdif_avg pdif_std pdif_normlo pdif_normup ///
+ p_pctlo p_pctup pdif_pctlo pdif_pctup z t tdf ///
+ totobs zpr zdc p_bcup p_bclo pdif_bcup pdif_bclo
+ tempname orig_pred orig_info orig_type orig_base orig_base2 ///
+ orig_upper orig_lower orig_upnorm orig_lonorm ///
+ orig_upbias orig_lobias
+ tempvar touse
+ tempfile original post_file
+
+ * store information to restore when bootstrapping is done
+ mat `orig_pred' = pepred
+ mat `orig_info' = peinfo
+ mat `orig_base' = pebase
+ mat `orig_upper' = peupper
+ mat `orig_lower' = pelower
+
+ * get information on model that has been estimated
+ local io $petype
+ local maxcnt = peinfo[1,11] // get max # of counts compute
+ if "`maxcnt'"=="." {
+ local maxcnt = 9
+ }
+ local cmd : word 1 of $petype // specific model command
+ local input : word 2 of $petype // typical or twoeq
+ local output : word 3 of $petype // output type
+ local depvar "`e(depvar)'" // dep var
+ local numcats = peinfo[1,2]
+ forval i = 1/`numcats' { // construct string with outcome categories
+ local curval = pepred[1, `i']
+ local catvals "`catvals'`cutval' "
+ }
+ local rhsnms : colnames(pebase)
+ if "`input'"=="twoeq" {
+ local rhsnms2 : colnames(pebase2)
+ }
+ local wtype "`e(wtype)'" // weight type
+ local wexp "`e(wexp)'" // weight expression
+ local nocon = "" // constant in model
+ if peinfo[1,6]==1 {
+ local nocon "nocon"
+ }
+ local inout "`input' `output'"
+ if "`input'"=="twoeq" {
+ mat `orig_base2' = pebase2
+ }
+ local nobs = e(N) // observations in original estimation sample
+ local level = peinfo[1,3]
+ scalar `z' = peinfo[1,4]
+
+ * trap improper use of match option
+ if ("`output'"!="binary" & "`output'"!="ordered" ///
+ & "`output'"!="mlogit") & "`match'"!="" {
+ di as error ///
+ "Error: match works only with binary, ordered, and mlogit routines."
+ exit
+ }
+
+ * create touse indicating cases in the original estimatin sample
+ mark `touse' if e(sample)
+ if "`size'"=="-9" | "`size'"=="" { // -9 is default for size
+ local size = e(N)
+ }
+ if "`size'"!="" & `size'>e(N) {
+ di as error ///
+ "Error: resample size is larger than the number of observations"
+ exit
+ }
+
+ * create list of variables and expressions used by post commands
+ forval i = 1/`numcats' {
+ tempname p`i'
+ local post_var "`post_var'`p`i'' "
+ local post_exp "`post_exp'(`p`i'') "
+ if "`diff'"!="" {
+ tempname p`i'dif
+ local post_var "`post_var'`p`i'dif' "
+ local post_exp "`post_exp'(`p`i'dif') "
+ }
+ }
+
+ * count # of statistics to bootstrap
+ local nstats = `numcats' // # of statistics being bootstrapped
+ if "`output'"=="count" {
+ local nstats = `nstats' + 1 // add mu
+ local post_exp "`post_exp'(`mu') "
+ local post_var "`post_var'`mu' "
+ if "`diff'"!="" {
+ local post_exp "`post_exp'(`mudif') "
+ local post_var "`post_var'`mudif' "
+ }
+ }
+ if "`input'"=="twoeq" {
+ local nstats = `nstats' + 1 // add pr always 0
+ local post_exp "`post_exp'(`all0') "
+ local post_var "`post_var'`all0' "
+ if "`diff'"!="" {
+ local post_exp "`post_exp'(`all0dif') "
+ local post_var "`post_var'`all0dif' "
+ }
+ }
+
+ local dots = cond("`dots'"=="", "*", "noisily")
+
+// STORE OBSERVED ESTIMATES
+
+ * get predictions for prob and discrete change
+ mat `p_obsmat' = (pepred[2, 1...])'
+ if "`diff'"!="" {
+ mat `pdif_obsmat' = (pepred[6,1...])'
+ }
+
+ * get rate and pr always 0
+ if "`output'"=="count" {
+ scalar `mu_obs' = pepred[3,2]
+ if "`diff'"!="" {
+ scalar `mudif_obs' = pepred[7,2]
+ }
+ }
+ if "`input'"=="twoeq" {
+ scalar `all0_obs' = pepred[3,4]
+ if "`diff'"!="" {
+ scalar `all0dif_obs' = pepred[7,4]
+ }
+ }
+
+ * hold non-bootstrap estimation results; restore later
+ _estimates hold `lastest', restore
+
+ if "`match'"!="" {
+ preserve // #1
+ quietly keep if `touse'
+ quietly save `original'
+ restore // #1
+ }
+
+ postfile `post_name' `post_var' using `post_file'
+
+// BEGIN SIMULATIONS
+
+ quietly {
+
+ * # of replications missed due to nonconvergence
+ local nmissed = 0
+
+ forval i = 1/`reps' {
+
+ `dots' dodot `reps' `i'
+ preserve // #2
+
+ * if match, resample within outcome categories
+ if "`match'"!="" {
+ tempname samppct catsize
+ scalar `samppct' = `size' / `nobs'
+
+ forval i = 1/`numcats' {
+ tempfile cat`i'file
+ use `original', clear
+ local cur_val: word `i' of `catvals'
+ local depval`i' "`cur_depval'"
+ keep if `depvar'==`cur_val'
+ count
+ scalar `catsize' = `samppct'*r(N)
+ local resamp = round(`catsize',1)
+ if `catsize'==0 {
+ local resamp = 1
+ }
+ bsample `resamp'
+ save `cat`i'file'
+ }
+
+ * stack data from all categories
+ use `cat1file', clear
+ forval i = 2/`numcats' {
+ append using `cat`i'file'
+ }
+ } // matched
+
+ * if match option not specified
+ else {
+
+ keep if `touse'
+ bsample `size'
+
+ * check if boot sample has all outcome categories
+ if "`output'"!="count" {
+ _pecats `depvar'
+ local catschk = r(numcats)
+ * if category missed, count it, and take another sample
+ if `catschk' != `numcats' {
+ local ++nmissed // count missed replication
+ local errlog "`errlog'`i', "
+ restore
+ continue
+ }
+ }
+ } // no matched
+
+// ESTIMATE MODEL WITH BOOTSTRAP SAMPLE
+
+ capture { // trap errors in estimation
+
+ if "`input'" == "typical" {
+ `cmd' `depvar' `rhsnms' ///
+ if `touse' [`wtype'`wexp'], `iterate' `nocon'
+ }
+ else if "`input'" == "twoeq" {
+ `cmd' `depvar' `rhsnms' ///
+ if `touse' [`wtype'`wexp'], ///
+ inflate(`rhsnms2') `iterate' `nocon'
+ }
+
+ * get base values for bootstrap sample
+ _pebase `if' `in', `x' `rest' `all'
+ mat `tempbase' = r(pebase)
+ mat PE_in = `tempbase'
+ if "`input'"=="twoeq" {
+ mat `tempbase2' = r(pebase2)
+ mat PE_in2 = `tempbase2'
+ }
+
+ * get predictions
+ _pepred, level(`level') maxcnt(`maxcnt')
+ local tmp2 = r(maxcount)
+ local tmp = r(level)
+ capture _return drop pepred
+ _return hold pepred
+ _return restore pepred, hold
+ * put results from bootstrap estimate into global matrices
+ _pecollect, inout(`inout') level(`tmp') ///
+ maxcount(`tmp2') `diff'
+
+ } // capture
+
+ * if error in estimation, count it as missed
+ if _rc!=0 {
+ local ++nmissed
+ local errlog "`errlog'`i', "
+ restore
+ continue
+ }
+
+ * get predicted probabilities
+ mat `probs1'= (pepred[2, 1...])'
+ * get mu and pr(always 0) from count models
+ if "`output'"=="count" {
+ scalar `mu' = pepred[3,2]
+ }
+ if "`input'"=="twoeq" {
+ scalar `all0' = pepred[3,4]
+ }
+
+// DISCRETE CHANGES
+
+ if "`diff'"!="" {
+
+ capture {
+
+ * $pexsetup hold x() rest() all from prior prvalue
+ _pebase `if' `in', $pexsetup
+ mat `tempbase' = r(pebase)
+ mat `tempbase2' = r(pebase2)
+ mat PE_in = `tempbase'
+ if "`input'"=="twoeq" {
+ mat PE_in2 = `tempbase2'
+ }
+ _pepred, level(`level') maxcnt(`maxcnt')
+ local tmp2 = r(maxcount)
+ local tmp = r(level)
+ _return drop _all
+ _return hold pepred
+ _return restore pepred, hold
+ _pecollect, inout(`inout') level(`tmp') ///
+ maxcount(`tmp2') `diff'
+
+ } // end of capture
+
+ if _rc !=0 { // if error in estimation
+ local ++nmissed // count missed replication
+ local errlog "`errlog'`i', "
+ restore
+ continue
+ }
+
+ mat `probs2' = (pepred[2, 1...])'
+ mat `probsdif' = `probs1' - `probs2'
+
+ * get results from count models
+ if "`output'"=="count" {
+ scalar `mudif' = -1 * pepred[7,2]
+ }
+ if "`input'"=="twoeq" {
+ scalar `all0dif' = -1 * pepred[7,4]
+ }
+
+ } // end of diff loop
+
+// POST RESULTS
+
+ * move probs from matrices to scalars for posting
+ forval j = 1/`numcats' {
+ scalar `p`j'' = `probs1'[`j', 1]
+ if "`diff'"!="" {
+ scalar `p`j'dif' = `probsdif'[`j', 1]
+ }
+ }
+ post `post_name' `post_exp'
+
+ restore // #2
+
+ } // end of replications loop
+
+ postclose `post_name' // close postfile
+
+// CONSTRUCT CI
+
+ preserve // #3
+
+ use `post_file', clear
+ qui count
+ scalar `totobs' = r(N)
+ scalar `tdf' = `totobs' -1
+ scalar `t' = invttail(`tdf',((1-(`level')/100)/2))
+
+ * rename mu and all0 so loop for p_i can be used later
+ local inew = `numcats'
+ if "`output'"=="count" {
+ local inew = `inew' + 1
+ tempname p`inew'
+ rename `mu' `p`inew''
+ matrix `p_obsmat' = `p_obsmat' \ `mu_obs'
+ if "`diff'"!="" {
+ tempname p`inew'dif
+ rename `mudif' `p`inew'dif'
+ matrix `pdif_obsmat' = `pdif_obsmat' \ `mudif_obs'
+ }
+ }
+ if "`input'"=="twoeq" {
+ local inew = `inew' + 1
+ tempname p`inew'
+ rename `all0' `p`inew''
+ matrix `p_obsmat' = `p_obsmat' \ `all0_obs'
+ if "`diff'"!="" {
+ tempname p`inew'dif
+ rename `all0dif' `p`inew'dif'
+ matrix `pdif_obsmat' = `pdif_obsmat' \ `all0dif_obs'
+ }
+ } // twoeq
+
+ * loop through each statistics
+ forval i = 1/`nstats' {
+
+ sum `p`i'', d
+ scalar `p_obs' = `p_obsmat'[`i',1]
+ scalar `p_avg' = r(mean)
+ scalar `p_std' = r(sd)
+
+ * bias correction method
+ qui count if `p`i''<=`p_obs'
+ * zpr will be missing if r(N)=0
+ scalar `zpr' = invnorm(r(N)/`totobs')
+
+ * use t for normal
+ scalar `p_normup' = `p_obs' + `t'*`p_std'
+ scalar `p_normlo' = `p_obs' - `t'*`p_std'
+
+ * percentile method
+ qui _pctile `p`i'', nq(1000)
+ local upperpctile = 500 - 5*-`level'
+ local lowerpctile = 1000 - `upperpctile'
+ scalar `p_pctup' = r(r`upperpctile')
+ scalar `p_pctlo' = r(r`lowerpctile')
+
+ * percentile for the bias-correction.
+ local upnum = round((norm(2*`zpr' + `z')) * 1000, 1)
+ local lonum = round((norm(2*`zpr' - `z')) * 1000, 1)
+ if `zpr'==. { // if missing, upper & lower limits are missing
+ scalar `p_bcup' = .
+ scalar `p_bclo' = .
+ }
+ else {
+ scalar `p_bcup' = r(r`upnum')
+ scalar `p_bclo' = r(r`lonum')
+ }
+
+ * stack results from 3 methods
+ mat `pci_mat' = nullmat(`pci_mat') \ ///
+ `p_pctlo', `p_pctup', ///
+ `p_normlo', `p_normup', ///
+ `p_bclo', `p_bcup'
+
+ // CI FOR DISCRETE CHANGE
+
+ if "`diff'"!="" {
+
+ sum `p`i'dif', d
+ scalar `pdif_obs' = `pdif_obsmat'[`i',1]
+ scalar `pdif_avg' = r(mean)
+ scalar `pdif_std' = r(sd)
+
+ * bias corrected method
+ qui count if `p`i'dif'<=`pdif_obs'
+ scalar `zdc' = invnorm(r(N)/`totobs')
+ local upnum = round((norm(2*`zdc' + `z'))*1000, 1)
+ local lonum = round((norm(2*`zdc' - `z'))*1000, 1)
+
+ * use t for normal
+ scalar `pdif_normup' = `pdif_obs' + `t'*`pdif_std'
+ scalar `pdif_normlo' = `pdif_obs' - `t'*`pdif_std'
+
+ * percentile method
+ _pctile `p`i'dif', nq(1000)
+ scalar `pdif_pctup' = r(r`upperpctile')
+ scalar `pdif_pctlo' = r(r`lowerpctile')
+
+ * percentile for bias corrected
+ if `zdc'==. {
+ scalar `pdif_bcup' = .
+ scalar `pdif_bclo' = .
+ }
+ else {
+ scalar `pdif_bcup' = r(r`upnum')
+ scalar `pdif_bclo' = r(r`lonum')
+ }
+
+ * stack results from 3 methods
+ mat `pdifci_mat' = nullmat(`pdifci_mat') \ ///
+ `pdif_pctlo', `pdif_pctup', ///
+ `pdif_normlo', `pdif_normup', ///
+ `pdif_bclo', `pdif_bcup'
+ }
+ }
+
+ } // end of quietly
+
+ * grab the mu and all0 ci's
+ tempname muci mudifci all0ci all0difci
+ local inew = `numcats'
+ if "`output'"=="count" {
+ local inew = `inew' + 1
+ matrix `muci' = `pci_mat'[`inew',1...]
+ if "`diff'"!="" {
+ matrix `mudifci' = `pdifci_mat'[`inew',1...]
+ }
+ }
+ if "`input'"=="twoeq" {
+ local inew = `inew' + 1
+ matrix `all0ci' = `pci_mat'[`inew',1...]
+ if "`diff'"!="" {
+ matrix `all0difci' = `pci_mat'[`inew',1...]
+ }
+ }
+ * get rid of mu and all 0 info leaving only probabilities
+ mat `pci_mat' = `pci_mat'[1..`numcats',1...]
+ if "`diff'"!="" {
+ mat `pdifci_mat' = `pdifci_mat'[1..`numcats',1...]
+ }
+
+// RESTORE DATA FROM ORIGINAL ESTIMATION
+
+ mat pepred = `orig_pred'
+ mat peinfo = `orig_info'
+ mat pebase = `orig_base'
+ if "`input'"=="twoeq" {
+ mat pebase2 = `orig_base2'
+ }
+ mat peupper = `orig_upper'
+ mat pelower = `orig_lower'
+ mat peupnorm = peupper
+ mat pelonorm = pelower
+ mat peupbias = peupper
+ mat pelobias = pelower
+ mat peuppct = peupper
+ mat pelopct = pelower
+
+ global petype "`io'"
+
+// ADD CIs TO GLOBAL
+
+ * get list of rownames to use in return matrices
+ forval i = 1/`numcats' {
+ local curval = pepred[1, `i'] // current val
+ local plist "`plist' p`curval' " // predicted probabilities
+ local dlist "`dlist' pdif`curval' " // discrete changes
+ }
+
+ * save x() rest() all setup to be used for prvalue, dif
+ if "`save'"!="" {
+ global pexsetup "`x' `rest' `all'"
+ }
+
+ if "`diff'"!="" { // if discrete change
+ mat colnames `pdifci_mat' = pctlo pctup nrmlo nrmup bclo bcup
+ mat rownames `pdifci_mat' = `dlist'
+ mat pelower[6,1] = (`pdifci_mat'[1...,1])'
+ mat peupper[6,1] = (`pdifci_mat'[1...,2])'
+ mat pelonorm[6,1] = (`pdifci_mat'[1...,3])'
+ mat peupnorm[6,1] = (`pdifci_mat'[1...,4])'
+ mat pelobias[6,1] = (`pdifci_mat'[1...,5])'
+ mat peupbias[6,1] = (`pdifci_mat'[1...,6])'
+ return mat bootcidifp = `pdifci_mat'
+ } // difference
+
+ mat colnames `pci_mat' = pctlo pctup nrmlo nrmup bclo bcup
+ mat rownames `pci_mat' = `plist'
+ mat pelower[2,1] = (`pci_mat'[1..., 1])'
+ mat peupper[2,1] = (`pci_mat'[1..., 2])'
+ mat pelonorm[2,1] = (`pci_mat'[1..., 3])'
+ mat peupnorm[2,1] = (`pci_mat'[1..., 4])'
+ mat pelobias[2,1] = (`pci_mat'[1..., 5])'
+ mat peupbias[2,1] = (`pci_mat'[1..., 6])'
+ return mat bootcip = `pci_mat'
+ local repsnomis = `reps' - `nmissed'
+ return scalar Nrepsnomis = `repsnomis'
+
+ if "`output'"=="count" {
+ mat pelower[3,2] = `muci'[1,1]
+ mat peupper[3,2] = `muci'[1,2]
+ mat pelonorm[3,2] = `muci'[1,3]
+ mat peupnorm[3,2] = `muci'[1,4]
+ mat pelobias[3,2] = `muci'[1,5]
+ mat peupbias[3,2] = `muci'[1,6]
+ if "`diff'"!="" {
+ mat pelower[7,2] = `mudifci'[1,1]
+ mat peupper[7,2] = `mudifci'[1,2]
+ mat pelonorm[7,2] = `mudifci'[1,3]
+ mat peupnorm[7,2] = `mudifci'[1,4]
+ mat pelobias[7,2] = `mudifci'[1,5]
+ mat peupbias[7,2] = `mudifci'[1,6]
+ }
+ }
+ if "`input'"=="twoeq" {
+ mat pelower[3,4] = `all0ci'[1,1]
+ mat peupper[3,4] = `all0ci'[1,2]
+ mat pelonorm[3,4] = `all0ci'[1,3]
+ mat peupnorm[3,4] = `all0ci'[1,4]
+ mat pelobias[3,4] = `all0ci'[1,5]
+ mat peupbias[3,4] = `all0ci'[1,6]
+ if "`diff'"!="" {
+ mat pelower[7,4] = `all0difci'[1,1]
+ mat peupper[7,4] = `all0difci'[1,2]
+ mat pelonorm[7,4] = `all0difci'[1,3]
+ mat peupnorm[7,4] = `all0difci'[1,4]
+ mat pelobias[7,4] = `all0difci'[1,5]
+ mat peupbias[7,4] = `all0difci'[1,6]
+ }
+ }
+
+ if "`saving'"!="" {
+ forval i = 1/`numcats' {
+ local varnm: word `i' of `plist'
+ rename `p`i'' b_`varnm'
+ if "`diff'"!="" {
+ local varnm: word `i' of `dlist'
+ rename `p`i'dif' b_`varnm'
+ }
+ }
+ if "`output'"=="count" {
+ local iadd = `numcats'+1
+ rename `p`iadd'' b_mu
+ if "`diff'"!="" {
+ rename `p`iadd'dif' b_mudif
+ }
+ }
+ if "`input'"=="twoeq" {
+ local iadd = `iadd' + 1
+ rename `p`iadd'' b_alw0
+ if "`diff'"!="" {
+ rename `p`iadd'dif' b_alw0dif
+ }
+ }
+ save `saving'
+ }
+
+ restore // #3
+
+// RESTORE ERETURNS
+
+ mat peuppct = peupper // just duplicate the default method
+ mat pelopct = pelower // just duplicate the default method
+ _estimates unhold `lastest'
+
+end // _peciboot
+
+* produce dots
+capture program drop dodot
+program define dodot
+ version 8
+ args N n
+ local dot "."
+ * don't bother with %'s if few than 20 reps
+ if `N'>19 {
+ scalar s = `N'/10
+ forvalues c = 0/10 {
+ local c`c' = floor(`c'*s)
+ if `n'==`c`c'' {
+ local pct = `c'*10
+ di in g `pct' "%" _c
+ local dot ""
+ * new line when iterations are done
+ if `pct'==100 {
+ di
+ }
+ }
+ } //forvalues
+ } // if > 19
+ di in g as txt "`dot'" _c
+end
+exit
+* version 0.2.0 2005-02-03 (13Apr2005)
+* version 0.2.1 13Apr2005
diff --git a/Modules/ado/plus/_/_peciboot.hlp b/Modules/ado/plus/_/_peciboot.hlp
new file mode 100644
index 0000000..0596003
--- /dev/null
+++ b/Modules/ado/plus/_/_peciboot.hlp
@@ -0,0 +1,154 @@
+{smcl}
+{* 2005-02-06}{...}
+{hline}
+help for {hi:_peciboot}{right:2/6/2005}
+{hline}
+
+{title: Utility to implement the bootstrap method for calculating confidence intervals}
+
+{p 8 15 2}{cmd:_peciboot} [if] [in] [{cmd:,}
+{cmd:x(}{it:variables_and_values}{cmd:)}
+{cmd:rest(}{it:stat}{cmd:)}
+{cmdab:r:eps(}{it:#}{cmd:)}
+{cmdab:si:ze(}{it:#}{cmd:)}
+{cmd:save}
+{cmd:diff}
+{cmd:all match dots}
+{cmdab:sa:ving(}{it:filename, save_options}{cmd:)}]
+
+{p 4 4 2}
+where {it:variables_and_values} is an alternating list of variables
+and either numeric values or mean, median, min, max, upper, lower,
+previous and {it:stat} is either mean, median, min, max, upper, lower,
+previous, grmean(group mean), mrmedian, grmin, grmax.
+
+{title: Description}
+
+{p 4 4 2}
+{cmd:_peciboot} is a utility command that returns prediction, discrete
+changes and their confidence intervals using {help bootstrap} method
+with resampling technique. It can calculate boostrapped confidence intervals
+using the normal approximation, percentile, and bias-corrected methods.
+It applies to {help logit}, {help probit}, {help cloglog}, {help ologit},
+{help oprobit}, {help gologit}, {help mlogit}, {help poisson}, {help nbreg},
+{help zip}, and {help zinb} models.
+
+{title: Options}
+
+{p 4 8 2}
+{cmd:x(}{it:variables_and_values}{cmd:)} sets the values of independent
+variables for calculating predicted values. The list must alternate variable
+names and either numeric values or types of {cmd:stat}.
+
+{p 4 8 2}
+{cmd:rest(}{it:stat}{cmd:)} sets the independent variables not specified
+in {cmd:x(}{it:variables_and_values}{cmd:)} to one of the types of {cmd:stat}.
+Check into {help prstar} for more details about using
+{cmd:x(}{it:variables_and_values}{cmd:)} and {cmd:rest(}{it:stat}{cmd:)}
+
+{p 4 8 2}
+{cmd:reps(}{it:#}{cmd:)} specifies the number of bootstrap replications
+to be performed. The default is 1000.
+
+{p 4 8 2}
+{cmd: size(}{it:#}{cmd:)} specifies the size of the samples to be drawn.
+The default is _N, meaning to draw samples of the same size as the data.
+
+{p 4 8 2}
+{cmd:save} saves current values of indepenent variables and predictions
+for computing changes using the diff option.
+
+{p 4 8 2}
+{cmd:diff} computes difference between current predictions and those that
+were saved.
+
+{p 4 8 2}
+{cmd:all} specifies that any calculation of means, medians, etc., should
+use the entire sample instead of the sample used to estimate the model.
+
+{p 4 8 2}
+{cmd:match} requests {cmd:_peciboot} to resample from each category group
+of the dependent variable in proportion of the resample size to the original
+sample size.
+
+{p 4 8 2}
+{cmd:dots} requests a dot be placed on the screen at the beginning of each
+replication, thus providing entertainment when a large number of reps() are
+requested. It also prints out the percent replications finished.
+
+{p 4 8 2}
+{cmd:saving(}{it:filename, save_options}{cmd:)} creates a Stata data file
+(.dta file) containing the bootstrap distribution for predictions and discrete
+changes.
+
+
+{title: Global Matrices}
+
+{p 4 4 2}
+The second row of the following matrices contains predicted probabilities and
+the sixth row contains differences for predicted probabilities.
+
+{p 4 8 2}
+peupper: is a global matrix containing upper end of confidence intervals.
+Default produces the percentile confidence intervals.
+
+{p 4 8 2}
+pelower: is a global matrix containing lower end of confidence intervals.
+Default produces the percentile confidence intervals.
+
+{p 4 8 2}
+peuppct: is a global matrix containing upper end of confidence intervals
+using the percentile method.
+
+{p 4 8 2}
+pelopct: is a global matrix containing lower end of confidence intervals
+using the percentile method.
+
+{p 4 8 2}
+peupnorm: is a global matrix containing lower end of confidence intervals
+using the normal approximation method.
+
+{p 4 8 2}
+pelonorm: is a global matrix containing lower end of confidence intervals
+using normal approximation method.
+
+{p 4 8 2}
+peupbias: is a global matrix containing upper end of confidence intervals
+using the bias-corrected method.
+
+{p 4 8 2}
+pelobias: is a global matrix containing lower end of confidence intervals
+using the bias-corrected method.
+
+{title: Returns}
+
+{p 4 8 2}
+r(Nrepsnomis): is a scalar return containing the factual number of replications
+used for calculating bootstraped confidence intervals, which might be smaller than
+the one requested by users.
+
+
+{title: Examples}
+
+{p 4 8 2}{cmd:._pebase `if' `in' , `x' `rest' `choices' `all'}{p_end}
+{p 4 8 2}{cmd:.mat `tobase' = r(pebase)}{p_end}
+{p 4 8 2}{cmd:._pepred, `level' `maxcnt'}{p_end}
+{p 4 8 2}{cmd:.local maxc = r(maxcount)}{p_end}
+{p 4 8 2}{cmd:.local lvl = r(level)}{p_end}
+{p 4 8 2}{cmd:.capture _return drop pepred}{p_end}
+{p 4 8 2}{cmd:._return hold pepred}{p_end}
+{p 4 8 2}{cmd:._return restore pepred, hold}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:._pecollect, inout("`io'") level(`lvl') /// }{p_end}
+{p 4 8 2}{cmd:. maxcount(`maxc') `diff' `reps'}{p_end}
+
+{p 4 8 2}{cmd:._peciboot, `x' `rest' `all' `save' /// }{p_end}
+{p 4 8 2}{cmd:. `diff' `reps' `size' `dots' `match' `saving'}{p_end}
+
+{hline}
+
+{p 2 4 2}Authors: J. Scott Long & Jun Xu{p_end}
+{p 11 4 2}{browse www.indiana.edu/~jslsoc/spost.htm}{p_end}
+{p 11 4 2}spostsup@indiana.edu{p_end}
diff --git a/Modules/ado/plus/_/_pecidelta.ado b/Modules/ado/plus/_/_pecidelta.ado
new file mode 100644
index 0000000..6440f0c
--- /dev/null
+++ b/Modules/ado/plus/_/_pecidelta.ado
@@ -0,0 +1,552 @@
+*! version 2.5.0 2009-10-28 jsl
+* - stata 11 update for returns from -mlogit-
+
+// delta method for prvalue
+
+capture program drop _pecidelta
+program define _pecidelta, rclass
+
+ version 8
+ * _G==gradient matrix; _V=var/cov matrix; _up=upper bound; _lo=lower
+ tempname x_base x_base1 x_baseneg xb b b_j b_nocuts designmat cur_eq_sav
+ tempname pdf z G V temp yval eV v
+ tempname mu mu_G mu_V mudif mudif_V
+ tempname pr_cur pr_G pr_V pr_se pr_lo pr_up pr_sav
+ tempname prdif prdif_se prdif_lo prdif_up prdif_V
+
+ /* Matrix definitions:
+
+ pr_cur : predicted probabilities
+ pr_lo : lower bound for pred prob
+ pr_up : upper bound for pred prob
+ pr_G : gradient matrix for pred prob
+ : [dp/db'*e(V)*dp/db]
+ pr_V : variance (only) matrix for pred prob
+ pr_se : standards error for pred prob
+
+ prdif : discrete change for pred prob
+ prdif_lo : lower bound for discrete change
+ prdif_up : upper bound for discrete change
+ prdif_V : covariance matrix for discrete change
+ : [d(p2-p1)/db'*e(V)*d(p2-p1)/db]
+ prdif_se : standards error for discrete change
+
+ yval : y values
+
+ G = [dF(XB)/dB]'
+ = [dF(XB)/dXB]*[dXB/dB]' = f(XB)*X
+ V = Var(F(XB))
+ = [dF(XB)/dB]' V(B) [dF(XB)/dB]
+ */
+
+// DECODE SYNTAX
+
+ * syntax [, Save Diff] // 0.2.3
+ * 0.2.5 - caller indicates version of stata calling _pecidelta;
+ * needed since other commands change versions.
+
+ syntax [, Save Diff caller(real 5.0)]
+
+// GET INFORMATION STORED IN GLOBALS
+
+ loc io $petype
+ loc cmd : word 1 of $petype // model command
+ loc input : word 2 of $petype // typical or twoeqn
+ loc output : word 3 of $petype // output type
+
+ loc nrhs = peinfo[1,1] // # of rhs
+ loc nrhsp1 = peinfo[1,1] + 1 // adding 1 for constant
+ scalar `z' = peinfo[1,4]
+ loc numcats = peinfo[1,2]
+ loc numcatsm1 = peinfo[1,2] - 1
+ loc max_count = `numcats' - 1 // count model max counts
+
+ * mat `b' = e(b) // 0.2.2
+ * 0.2.5 get b and v for all estimation commands
+ mat `b' = e(b)
+ local nbeta = colsof(`b')
+ mat `eV' = e(V)
+
+ * 0.2.6 get_mlogit_bv to get b and V under Stata 11
+ if "`e(cmd)'"=="mlogit" { // if mlogit, special treatment
+ nobreak {
+ _get_mlogit_bvecv `b' `eV'
+ }
+ }
+
+ * base values
+ mat `x_base'= pebase[1, 1...] // base values for predictions
+ mat `x_base1' = `x_base', 1 // adding 1 to end for constant
+
+// GET PREDICTED PROBABILITIES
+
+ if "`output'"=="count" | "`output'"=="binary" {
+ forval i = 0/`numcats' {
+ tempname p`i'
+ scalar `p`i'' = pepred[2,`i'+1]
+ }
+ }
+ else {
+ forval i = 1/`numcats' {
+ tempname p`i'
+ scalar `p`i'' = pepred[2,`i']
+ }
+ }
+ mat `pr_cur'= pepred[2,1...]'
+
+// BINARY MODELS - predicted probability
+
+ if "`output'"=="binary" {
+
+ scalar `xb' = pepred[3,1]
+
+ // dF(XB)/dXB = pdf
+ if "`e(cmd)'"=="cloglog" {
+ scalar `pdf' = (`p1'-1) * exp(`xb')
+ }
+ if "`e(cmd)'"=="logit" | "`e(cmd)'"=="logistic" {
+ scalar `pdf' = `p1' * (1-`p1')
+ }
+ if "`e(cmd)'"=="probit"{
+ scalar `pdf' = normden(`xb')
+ }
+
+ // dF(XB)/dB = f(XB)*X
+ mat `G' = `pdf' * `x_base1'
+ // noncon fix 2004-12-22
+ mat `G' = `G'[1,1..`nbeta']
+ mat `pr_G' = `G' \ `G'
+ // Var(F(XB)) = dF(XB)/dB' V(B) dF(XB)/dB
+ * 0.2.2 mat `V' = `G' * e(V) * `G''
+ mat `V' = `G' * `eV' * `G'' // 0.2.5
+ // Since V(p1)=V(p0):
+ mat `pr_V' = `V'[1,1] \ `V'[1,1]
+ }
+
+// ORDERED MODELS
+
+ if "`output'"=="ordered" {
+
+ * Ordered logit/probit involves computing:
+ *
+ * Pr(y=m) = F(t_m - xb) - F(t_m-1 * xb)
+ *
+ * The e(b) matrix is a vector of b's associated with the
+ * x's and then the tau's. To compute t_m - xb by vector
+ * multiplicaton of e(b), we need to compute vectors like:
+ *
+ * x_tau1 = -x1 -x2 -x3 1 0 0 0
+ * x_tau2 = -x1 -x2 -x3 0 1 0 0
+ * x_tau3 = -x1 -x2 -x3 0 0 1 0
+ * x_tau4 = -x1 -x2 -x3 0 0 0 1
+ *
+ * Then x_taum*e(b) = t_m - xb
+
+ tempname I tau_xb tau_xbm1 pdf1 pdflast
+ mat `I' = I(`numcatsm1')
+
+ * loop through categories
+ forval i = 1/`numcatsm1' {
+ tempname x_tau`i'
+ mat `x_tau`i'' = -(`x_base'), `I'[`i',1...]
+ }
+
+ * get b's with tau's at end
+ mat `b' = e(b)
+ * compute tau_m - xb
+ mat `tau_xb' = `x_tau1'*`b''
+ scalar `tau_xb' = `tau_xb'[1,1]
+ * for category 1: d cdf/d xb = pdf
+ if "`e(cmd)'"=="ologit" {
+ lgtpdf 0 `tau_xb'
+ scalar `pdf1' = r(pdf)
+ }
+ if "`e(cmd)'"=="oprobit" {
+ scalar `pdf1' = normden(`tau_xb')
+ }
+ * for the first outcome
+ mat `G' = `pdf1' * `x_tau1'
+ mat `pr_G' = `G'
+ * 0.2.2 mat `V' = `G' * e(V) * (`G')'
+ mat `V' = `G' * `eV' * (`G')' // 0.2.5
+ mat `pr_V' = `V'[1,1]
+
+ * cateories 2 through next to last add to matrices for category 1
+ forval i = 2/`numcatsm1' {
+
+ local im1 = `i' - 1 // prior cutpoint
+ tempname pdf`i'
+ mat `tau_xb' = `x_tau`i''*`b''
+ scalar `tau_xb' = `tau_xb'[1,1]
+ mat `tau_xbm1' = `x_tau`im1''*`b''
+ scalar `tau_xbm1' = `tau_xbm1'[1,1]
+ if "`e(cmd)'"=="ologit" {
+ * cutpoint i
+ lgtpdf 0 `tau_xb'
+ scalar `pdf`i'' = r(pdf)
+ * cutpoint i-1
+ lgtpdf 0 `tau_xbm1'
+ scalar `pdf`im1'' = r(pdf)
+ }
+ if "`e(cmd)'"=="oprobit" {
+ scalar `pdf`i'' = normden(`tau_xb')
+ scalar `pdf`im1'' = normden(`tau_xb')
+ }
+
+ mat `G' = (`pdf`i'')*(`x_tau`i'') ///
+ - (`pdf`im1'') * (`x_tau`im1'')
+ mat `pr_G' = `pr_G' \ `G'
+ * 0.2.2 mat `V' = `G' * e(V) * (`G')'
+ mat `V' = `G' * `eV' * (`G')' // 0.2.5
+ mat `pr_V' = `pr_V' \ `V'[1,1]
+
+ } // if given category
+
+ * last category
+ local im1 = `numcats' - 1
+ mat `tau_xb' = `x_tau`im1''*`b''
+ scalar `tau_xb' = `tau_xb'[1,1]
+ if "`e(cmd)'"=="ologit" {
+ lgtpdf 0 `tau_xb'
+ scalar `pdflast' = - r(pdf)
+ }
+ if "`e(cmd)'"=="oprobit" {
+ scalar `pdflast' = -normden(`tau_xb')
+ }
+ mat `G' = `pdflast' * (`x_tau`im1'')
+ mat `pr_G' = `pr_G' \ `G'
+ * 0.2.2 mat `V' = `G' * e(V) * (`G')'
+ mat `V' = `G' * `eV' * (`G')' // 0.2.5
+ mat `pr_V' = `pr_V' \ `V'[1,1]
+
+ } // ordered
+
+// GOLOGIT
+
+ if "`e(cmd)'"=="gologit" {
+
+ tempname nextrow pdfmat fmxb_mx
+
+ forval j = 1/`numcatsm1' {
+
+ * select betas for outcome j
+ local start = (`j'-1) * `nrhsp1' + 1
+ local end = `start' + `nrhs' // including constant
+ mat `b_j' = `b'[1...,`start'..`end']
+
+ * pdf at -xb
+ mat `xb' = `x_base1'*(`b_j')'
+ lgtpdf 0 -`xb'[1,1]
+ scalar `pdf' = r(pdf)
+
+ * collect column vector with pdfs for each outcome
+ mat `pdfmat' = nullmat(`pdfmat') \ `pdf'
+ }
+
+ * dF(-xb)/dB = dFxbdB contains vec of:
+ *
+ * -x1*f(xb1) ... -x1*f(xbJ-1)
+ * :::
+ * -xK*f(xb1) ... -xK*f(xbJ-1)
+ * -1 *f(xb1) ... -1 *f(xbJ-1)
+
+ mat `fmxb_mx' = vec((-1 * `pdfmat' * `x_base1')')
+
+ * designmat: let J = (1 1 ... 1) for # rhs + 1
+ * let M = -J
+ * let 0 = 0 matrix of same size
+ *
+ * designmat = J 0 0 0 0 ... 0 0 ==> -xf(-xb_1)
+ * M J 0 0 0 ... 0 0 ==> xf(-xb_1)-xf(-xb_2)
+ * 0 M J 0 0 ... 0 0
+ * : : : : :::::::::
+ * 0 0 0 0 0 ... 0 M==> xf(-xb_ncats)-xf(-xb_2)
+
+ tempname J M
+ mat `J' = J(1,`nrhsp1',1)
+ mat `M' = J(1,`nrhsp1',-1)
+
+ * outcome 1
+ mat `designmat' = J(1,`nrhsp1',1), J(1,`nbeta'-`nrhsp1',0)
+
+ * outcomes 2 - J-1
+ forval i = 2/`numcatsm1' {
+ mat `nextrow' = J(1,`nbeta',0)
+ local startneg = (`i'-2) * `nrhsp1' + 1 // start -1
+ local startpos = (`i'-1) * `nrhsp1' + 1 // start 1
+ mat `nextrow'[1,`startneg'] = `M'
+ mat `nextrow'[1,`startpos'] = `J'
+ mat `designmat' = nullmat(`designmat') \ `nextrow'
+ }
+
+ * outcome J
+ mat `nextrow' = J(1,`nbeta'-`nrhsp1',0), J(1,`nrhsp1',-1)
+ mat `designmat' = nullmat(`designmat') \ `nextrow'
+ * compute gradient and variance
+ mat `pr_G' = `designmat' * diag(`fmxb_mx')
+ * 0.2.2 mat `pr_V' = ( vecdiag(`pr_G' * e(V) * (`pr_G')') )'
+ mat `pr_V' = ( vecdiag(`pr_G' * `eV' * (`pr_G')') )' // 0.2.5
+ }
+
+// NOMINAL
+
+ if "`e(cmd)'"=="mlogit" {
+ local nbeta = colsof(`b')
+ local nrhspluscon = `nrhsp1' // if constant
+ local iscon "1"
+ if `nrhs'*`numcatsm1'==`nbeta' { // if true, noconstant
+ local nrhspluscon = `nrhsp1' - 1 // if noconstant
+ local iscon ""
+ }
+
+ tempname pj_xk_mat pj_xk_vec
+ forval i = 1/`numcats' {
+ tempname p`i'fst p`i'snd Var`i'
+ }
+
+ * X = base values with 1 for contant
+ * 0 = 0 row vector of same size.
+ * Create:
+ * X 0 0 0 ...
+ * 0 X 0 0 ...
+ * 0 0 X 0 ...
+ mat `designmat' = J(`numcatsm1',`nbeta',0)
+ forval i = 1/`numcatsm1' {
+ local st = (`i'-1) * `nrhspluscon'
+ forval j = 1/`nrhspluscon' {
+ local k = `st' + `j'
+ mat `designmat'[`i',`k'] = `x_base`iscon''[1,`j']
+ }
+ }
+ * vector p1x1 p1x2 p1x3...p2x1 p2x2 p2x3...p3x1 p3x2 p3x3...
+ forval i = 1/`numcatsm1' {
+ mat `pj_xk_vec' = nullmat(`pj_xk_vec'),(`x_base`iscon'' * `p`i'')
+ }
+ * compute the variances
+ forval i = 1/`numcats' {
+ if "`i'"<"`numcats'" {
+ mat `G' = (`p`i'') * (`designmat'[`i',1..`nbeta']) ///
+ - (`p`i'') * (`pj_xk_vec')
+ mat `pr_G' = nullmat(`pr_G') \ `G'
+ }
+ if "`i'"=="`numcats'" {
+ mat `G' = -(`p`i'') * (`pj_xk_vec')
+ mat `pr_G' = `pr_G' \ `G'
+ }
+
+ // noncon fix 2004-12-22
+ mat `G' = `G'[1,1..`nbeta']
+ * 0.2.2 mat `V' = `G' * e(V) * (`G')'
+ mat `V' = `G' * `eV' * (`G')' // 0.2.5
+ mat `pr_V' = nullmat(`pr_V') \ `V'[1,1]
+ }
+ }
+
+// NBREG AND POISSON
+
+ if "`output'"=="count" & "`input'"=="typical" {
+
+ // POISSON
+
+ if "`e(cmd)'"=="poisson" {
+ scalar `mu' = pepred[3,2]
+ mat `mu_G' = `mu'*`x_base1' // d mu/dB
+ mat `mu_G' = `mu_G'[1,1..`nbeta'] // noncon fix 2004-12-22
+ forval i = 0/`max_count' {
+ matrix `G' = `x_base1' * ///
+ ( `i' * `mu'^`i' - `mu'^(`i'+1) ) / ///
+ ( exp(lngamma(`i'+1)) * exp(`mu') )
+ mat `G' = `G'[1,1..`nbeta'] // noncon fix 2004-12-22
+ mat `pr_G' = nullmat(`pr_G') \ `G'
+ * 0.2.2 mat `V' = `G' * e(V) * (`G')'
+ mat `V' = `G' * `eV' * (`G')' // 0.2.5
+ mat `pr_V' = nullmat(`pr_V') \ `V'[1,1]
+ * 0.2.2 mat `eV' = e(V)
+ }
+ }
+
+ // NBREG
+
+ if "`e(cmd)'"=="nbreg" {
+
+ tempname alpha alphainv inv1alpmu
+ tempname scorexb gradb scorelnalpha gradlnalpha
+ scalar `mu' = pepred[3,2]
+ mat `mu_G' = (`mu' * `x_base1'), 0
+
+ // noncon fix 2005-01-08
+ * strip off the alpha
+ local nbeta = `nbeta' - 1 // drop alpha
+ * strip off the alpha
+ mat `mu_G' = `mu_G'[1,1..`nbeta']
+
+ scalar `alpha' = e(alpha)
+ scalar `inv1alpmu' = 1 / (1+`alpha'*`mu')
+ scalar `alphainv' = 1 / `alpha'
+
+ forval y = 0/`max_count' { // loop through counts
+
+ scalar `scorexb' = `inv1alpmu' * (`y'-`mu')
+ mat `gradb' = (`scorexb' * `x_base1') * `p`y''
+ scalar `scorelnalpha' = `alphainv' * ///
+ ( digamma(`alphainv') ///
+ - digamma(`y' + `alphainv') ///
+ - ln(`inv1alpmu') ///
+ ) ///
+ + `inv1alpmu'*(`y'-`mu')
+ scalar `gradlnalpha' = `scorelnalpha' * `p`y''
+ mat `G' = `gradb', `gradlnalpha'
+ mat `G' = `G'[1,1..`nbeta'] // noncon fix 2004-12-22
+ mat `pr_G' = nullmat(`pr_G') \ `G'
+
+ // noncon fix 2005-01-08
+ *drop mat `V' = `G' * e(V) * (`G')'
+ * 0.2.2 mat `eV' = e(V)
+ mat `eV' = `eV'[1..`nbeta',1..`nbeta']
+ mat `V' = `G' * `eV' * (`G')'
+ mat `pr_V' = nullmat(`pr_V') \ `V'[1,1]
+
+ } // loop through counts
+
+ }
+
+ // BOTH MODELS
+
+ // noncon fix 2005-01-08
+ mat `mu_V' = `mu_G' * `eV' * (`mu_G')' // variance for expected rate
+
+ } // negbin and poisson
+
+// GET CATEGORY VALUES FOR PROBABILITIES - used to label matrices
+
+ forval i = 1/`numcats' {
+ local category = pepred[1,`i'] // value of category
+ * used for column names later
+ local catnames "`catnames' Cat=`category'"
+ }
+
+// VARIANCE FOR DISCRETE CHANGE
+
+ if "`diff'"=="diff" {
+
+ /* 0.2.2
+ if "`e(cmd)'"!="nbreg" {
+ mat `eV' = e(V)
+ } */
+
+ mat def `pr_sav' = pepred[4,1...]'
+ mat `prdif' = `pr_cur' - `pr_sav'
+
+ * is there no change in x? 0 if no difference.
+ scalar `cur_eq_sav' = mreldif(`pr_sav',`pr_cur')
+
+ * variance for change in prob
+ mat `prdif_V' = pegrad_pr * `eV' * pegrad_pr' ///
+ + `pr_G' * `eV' * (`pr_G')' ///
+ - pegrad_pr * `eV' * (`pr_G')' ///
+ - `pr_G' * `eV' * pegrad_pr'
+ mat `prdif_V' = (vecdiag(`prdif_V'))'
+
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ mat `mudif' = `mu' - pepred[5,2] // minus save mu
+ * variance for change in mu
+ mat `mudif_V' = pegrad_mu * `eV' * pegrad_mu' ///
+ + `mu_G' * `eV' * (`mu_G')' ///
+ - pegrad_mu * `eV' * (`mu_G')' ///
+ - `mu_G' * `eV' * pegrad_mu'
+ }
+ }
+
+// COMPUTE UPPER AND LOWER BOUNDS
+
+ mat rownames `pr_V' = `catnames'
+ mat rownames `pr_G' = `catnames'
+
+ * std errors = square root of variances
+ mat `pr_se' = vecdiag(cholesky(diag(`pr_V')))'
+
+ * 2008-07-09
+ matrix pedifsep = `pr_se'
+
+ if "`diff'"=="diff" {
+
+ if `cur_eq_sav'==0 { // no change from x_dif==0
+ * se's are 0
+ mat `prdif_se' = J(rowsof(`prdif_V'),1,0)
+ }
+ else {
+ mat `prdif_se' = vecdiag(cholesky(diag(`prdif_V')))'
+ }
+
+ * 2008-07-09
+ matrix pedifsep = `prdif_se'
+
+ }
+
+ * construct bounds for pred prob
+ mat `pr_lo' = `pr_cur' - `z'*`pr_se'
+ mat `pr_up' = `pr_cur' + `z'*`pr_se'
+ mat peupper[2,1] = (`pr_up')'
+ mat pelower[2,1] = (`pr_lo')'
+
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ * 2008-07-09
+ global pesemu = sqrt(`mu_V'[1,1])
+ mat peupper[3,2] = `mu' + `z'*sqrt(`mu_V'[1,1])
+ mat pelower[3,2] = `mu' - `z'*sqrt(`mu_V'[1,1])
+ }
+
+// CREATE BOUNDS FOR DISCRETE CHANGE
+
+ if "`diff'"=="diff" {
+ mat `prdif_lo' = `prdif' - `z'*`prdif_se'
+ mat `prdif_up' = `prdif' + `z'*`prdif_se'
+ mat peupper[6,1] = (`prdif_up')'
+ mat pelower[6,1] = (`prdif_lo')'
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ * 2008-07-09
+ global pedifsemu = sqrt(`mudif_V'[1,1])
+ mat peupper[7,2] = (`mudif' + `z'*sqrt(`mudif_V'[1,1]))
+ mat pelower[7,2] = (`mudif' - `z'*sqrt(`mudif_V'[1,1]))
+ }
+ }
+
+// SAVE GRADIENTS TO COMPUTE CI FOR DCs
+
+ if "`save'"=="save" {
+ mat pegrad_pr = `pr_G'
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ mat pegrad_mu = `mu_G'
+ }
+ }
+
+end
+
+capture program drop lgtpdf
+// lgtpdf 0 0
+// scalar a = r(pdf) // pdf of logit
+// scalar b = r(cdf) // cdf of logit
+// di "pdf: " r(pdf)
+// di "cdf: " r(cdf)
+
+program define lgtpdf, rclass
+ version 8
+ tempname expab pdf cdf
+ args a bx
+ scalar `expab' = exp(`a' + `bx')
+ scalar `pdf' = `expab' / (1 + `expab')^2
+ scalar `cdf' = `expab' / (1 + `expab')
+ return scalar pdf = `pdf'
+ return scalar cdf = `cdf'
+end
+
+exit
+
+version 0.2.0 2005-02-03
+version 0.2.1 13Apr2005
+version 0.2.2 2008-07-09
+ - return global pedifsep
+version 0.2.5 2009-09-18
+ - update for stata 11 - drop for _get_mlogit_bv.ado
+version 0.2.6 2009-10-21
+ - use _get_mlogit_bv.ado
diff --git a/Modules/ado/plus/_/_pecidelta.hlp b/Modules/ado/plus/_/_pecidelta.hlp
new file mode 100644
index 0000000..bc33155
--- /dev/null
+++ b/Modules/ado/plus/_/_pecidelta.hlp
@@ -0,0 +1,67 @@
+{smcl}
+{* 2005-02-06}{...}
+{hline}
+help for {hi:_pecidelta}{right:2/6/2005}
+{hline}
+
+{title: Utility to implement the delta method for calculating confidence intervals}
+
+{p 8 15 2}{cmd:_pecidelta} [{cmd:,}
+{cmdab:s:ave}
+{cmdab:d:iff}]
+
+{title: Description}
+
+{p 4 4 2}
+{cmd:_pecidelta} is a utility command that calculates confidence
+intervals for prediction and discrete changes by {search delta}
+method using analytical derivatives. It applies to {help logit},
+{help probit}, {help cloglog}, {help ologit}, {help oprobit},
+{help gologit}, {help mlogit}, {help poisson}, and {help nbreg}.
+
+{title: Options}
+
+{p 4 8 2}
+{cmd:save} saves current values of indepenent variables and predictions
+for computing changes using the diff option.
+
+{p 4 8 2}
+{cmd:diff} computes difference between current predictions and those that
+were saved.
+
+{title: Global Matrices}
+
+{p 4 4 2}
+The second row of the following matrices contains predicted probabilities and
+the sixth row contains differences for predicted probabilities.
+
+{p 4 8 2}
+peupper: _pecidelta calculates confidence intervals for prediction
+and place upper end into the global matrix peupper.
+
+{p 4 8 2}
+pelower: _pecidelta calculates confidence intervals for prediction
+and place lower end into the global matrix pelower.
+
+{title: Examples}
+
+{p 4 8 2}{cmd:._pebase `if' `in' , `x' `rest' `choices' `all'}{p_end}
+{p 4 8 2}{cmd:.mat `tobase' = r(pebase)}{p_end}
+{p 4 8 2}{cmd:._pepred, `level' `maxcnt'}{p_end}
+{p 4 8 2}{cmd:.local maxc = r(maxcount)}{p_end}
+{p 4 8 2}{cmd:.local lvl = r(level)}{p_end}
+{p 4 8 2}{cmd:.capture _return drop pepred}{p_end}
+{p 4 8 2}{cmd:._return hold pepred}{p_end}
+{p 4 8 2}{cmd:._return restore pepred, hold}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:...}{p_end}
+{p 4 8 2}{cmd:._pecollect, inout("`io'") level(`lvl') /// }{p_end}
+{p 4 8 2}{cmd:. maxcount(`maxc') `diff' `reps'}{p_end}
+{p 4 8 2}{cmd:._pecidelta, `save' `diff'}{p_end}
+
+{hline}
+
+{p 2 4 2}Authors: J. Scott Long & Jun Xu{p_end}
+{p 11 4 2}{browse www.indiana.edu/~jslsoc/spost.htm}{p_end}
+{p 11 4 2}spostsup@indiana.edu{p_end}
diff --git a/Modules/ado/plus/_/_peciml.ado b/Modules/ado/plus/_/_peciml.ado
new file mode 100644
index 0000000..52fddda
--- /dev/null
+++ b/Modules/ado/plus/_/_peciml.ado
@@ -0,0 +1,70 @@
+*! version 0.2.2 2008-07-09
+* - global pedifsey std error of dif in y
+
+// ci for difference in y or y* based on ML Wald computation
+
+capture program drop _peciml
+program define _peciml, rclass
+
+ version 8
+ tempname xb_dif xb_dif_var xb_dif_sd xb_dif_lo xb_dif_up
+ tempname x_cur x_sav x_dif z b b_var
+
+ // retrieve global data
+
+ local nocon = peinfo[1,6] // 1 if no constant
+ local output : word 3 of $petype // what is the output type?
+ scalar `z' = peinfo[1,4] // width of confidence interval
+ local nrhs = peinfo[1,1] // # of RHS variables
+ sca `xb_dif'= pepred[7,1] // difference in xb from saved to current
+ matrix `x_cur' = pebase[1,1...] // current base values
+ matrix `x_sav' = pebase[2,1...] // saved base values
+ mat `b_var' = e(V)
+ mat `b' = e(b)
+
+ // select and augment matrices to match model type
+
+ * ologit, oprobit // nocon option not allowed
+ if "`output'"=="ordered" {
+ mat `b_var' = `b_var'[1..`nrhs',1..`nrhs']
+ }
+
+ * tobit, cnreg, intreg
+ if "`output'"=="tobit" {
+ if `nocon' != 1 {
+ mat `x_cur' = `x_cur', 1, 0
+ mat `x_sav' = `x_sav', 1, 0
+ }
+ else {
+ mat `x_cur' = `x_cur', 0
+ mat `x_sav' = `x_sav', 0
+ }
+ }
+
+ * regress, fit, logit, probit
+ if "`output'"=="regress" | "`output'"=="binary" {
+ if `nocon' != 1 {
+ mat `x_cur' = `x_cur', 1
+ mat `x_sav' = `x_sav', 1
+ }
+ }
+
+ mat `x_dif' = `x_cur' - `x_sav'
+ * variance of difference
+ mat `xb_dif_var' = (`x_dif')*`b_var'*(`x_dif')'
+ sca `xb_dif_sd' = sqrt(`xb_dif_var'[1,1])
+
+ * 2008-07-09
+ global pedifsey = `xb_dif_sd'
+
+ * compute and store upper and lower limits
+ sca `xb_dif_lo' = `xb_dif' - `z'*`xb_dif_sd'
+ sca `xb_dif_up' = `xb_dif' + `z'*`xb_dif_sd'
+
+ mat peupper[7,1] = `xb_dif_up'
+ mat pelower[7,1] = `xb_dif_lo'
+
+end
+
+* version 0.2.1 13Apr2005
+* version 0.2.0 2005-02-03
diff --git a/Modules/ado/plus/_/_pecmdcheck.ado b/Modules/ado/plus/_/_pecmdcheck.ado
new file mode 100644
index 0000000..d6f56a0
--- /dev/null
+++ b/Modules/ado/plus/_/_pecmdcheck.ado
@@ -0,0 +1,77 @@
+*! version 0.2.3 13Apr2005
+* version 0.2.2 03Mar2005 cloglog
+* version 0.2.1 19Feb2005 zt
+* version 0.2.0 03Feb2005
+
+// simply check if last command was valid for spost
+
+capture program drop _pecmdcheck
+program define _pecmdcheck, rclass
+ version 8
+ args spostcmd
+ local io ""
+ * 03Mar2005 zt models added
+ if "`e(cmd)'"=="ztp" {
+ local io "typical count"
+ }
+ if "`e(cmd)'"=="ztnb" {
+ local io "typical count"
+ }
+ if "`e(cmd)'"=="cloglog" {
+ local io "typical binary"
+ }
+ if "`e(cmd)'"=="cnreg" {
+ local io "typical tobit"
+ }
+ if "`e(cmd)'"=="fit" {
+ local io "typical regress"
+ }
+ if "`e(cmd)'"=="gologit" {
+ local io "typical ordered"
+ }
+ if "`e(cmd)'"=="intreg" {
+ local io "typical tobit"
+ }
+ if "`e(cmd)'"=="logistic" {
+ local io "typical binary"
+ }
+ if "`e(cmd)'"=="logit" {
+ local io "typical binary"
+ }
+ if "`e(cmd)'"=="mlogit" {
+ local io "typical nominal"
+ }
+ if "`e(cmd)'"=="nbreg" {
+ local io "typical count"
+ }
+ if "`e(cmd)'"=="ologit" {
+ local io "typical ordered"
+ }
+ if "`e(cmd)'"=="oprobit" {
+ local io "typical ordered"
+ }
+ if "`e(cmd)'"=="poisson" {
+ local io "typical count"
+ }
+ if "`e(cmd)'"=="probit" {
+ local io "typical binary"
+ }
+ if "`e(cmd)'"=="regress" {
+ local io "typical regress"
+ }
+ if "`e(cmd)'"=="tobit" {
+ local io "typical tobit"
+ }
+ if "`e(cmd)'"=="zinb" {
+ local io "twoeq count"
+ }
+ if "`e(cmd)'"=="zip" {
+ local io "twoeq count"
+ }
+ if "`io'"=="" {
+ di as error _new ///
+ "`spostcmd' does not work for the last type of model estimated."
+ }
+ return local io = "`io'"
+
+end
diff --git a/Modules/ado/plus/_/_pecollect.ado b/Modules/ado/plus/_/_pecollect.ado
new file mode 100644
index 0000000..203a3b9
--- /dev/null
+++ b/Modules/ado/plus/_/_pecollect.ado
@@ -0,0 +1,349 @@
+*! version 2.0.1 2008-07-09 jsl
+* - peinfo[3,8] to missing since it isn't the sd of the difference
+
+// Utility to collect information from the current model and
+// saves it to global matrices for use by other programs (e.g.,
+// for simulations or constructing plots unavailable with prgen).
+// For details on these matrices, -help prvalue_collect-
+
+capture program drop _pecollect
+program define _pecollect, rclass
+ version 8
+ tempname temp values mu xb prall0 nrhs2 muC ey mucount
+ tempname dif difp difm r1 r2 r3
+
+ syntax , level(real) inout(string) maxcount(string) [Diff reps(int 1000)]
+
+// get information about current model
+
+ * is it zero truncated?
+ local iszt = 0
+ if ("`e(cmd)'"=="ztp" | "`e(cmd)'"=="ztnb") local iszt = 1
+
+ * type of model
+ global petype "`e(cmd)' `inout'"
+ local input : word 2 of $petype // is it a typical or twoeq model?
+ local output : word 3 of $petype // what is the output type?
+
+ local level = r(level) // CI level for current model
+
+ * nrhs: # of rhs variables
+ local colnms: colnames(PE_in)
+ local nrhs: word count `colnms'
+ local nrhs = `nrhs' // no _cons included
+
+ * ncat: number of outcome categories
+ if "`output'"=="count" {
+ local ncat = `maxcount'+1
+ }
+ else if "`output'"=="regress" | "`output'"=="tobit" {
+ local ncat = 1
+ }
+ else {
+ _pecats
+ local catvals = r(catvals)
+ local ncat = r(numcats)
+ _return restore pepred, hold // restore returns from _pepred
+ }
+
+ * nrhs2: # of rhs if zip or zinb
+ local nrhs2 = .
+ if "`input'"=="twoeq" {
+ local colnms2: colnames(PE_in2)
+ local nrhs2: word count `colnms2'
+ local nrhs2 = `nrhs2' // no _cons included
+ }
+
+ * basecat: mlogit base category
+ local basecat = .
+ * if "`e(cmd)'"=="mlogit" { local basecat = e(basecat) }
+ if "`e(cmd)'"=="mlogit" {
+ local basecat = e(i_base)
+ }
+
+// peinfo - global matrix with numeric information about:
+//
+// Row 1: the current model
+// Row 2: the saved model used to compute the difference
+// Row 3: Row 1 - Row 2
+
+ mat def peinfo = J(3,12,.)
+ matrix peinfo[1,1] = `nrhs' // nrhs - columns for pebase
+ matrix peinfo[1,2] = `ncat' // numcats from _pecats
+ matrix peinfo[1,3] = `level'*100 // ci level as 95 not .95
+ matrix peinfo[1,4] = -invnorm((1-`level')/2) // z @ level for ci
+ matrix peinfo[1,5] = `nrhs2' // nrhs2
+ matrix peinfo[1,6] = . // nocon
+ matrix peinfo[1,7] = `basecat' // base category for mlogit
+ matrix peinfo[1,8] = . // stdp for binary model
+ matrix peinfo[1,9] = `reps' // requested # of replications for bootstrap
+ matrix peinfo[1,10] = . // completed # of replications for bootstrap
+ // this will be added after _peciboot is called
+ matrix peinfo[1,11] = `maxcount'
+
+ * if diff, add saved and compute current-saved
+ if "`diff'" == "diff" {
+
+ mat `r1' = peinfo[1,1...] // current
+ mat `r2' = PRVinfo // saved
+ mat `dif' = `r1' - `r2'
+ mat peinfo = `r1' \ `r2' \ `dif'
+
+* 2008-07-09
+mat peinfo[3,8] = . // since this is not a valid stdp
+
+ } // "`diff'" == "diff"
+
+// pebase and pebase2 - global matrices with base values
+
+ * start with current base and two blank rows
+ mat pebase = PE_in \ J(1,`nrhs',.) \ J(1,`nrhs',.)
+ if "`input'" == "twoeq" {
+ mat pebase2 = PE_in2 \ J(1,`nrhs2',.) \ J(1,`nrhs2',.)
+ matrix rownames pebase2 = Current Saved Cur-Saved
+ }
+
+ * if diff, get previous base values
+ if "`diff'" == "diff" {
+ mat `dif' = pebase[1,1...] - PRVbase
+ mat pebase = PE_in \ PRVbase \ `dif'
+ if "`input'" == "twoeq" {
+ mat `dif' = pebase2[1,1...] - PRVbase2
+ mat pebase2 = PE_in2 \ PRVbase2 \ `dif'
+ matrix rownames pebase2 = Current Saved Cur-Saved
+ }
+ }
+
+// gather information about current model
+
+ * missing by default
+ scalar `xb' = .
+ scalar `mu' = . // rate in count; e(y) in zip/zinb
+ scalar `mucount' = . // mu in count portion of zip/zinb
+ scalar `prall0' = .
+
+ * info on mu for count models
+ if "`output'"=="count" {
+ mat `temp' = r(mu)
+ scalar `mu' = `temp'[1,1]
+ }
+ if "`e(cmd)'"=="zip" | "`e(cmd)'"=="zinb" {
+ mat `temp' = r(mucount) // grab rate from count portion of model
+ scalar `mucount' = `temp'[1,1]
+ }
+ if `iszt' {
+ mat `temp' = r(xb)
+ scalar `xb' = `temp'[1,1]
+ mat `temp' = r(muC) // E(y|y<0)
+ scalar `muC' = `temp'[1,1]
+ }
+ if "`e(cmd)'"=="poisson" ///
+ | "`e(cmd)'"=="nbreg" {
+ mat `temp' = r(xb)
+ scalar `xb' = `temp'[1,1]
+ }
+ if "`input'"=="twoeq" { // zip and zinb
+ scalar `xb' = log(`mu')
+ mat `temp' = r(always0)
+ scalar `prall0' = `temp'[1,1]
+ }
+
+ if "`output'"=="binary" ///
+ | "`output'"=="regress" ///
+ | "`output'"=="tobit" ///
+ | "`output'"=="ordered" {
+ mat `temp' = r(xb)
+ scalar `xb' = `temp'[1,1]
+ }
+
+// start with empty pepred & peCpred matrices
+
+ mat def pepred = J(7,`ncat',.)
+ matrix rownames pepred = ///
+ 1values 2prob 3misc 4sav_prob 5sav_misc 6dif_prob 7dif_misc
+ mat def peupper = pepred // holds upper ci
+ mat def pelower = pepred // holds lower ci
+ local method = word("$pecimethod",1)
+ if "`method'"=="bootstrap" { // bootstrap computes 3 types of CIs
+ mat def peupnorm = pepred // holds upper by normal appox
+ mat def pelonorm = pepred // holds lower by normal appox
+ mat def peupbias = pepred // holds upper with bias adjustment
+ mat def pelobias = pepred // holds lower with bias adjustment
+ }
+ if `iszt' {
+ mat def peCpred = pepred // for conditional results
+ }
+
+// pepred & peinfo: add info about current model
+
+ if "`output'"=="binary" {
+
+ mat pepred[1,1] = 0 // outcome values
+ mat pepred[1,2] = 1
+ mat `temp' = r(p0) // predictions
+ mat pepred[2,1] = `temp'[1,1]
+ mat `temp' = r(p1)
+ mat pepred[2,2] = `temp'[1,1]
+ mat pepred[3,1] = `xb'
+ mat `temp' = r(stdp)
+ mat peinfo[1,8] = `temp'[1,1]
+ mat `temp' = r(p0_lo) // upper and lower limits
+ * due to error in _pepred, r(p0_lo) is really upper limit
+ mat peupper[2,1] = `temp'[1,1]
+ mat `temp' = r(p0_hi)
+ mat pelower[2,1] = `temp'[1,1]
+ mat `temp' = r(p1_hi)
+ mat peupper[2,2] = `temp'[1,1]
+ mat `temp' = r(p1_lo)
+ mat pelower[2,2] = `temp'[1,1]
+ mat `temp' = r(xb_hi)
+ mat peupper[3,1] = `temp'[1,1]
+ mat `temp' = r(xb_lo)
+ mat pelower[3,1] = `temp'[1,1]
+ }
+
+ if "`output'"=="tobit" ///
+ | "`output'"=="regress" {
+
+ mat pepred[1,1] = . // value
+ mat pepred[2,1] = . // predicted probability
+ mat pepred[3,1] = `xb'
+ mat `temp' = r(xb_lo)
+ mat pelower[3,1] = `temp'[1,1]
+ mat `temp' = r(xb_hi)
+ mat peupper[3,1] = `temp'[1,1]
+ mat `temp' = r(stdp)
+ mat peinfo[1,8] = `temp'[1,1]
+ }
+
+ if "`output'"=="ordered" { // also works for mlogit
+
+ mat `temp' = r(stdp)
+ mat peinfo[1,8] = `temp'[1,1]
+ mat `temp' = r(xb_hi)
+ mat peupper[3,1] = `temp'[1,1]
+ mat `temp' = r(xb_lo)
+ mat pelower[3,1] = `temp'[1,1]
+ forval i=1/`ncat' {
+ local v : word `i' of `catvals'
+ mat pepred[1,`i'] = `v'
+ mat `temp' = r(p`i')
+ mat pepred[2,`i'] = `temp'[1,1]
+ }
+ mat pepred[3,1] = `xb'
+ }
+
+ if "`e(cmd)'"=="gologit" | "`e(cmd)'"=="mlogit" ///
+ | "`e(cmd)'"=="mprobit" | "`e(cmd)'"== "slogit" {
+ forval i=1/`ncat' {
+ local v : word `i' of `catvals'
+ mat pepred[1,`i'] = `v'
+ mat `temp' = r(p`i')
+ mat pepred[2,`i'] = `temp'[1,1]
+ mat pepred[2,`i'] = `temp'[1,1]
+ if `i' != `ncat' {
+ mat `temp' = r(xb`i')
+ mat pepred[3,`i'] = `temp'[1,1]
+ }
+ }
+ }
+
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" ///
+ | "`e(cmd)'"=="zip" | "`e(cmd)'"=="zinb" ///
+ | `iszt' {
+ forval i=1/`ncat' { // add labels to headers
+ local im1 = `i' - 1
+ mat pepred[1,`i'] = `im1' // numbers 0 to ncat-1
+ mat `temp'=r(p`im1')
+ mat pepred[2,`i'] = `temp'[1,1]
+ if `iszt' { // if zt model, get pr(y|y>0)
+ mat peCpred[1,`i'] = `im1' // numbers 0 to ncat-1
+ mat `temp'=r(Cp`im1')
+ mat peCpred[2,`i'] = `temp'[1,1]
+ }
+ }
+ mat pepred[3,1] = `xb'
+ mat pepred[3,2] = `mu' // overall rate E(y)
+ mat pepred[3,3] = `mucount' // mu for count model E(y|~always0)
+ mat `temp' = r(stdp)
+ mat peinfo[1,8] = `temp'[1,1]
+ mat `temp' = r(mu_hi)
+ mat peupper[3,1] = `temp'[1,1]
+ mat `temp' = r(mu_lo)
+ mat pelower[3,1] = `temp'[1,1]
+ if "`input'"=="twoeq" {
+ mat pepred[3,4] = `prall0'
+ }
+ if `iszt' { // zt models
+ mat `temp' = r(Cmu) // conditional mu
+ mat peCpred[3,2] = `temp'[1,1]
+ }
+
+ }
+
+ * Information on current model is now located in pepred, peCpred,
+ * peinfo, peupper, pelower.
+
+// if -diff-, add saved and difference to output matrix
+
+ if "`diff'" == "diff" {
+
+ * peinfo
+ mat `dif' = peinfo[1,1...] - PRVinfo
+ mat peinfo = peinfo[1,1...] \ PRVinfo \ `dif'
+
+ * pepred: row 1-values; 2-prob; 3-misc
+ mat `difp' = pepred[2,1...] - PRVprob // dif in prob
+ mat `difm' = pepred[3,1...] - PRVmisc // dif in other stats
+ * Current SavedMode Difference
+ mat pepred = pepred[1..3,1...] \ PRVprob \ PRVmisc \ `difp' \ `difm'
+
+ if `iszt' { // if zero trucated, also fix conditional matrix
+ mat `difp' = pepred[2,1...] - PRVCprob
+ mat `difm' = pepred[3,1...] - PRVCmisc
+ mat peCpred = ///
+ pepred[1..3,1...] \ PRVCprob \ PRVCmisc \ `difp' \ `difm'
+ }
+
+ } // end if diff
+
+
+// ADD CATEGORY NUMBERS TO FIRST ROW; ADD ROW & COL NAMES
+
+ mat `r1' = pepred[1,1...]
+ mat `r2' = peupper[2...,1...]
+ mat `r3' = pelower[2...,1...]
+ mat peupper = `r1' \ `r2'
+ mat pelower = `r1' \ `r3'
+ matrix rownames peupper = ///
+ 1values 2up_pr 3up_misc 4up_sav_pr ///
+ 5up_sav_misc 6up_dif_pr 7up_dif_misc
+ matrix rownames pelower = ///
+ 1values 2lo_pr 3lo_misc 4lo_sav_pr ///
+ 5lo_sav_misc 6lo_dif_pr 7lo_dif_misc
+ matrix rownames peinfo = Current Saved Cur-Saved
+ matrix colnames peinfo = 1nrhs 2numcats 3level 4z_level ///
+ 5nrhs2 6nocon 7basecat 8stdp 9reps 10repsdone 11maxcount ///
+ 12blank
+ matrix rownames pebase = Current Saved Cur-Saved
+
+// INFORMATION ON WHETHER CONSTANT IS IN MODEL
+
+ _penocon
+ local temp = r(nocon)
+ matrix peinfo[1,6] = `temp'
+
+end
+
+exit
+
+version 1.0.0 15Apr2005 fix rate used for zip/zinb (see notes at end)
+
+ 15Apr2005 - correct error for zip and zinb (see changes in _pepred, _pecollect, _peciboot
+ E(y) was used incorrectly rather than E(y|~always0).
+ _pepred[3|5|7, 2] used to be mu defined as rate in count portion of model E(y|not always 0)
+ _pepred[3|5|7, 2] now is the overall rate E(y); listed as simply mu.
+ _pepred[3|5|7, 3] rate in count portion of model E(y|not always 0); listed as mucount.
+ To simplify changes in _peciboot, E(y) is referred to as mu; E(y|~always0) is mucount.
+
+version 2.0.0 2007-03-04 jsl - revised for prvalue repeated dif calls
diff --git a/Modules/ado/plus/_/_pecollect.hlp b/Modules/ado/plus/_/_pecollect.hlp
new file mode 100644
index 0000000..8a9e6fa
--- /dev/null
+++ b/Modules/ado/plus/_/_pecollect.hlp
@@ -0,0 +1,163 @@
+{smcl}
+{* 2005-02-06}{...}
+{hline}
+help for {hi:_pecollect}{right:2/6/2005}
+{hline}
+
+{title: Utility program to collect information used by prvalue2}
+
+{p 8 15 2}{cmd:_pecollect}
+{cmd:level(}{it:real}{cmd:)}
+{cmd:inout(}{it:string}{cmd:)}
+{cmd:maxcnt(}{it:string}{cmd:)}
+[{cmdab:d:iff}]
+
+
+{title: Description}
+
+{p 4 4 2}
+{cmd:_pecollect} collects results from _pepred, _perhs, _pecats and other
+low level utility SPost programsto pass to _pecidelta and _peciboot.
+
+{title: Options}
+
+{p 4 8 2}
+{cmd:level()} sets the level of the confidence interval for predicted values
+or probabilities for the commands for which these are provided.
+
+{p 4 8 2}
+{cmd:inout()} specifies model type, such as typical one equation versus two
+equation
+
+{p 4 8 2}
+{cmd:maxcount()} is the maximum count value for which the probability is computed
+in count models. Default is 9.
+
+{p 4 8 2}
+{cmd:diff} computes difference between current predictions and those that were
+saved.
+
+
+{title:Details on Globals}
+
+{p 4 8 2}
+{cmd:petype} - global string with type of model
+
+{p 8 8 2}
+1. Contents - string with three words
+
+{p 8 8 2}
+Word 1. cmd - e(cmd){break}
+Word 2. input from io - typical vs twoeq{break}
+Word 3. output from io - binary count mlogit ordered regress tobit{break}
+
+{p 8 8 2}
+2. To retrieve information
+
+{p 8 8 2}
+local cmd : word 1 of $petype // what model was estimated {break}
+local input : word 2 of $petype // is it a typical or twoeq model? {break}
+local output : word 3 of $petype // what is the output type? {break}
+
+{p 4 8 2}
+{cmd:pecimethod} - global string with type of ci
+
+{p 8 8 2}
+1. Contents - string with two words
+
+{p 8 8 2}
+Word 1. method for ci computation - ml, delta, ept, bootstrap {break}
+Word 2. type of bootstrap ci - normal, percentile, biascorrected {break}
+
+{p 8 8 2}
+2. To retrieve information
+
+{p 8 8 2}
+local cimethod : word 1 of $pecitype{break}
+local boottype : word 2 of $pecitype{break}
+
+
+{p 4 8 2}
+{cmd:peinfo} - global matrix (3x11) with information about the model
+
+{p 8 8 2}
+Row 1: current model {break}
+Row 2: saved model when diff option used{break}
+Row 3: difference current value - saved value{break}
+
+{p 8 8 2}
+Column 1: # of rhs variables (i.e., # of columns inh PEbase) peinfo[1,1]{break}
+Column 2: # of categories in outcome (from _pecats){break}
+Column 3: level for confidence interval (e.g., 95 not .95) peinfo[1,3]{break}
+Column 4: z value for confidence interval at given level peinfo[1,4]{break}
+Column 5: # of rhs variables for inflation in zip and zinb{break}
+Column 6: 1 if model with no constant, else 0 peinfo[1,6]{break}
+Column 7: base category for mlogit{break}
+Column 8: stdp for binary models{break}
+Column 9: # of requested reps for bootstrap (# specified by rep() option){break}
+Column 10: # of completed replications for bootstrap{break}
+Column 11: maximum # of values in predicted probs in count models.{break}
+
+{p 4 8 2}
+{cmd:pebase} and {cmd:pebase2} - base values for the x's
+
+{p 8 8 2}
+matrix pebase = PE_in{break}
+matrix pebase2 = PE_in2{break}
+
+{p 8 8 2}
+The jth column of pebase is the jth right hand size variable in the
+model. The jth column of pebase2 is the jsth right hand side inflation
+variable in zip or zinb. If save and dif, three rows are in the matrix:{break}
+
+{p 8 8 2}
+Row 1: current model {break}
+Row 2: saved model when diff option used{break}
+Row 3: difference current value - saved value{break}
+
+{p 4 8 2}
+{cmd:pepred} - a global matrix (7 by # of outcome) containing predicted values
+
+{p 8 8 2}
+Row 1: values of the outcome category
+
+{p 8 8 2}
+{result:Current model}{break}
+Row 2: predicted probabilities for the value in row 1{break}
+Row 3: Column 1: xb from first part of model{break}
+Column 2: mu from count model{break}
+Column 3: xb from inflation part of zip and zinb{break}
+Column 4: pr(always 0) from zip and zinb{break}
+
+{p 8 8 2}
+{result:Saved model}{break}
+Row 4: predicted probabilities for the value in row 1{break}
+Row 5: Column 1: xb from first part of model{break}
+Column 2: mu from count model{break}
+Column 3: xb from inflation part of zip and zinb{break}
+Column 4: pr(always 0) from zip and zinb{break}
+
+{p 8 8 2}
+{result:Difference for saved - current}{break}
+Row 6: predicted probabilities for the value in row 1{break}
+Row 7: Column 1: xb from first part of model{break}
+Column 2: mu from count model{break}
+Column 3: xb from inflation part of zip and zinb{break}
+Column 4: pr(always 0) from zip and zinb{break}
+
+{p 4 8 2}
+{cmd:peupper} - upper bound of ci
+
+{p 4 8 2}
+{cmd:pelower} - lower bound of ci
+
+{p 8 8 2}
+Row 1: is identical to pepred.{break}
+Rows 2-7: the upper or lower bounds from the corresponding quantity in pepred{break}
+
+*** ADD MATRICES FROM BOOT FOR VARIOUS TYPES OF CIs
+
+{hline}
+{p 2 4 2}Authors: J. Scott Long & Jun Xu{p_end}
+{p 11 4 2}{browse www.indiana.edu/~jslsoc/spost.htm}{p_end}
+{p 11 4 2}spostsup@indiana.edu{p_end}
diff --git a/Modules/ado/plus/_/_pedum.ado b/Modules/ado/plus/_/_pedum.ado
new file mode 100644
index 0000000..2e6e27f
--- /dev/null
+++ b/Modules/ado/plus/_/_pedum.ado
@@ -0,0 +1,9 @@
+*! version 1.6.0 2/27/99
+
+capture program drop _pedum
+program define _pedum, rclass
+ version 6
+ syntax varlist(max=1) [if] [in]
+ capture assert `varlist' == 0 | `varlist' == 1 | `varlist' == . `if' `in'
+ return scalar dummy = _rc==0
+end
diff --git a/Modules/ado/plus/_/_pedum.hlp b/Modules/ado/plus/_/_pedum.hlp
new file mode 100644
index 0000000..a011292
--- /dev/null
+++ b/Modules/ado/plus/_/_pedum.hlp
@@ -0,0 +1,35 @@
+.-
+help for ^_pedum^ - 1.6.0 - 2/27/1999
+.-
+
+Utility to determine if a variable is 0, 1 or .
+-----------------------------------------------
+
+ ^_pedum^ varname [^if^ exp] [^in^ range]
+
+Description
+-----------
+
+^_pedum^ returns the scalar ^r(dummy)^=1 if the variable is binary, else 0.
+ Binary variables have all values equal to 0, 1, or missing.
+
+Examples within a program
+-------------------------
+
+ local i = 1
+ while `i'<=`nvars' {
+ local nmtoget : word `i' of `varnms'
+ _pedum `nmtoget' `if' `in'
+ mat `Sdummy'[1,`i'] = r(dummy)
+ local i=`i'+1
+ }
+
+Note
+----
+
+You must use ^_peife^ prior to calling ^_pedum^.
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
diff --git a/Modules/ado/plus/_/_peife.ado b/Modules/ado/plus/_/_peife.ado
new file mode 100644
index 0000000..522d971
--- /dev/null
+++ b/Modules/ado/plus/_/_peife.ado
@@ -0,0 +1,25 @@
+*! version 1.6.0 2/7/99
+
+capture program drop _peife
+program define _peife, rclass
+ version 6.0
+ syntax [if/] [,All]
+
+ * Case 1: no if and no all
+ if "`if'"=="" & "`all'"!="all" { local ifis "if e(sample)" }
+ else {
+
+ * Case 2: if and no all
+ if "`all'"!="all" { local ifis "if e(sample) & `if'" }
+
+ if "`all'"=="all" {
+
+ * Case 3: if and all
+ if "`if'"!="" { local ifis "if `if'" }
+
+ * Case 4: no if and all
+ if "`if'"=="" { local ifis "" }
+ }
+ }
+ return local if "`ifis'"
+end
diff --git a/Modules/ado/plus/_/_peife.hlp b/Modules/ado/plus/_/_peife.hlp
new file mode 100644
index 0000000..6aa3462
--- /dev/null
+++ b/Modules/ado/plus/_/_peife.hlp
@@ -0,0 +1,54 @@
+.-
+help for ^_peife^ - 1.6.0 - 2/7/1999
+.-
+
+Utility to decide if estimation sample is used
+----------------------------------------------
+
+ ^_peife^ [^if^ exp] [, ^a^ll]
+
+Description
+-----------
+
+^_peife^ modifies the given ^if^ expression to add restrictions to the last
+ estimation sample ^e(sample)^. Whem the option ^all^ is specified, the
+ ^if^ statement is not modified to add ^e(sample)^.
+
+
+Output
+------
+
+You can retrieve a string with the resulting ^if^ statement by using ^r(if)^.
+ For example: local if "`r(if)'" Note that the resulting string includes
+ the work ^if^.
+
+Options
+-------
+
+^all^ By default, the ^if^ statement passed to ^_peife^ is modified to add
+ ^& e(sample)^. With option ^all^ the ^if^ condition is not changed.
+ Consequently, all that is done is the word "if" is placed in front of the
+ current ^if^ condition before the string is returned.
+
+Examples within a program
+-------------------------
+ ...
+ * `if' is the curret if condition
+ _peife `if',`all'
+ * the new condition includes & e(sample)
+ local if "`r(if)'"
+ * note that `if' has the word if in it
+ sum `varlist' `if'
+ ...
+
+Note
+----
+
+_pesum, _pedum, _pecats do not call _peife. You need to pass the correct if
+condition to them.
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_pemarg.ado b/Modules/ado/plus/_/_pemarg.ado
new file mode 100644
index 0000000..7a01b57
--- /dev/null
+++ b/Modules/ado/plus/_/_pemarg.ado
@@ -0,0 +1,232 @@
+*! version 2.5.0 2009-10-28 jsl
+* - stata 11 update for returns from -mlogit-
+
+* compute marginal effects
+
+capture program drop _pemarg
+program define _pemarg, rclass
+
+ * 11Apr2005; 13Jun2005
+ if c(stata_version) >= 9 {
+ tempname tmpb
+ mat `tmpb' = e(b)
+ local tmpcut : colnames `tmpb'
+ if index("`tmpcut'", "_cut1") != 0 {
+ local cut "_"
+ }
+ else {
+ local cut "/"
+ }
+ }
+ else {
+ local cut "_"
+ }
+
+ syntax [, caller(real 5.0)] // 1.7.0 stata version
+
+ version 6.0
+ tempname b x xb sxb prob marg tmp bxb bxbm1 difpdf tmp2
+ tempname b x o xo xb sxb prob marg tmp bxb bxbm1 difpdf tmp2 bi alpha
+ tempname sumxb sp PredVal PredPr sump
+ tempname pdiag sumpb o
+
+ if "`e(cmd)'"=="cloglog" { local hasmarg = "not yet" }
+ if "`e(cmd)'"=="cnreg" { local hasmarg = "not applicable" }
+ if "`e(cmd)'"=="fit" { local hasmarg = "not applicable" }
+ if "`e(cmd)'"=="gologit" { local hasmarg = "not yet" }
+ if "`e(cmd)'"=="intreg" { local hasmarg = "not applicable" }
+ if "`e(cmd)'"=="logistic" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="logit" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="mlogit" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="nbreg" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="ologit" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="oprobit" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="poisson" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="probit" { local hasmarg = "yes" }
+ if "`e(cmd)'"=="regress" { local hasmarg = "not applicable" }
+ if "`e(cmd)'"=="tobit" { local hasmarg = "not applicable" }
+ if "`e(cmd)'"=="zinb" { local hasmarg = "not yet" }
+ if "`e(cmd)'"=="zip" { local hasmarg = "not yet" }
+ return local hasmarg `hasmarg'
+ if "`hasmarg'"!="yes" { exit }
+
+ /* 1.6.4
+ matrix `b' = e(b)
+ if "`e(cmd)'"=="mlogit" {
+ version 5.0
+ matrix `b' = get(_b)
+ version 6.0
+ }
+ */
+
+ tempname eV
+ * 0.2.5 - get b and v for all estimation commands
+ mat `b' = e(b)
+ * drop local nbeta = colsof(`b')
+ if "`e(cmd)'"=="mlogit" {
+ version 5.0
+ matrix `b' = get(_b)
+ version 6.0
+ }
+ mat `eV' = e(V)
+ * 2009-10-28 get b and V under Stata 11
+ if "`e(cmd)'"=="mlogit" { // if mlogit, special treatment
+ nobreak {
+ _get_mlogit_bv `b' `eV'
+ }
+ }
+
+ if "`e(cmd)'"=="nbreg" {
+ local nb = colsof(`b') - 1 /* -1 for alpha */
+ matrix `b' = `b'[1,1..`nb']
+ }
+ matrix `x' = PE_base
+
+ if "`e(cmd)'"=="logit" | "`e(cmd)'"=="probit" | /*
+ */ "`e(cmd)'"=="logistic" | /*
+ */"`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ matrix `x' = `x',J(1,1,1)
+ matrix `xb' = `x' * `b''
+ local nb = colsof(`b') - 1
+ matrix `b' = `b'[1,1..`nb'] /* get rid of _con */
+ scalar `sxb' = `xb'[1,1]
+ if "`e(cmd)'"=="logit" | "`e(cmd)'"=="logistic" {
+ scalar `prob' = exp(`sxb')/(1+exp(`sxb'))
+ scalar `tmp' = `prob'*(1-`prob')
+ matrix `marg' = `tmp'*`b'
+ }
+ else if "`e(cmd)'"=="probit" {
+ scalar `prob' = normprob(`sxb')
+ scalar `tmp' = exp(-`sxb'*`sxb'/2)/sqrt(2*_pi)
+ matrix `marg' = `tmp'*`b'
+ }
+ else if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="nbreg" {
+ scalar `prob' = exp(`sxb')
+ matrix `marg' = `prob'*`b'
+ scalar `prob' = -exp(`sxb') /* to undo change below */
+ }
+ matrix `prob' = -1 * `marg'
+ matrix `marg' = `prob' \ `marg'
+ }
+
+ if "`e(cmd)'"=="oprobit" | "`e(cmd)'"=="ologit" {
+ local ncats = e(k_cat)
+ * xb without intercept
+ local nb = colsof(`b') - `ncats' + 1
+ matrix `b' = `b'[1,1..`nb'] /* get rid of _con's */
+ matrix `xb' = `x' * `b''
+ scalar `sxb' = `xb'[1,1]
+ matrix `difpdf' = J(1,`ncats',1)
+ matrix `marg' = J(`nb',`ncats',1)
+ * compute probabilities
+ if "`e(cmd)'"=="oprobit" {
+ matrix `prob' = J(1,`ncats',1)
+ scalar `bxb' = _b[`cut'cut1]-`sxb'
+ matrix `prob'[1,1] = normprob(`bxb') /* prob for cat 1 */
+ matrix `difpdf'[1,1] = exp(-`bxb'*`bxb'/2)/sqrt(2*_pi)
+ local i 2
+ while `i'<`ncats' {
+ local im1 = `i' - 1
+ scalar `bxb' = _b[`cut'cut`i'] - `sxb'
+ scalar `bxbm1' = _b[`cut'cut`im1'] - `sxb'
+ matrix `prob'[1,`i'] = normprob(`bxb') - normprob(`bxbm1')
+ matrix `difpdf'[1,`i'] = exp(-`bxb'*`bxb'/2)/sqrt(2*_pi) /*
+ */ - exp(-`bxbm1'*`bxbm1'/2)/sqrt(2*_pi)
+ local i = `i' + 1
+ }
+ local im1 = `i' - 1
+ scalar `bxb' = `sxb'-_b[`cut'cut`im1']
+ matrix `prob'[1,`ncats'] = normprob(`bxb')
+ * 12/6/00
+ matrix `difpdf'[1,`ncats'] = -1*exp(-`bxb'*`bxb'/2)/sqrt(2*_pi)
+ }
+ if "`e(cmd)'"=="ologit" {
+ matrix `prob' = J(1,`ncats',1)
+ scalar `tmp' = 1/(1+exp(`sxb'-_b[`cut'cut1]))
+ matrix `prob'[1,1] = `tmp'
+ matrix `difpdf'[1,1] = `tmp'*(1-`tmp')
+ local i 2
+ while `i'<`ncats' {
+ local im1=`i'-1
+ scalar `tmp' = 1/(1+exp(`sxb'-_b[`cut'cut`i']))
+ scalar `tmp2' = 1/(1+exp(`sxb'-_b[`cut'cut`im1']))
+ matrix `prob'[1,`i'] = `tmp' - `tmp2'
+ matrix `difpdf'[1,`i'] = (`tmp'*(1-`tmp')) - (`tmp2'*(1-`tmp2'))
+ local i=`i'+1
+ }
+ local im1 = `i'-1
+ scalar `tmp' = 1/(1+exp(`sxb'-_b[`cut'cut`im1']))
+ matrix `prob'[1,`ncats'] = 1-`tmp'
+ matrix `difpdf'[1,`i'] = - (`tmp'*(1-`tmp'))
+ }
+ local i 1
+ while `i'<=`nb' {
+ local j 1
+ while `j'<=`ncats' {
+ matrix `marg'[`i',`j'] = -1 * `difpdf'[1,`j'] * `b'[1,`i']
+ local j = `j' + 1
+ }
+ local i = `i' + 1
+ }
+ }
+
+ if "`e(cmd)'"=="mlogit" {
+ matrix `x' = PE_base
+ matrix `xo' = `x',J(1,1,1)
+ matrix `PredVal' = J(1,1,1)
+ matrix colnames `PredVal' = xb
+ /* 1.6.4 - does not work with Stat 11
+ version 5.0
+ matrix `b' = get(_b)
+ version 6.0
+ */
+ * 2007-06-29 stata 10
+ if c(stata_version) < 10 {
+ local ncats = e(k_cat)
+ }
+ else {
+ local ncats = e(k_out)
+ }
+ matrix `prob' = J(1,`ncats',-1)
+ matrix `xb' = `b'*`xo'' /* one row for each set of b's */
+ matrix `PredVal' = `xb'
+ scalar `sumxb' = 1
+ local i = 1
+ while `i' < `ncats' {
+ scalar `sxb' = exp(`xb'[`i',1])
+ scalar `sumxb' = `sumxb' + `sxb' /* sum of exp(xb) */
+ matrix `prob'[1,`i'] = `sxb'
+ local i = `i' + 1
+ }
+ scalar `sumxb' = 1/`sumxb'
+ matrix `prob'[1,`ncats'] = 1
+ matrix `prob' = `sumxb'*`prob'
+ matrix `PredPr' = `prob'
+ matrix `pdiag' = `PredPr'
+ matrix `pdiag' = diag(`pdiag')
+ * 2007-06-29 stata 10
+ if c(stata_version) < 10 {
+ local ncats = e(k_cat)
+ }
+ else {
+ local ncats = e(k_out)
+ }
+ local nb = colsof(`b')
+ matrix `b' = `b' \ J(1,`nb',0) /* add 0's for last outcome */
+ matrix `marg' = `pdiag' * (`b' - (J(`ncats',`ncats',1)*`pdiag'*`b'))
+ local nb = colsof(`b') - 1
+ matrix `marg' = `marg'[.,1..`nb']
+ matrix `marg' = `marg''
+ }
+ return matrix marginal `marg'
+
+end
+exit
+
+* version 1.6.0 3/29/01
+* version 1.6.1 11Apr2005 fix _cut for stata 9
+* version 1.6.2 13Apr2005
+* version 1.6.3 13Jun2005 - fix ologit version 8/9 bug with _cut
+* version 1.6.4 2007-06-29 stata 10
+* version 1.7.0 2009-09-19 jsl
+* - fix for e(b) for mlogit in stata 11
diff --git a/Modules/ado/plus/_/_pemarg.hlp b/Modules/ado/plus/_/_pemarg.hlp
new file mode 100644
index 0000000..697bc4b
--- /dev/null
+++ b/Modules/ado/plus/_/_pemarg.hlp
@@ -0,0 +1,15 @@
+.-
+help for ^_pemarg^
+.-
+
+ ^_pemarg^
+
+^_pemarg^ computes marginal effects for some regression models. ^_pemarg^
+takes as its input the contents of the PE_base matrix created by ^_pebase^.
+^_pemarg^ returns the marginal effects in r() class matrix r(marginal)
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_penocon.ado b/Modules/ado/plus/_/_penocon.ado
new file mode 100644
index 0000000..400ad36
--- /dev/null
+++ b/Modules/ado/plus/_/_penocon.ado
@@ -0,0 +1,94 @@
+*! version 0.2.3 13Apr2005
+* version 0.2.2 2005-03-29 stata 9 bug for aux parameters
+* version 0.2.1 2005-03-25 fixed long varlist bug
+* version 0.2.0 2005-02-03
+
+* determine if model has a constant in it
+
+capture program drop _penocon
+program define _penocon, rclass
+ version 9.0
+ tempname beta
+ matrix `beta' = e(b)
+ local nbeta = colsof(`beta')
+ local names : colnames `beta'
+ local tmpnms : subinstr local names `"_cons"' `"dog"', all count(local count)
+ local isnocon = 1 - `count'
+
+// binary
+
+ if "`e(cmd)'"=="cloglog" {
+ local isnocon = `isnocon'
+ }
+ if "`e(cmd)'"=="logistic" {
+ local isnocon = `isnocon'
+ }
+ if "`e(cmd)'"=="logit" {
+ local isnocon = `isnocon'
+ }
+ if "`e(cmd)'"=="probit" {
+ local isnocon = `isnocon'
+ }
+
+// ordered : nocon not allowed
+
+ if "`e(cmd)'"=="ologit" {
+ local isnocon = 0
+ }
+ if "`e(cmd)'"=="oprobit" {
+ local isnocon = 0
+ }
+ if "`e(cmd)'"=="gologit" {
+ local isnocon = 0
+ }
+
+// count
+
+ if "`e(cmd)'"=="poisson" {
+ local isnocon = `isnocon'
+ }
+ if "`e(cmd)'"=="nbreg" {
+ local nrhs = e(df_m)
+ local nbeta = `nbeta' - 1 // subtract alpha
+ local isnocon = (`nrhs'==`nbeta')
+ }
+
+ if "`e(cmd)'"=="zinb" {
+ local tmpnms : subinstr local names `"_cons"' `"dog"', all count(local count)
+ local isnocon = (`count'<3)
+ }
+ if "`e(cmd)'"=="zip" {
+ local tmpnms : subinstr local names `"_cons"' `"dog"', all count(local count)
+ local isnocon = (`count'<2)
+ }
+
+// regression models
+
+ if "`e(cmd)'"=="regress" | "`e(cmd)'"=="fit" {
+ local isnocon = `isnocon'
+ }
+ if "`e(cmd)'"=="tobit" {
+ * stata 9 includes auxillary parameters as a second equation
+ local isnocon = (`count'==1)
+ }
+ if "`e(cmd)'"=="cnreg" {
+ local isnocon = (`count'==1)
+ }
+ if "`e(cmd)'"=="intreg" {
+ local isnocon = (`count'==1)
+ }
+
+// nominal
+
+ if "`e(cmd)'"=="mlogit" {
+ _perhs
+ local nrhs = r(nrhs)
+ local ncatm1 = e(k_cat) - 1
+ local isnocon = (`nrhs'*`ncatm1'==`nbeta')
+ }
+
+// return results
+
+ return local nocon "`isnocon'"
+
+end
diff --git a/Modules/ado/plus/_/_penocon.hlp b/Modules/ado/plus/_/_penocon.hlp
new file mode 100644
index 0000000..f341644
--- /dev/null
+++ b/Modules/ado/plus/_/_penocon.hlp
@@ -0,0 +1,41 @@
+{smcl}
+{* 01/13/05}{...}
+{hline}
+help for {hi:_penocon}{right:1/13/2005}
+{hline}
+
+{title: Utility to determine if model was run with nocon option}
+
+{p 8 15 2}{cmd:_penocon}
+
+
+{title: Description}
+
+{p 4 4 2}
+{cmd:_penocon} returns 1 if model used nocon option, else 0. Works
+with {help cloglog}, {help logistic}, {help logit}, {help probit},
+{help ologit}, {help oprobit}, {help gologit}, {help poisson},
+{help nbreg}, {help zinb}, {help zip}, {help regress}, {help tobit},
+{help cnreg}, {help fit}, {help intreg}, and {help mlogit}.
+
+{title: Returns}
+
+{p 4 8 2}
+r(nocon) : local with 1 if nocon option, else 0.
+
+{title: Examples}
+
+ ...
+ _penocon
+ local isnocon = r(nocon)
+ if `isnocon'==1 {
+ ::: case without constant :::
+ }
+ else {
+ :::
+ }
+
+{hline}
+{p 2 4 2}Authors: J. Scott Long & Jun Xu{p_end}
+{p 11 4 2}{browse www.indiana.edu/~jslsoc/spost.htm}{p_end}
+{p 11 4 2}spostsup@indiana.edu{p_end}
diff --git a/Modules/ado/plus/_/_pepred.ado b/Modules/ado/plus/_/_pepred.ado
new file mode 100644
index 0000000..7c653b4
--- /dev/null
+++ b/Modules/ado/plus/_/_pepred.ado
@@ -0,0 +1,651 @@
+*! version 1.6.9 2013-08-05 increase maxcnt to 40
+* version 1.6.8 2008-07-10
+* - make stdp global
+
+* _pepred takes as input the matrix PE_in; each row is an observation and
+* the columns are values for the independent variables in the regression
+* model. _pepred temporarily adds these observations to the dataset and
+* generates predicted values. _pepred puts the predicted values in
+* return matrices that can then be used by the calling program.
+
+capture program drop _pepred
+program define _pepred, rclass
+ version 6
+ tempvar added stdp stdf xb xb_hi xb_lo p p1 p1_hi p1_lo p0 p0_hi p0_lo mucount mu
+ tempvar mu_hi mu_lo tempvar p1_inf p0_inf always0
+ tempname b alpha ai gai b_inf xb_inf infby replval zwidth
+ syntax [, level(integer $S_level) maxcnt(integer 9) choices(varlist)]
+ *handle 'level' option
+ if `level' < 10 | `level' > 99 {
+ di in r "level() invalid"
+ error 198
+ }
+ local level = `level'/100
+ *`zwidth' = SD width of confidence interval for `level'% ci
+ sca `zwidth' = invnorm(`level'+((1-`level')/2))
+
+ *check if `maxcnt' specified to acceptable value
+ local max_i = `maxcnt' /* how should this be set */
+ if `max_i' < 0 | `max_i' > 41 {
+ di in r "maxcnt() value not allowed"
+ exit 198
+ }
+
+ *preserve needed because data altered
+ preserve
+
+ *add observations to end of dataset
+ qui gen `added' = 0
+ local newobs = rowsof(PE_in)
+ local oldn = _N
+ local newn = `oldn'+`newobs'
+ qui set obs `newn'
+ *`added'==1 for observations created by _pepred
+ qui replace `added' = 1 if `added' == .
+
+ *use _perhs to get information about rhs variables
+ _perhs
+ local nrhs `r(nrhs)'
+ local nrhs2 `r(nrhs2)'
+ local rhsnms `r(rhsnms)'
+ local rhsnms2 `r(rhsnms2)'
+
+ *fill in added observations with rows of PE_in
+ *cycle through all rhs variables
+ local i = 1
+ while `i' <= `nrhs' {
+ local varname : word `i' of `rhsnms'
+ *for each rhs variable, cycle through all added observations
+ local i2 = 1
+ while `i2' <= `newobs' {
+ *to_rep is the row number of the observation to insert PE_in values
+ local to_rep = `oldn' + `i2'
+ *`replval' value to move from PE_in to dataset
+ sca `replval' = PE_in[`i2',`i']
+ qui replace `varname' = `replval' in `to_rep'
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+ *fill in values for variables in second equation of ZIP/ZINB model
+ if "`nrhs2'"!="" {
+ local i = 1
+ while `i' <= `nrhs2' {
+ local varname : word `i' of `rhsnms2'
+ local i2 = 1
+ while `i2' <= `newobs' {
+ local to_rep = `oldn' + `i2'
+ sca `replval' = PE_in2[`i2',`i']
+ qui replace `varname' = `replval' in `to_rep'
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+ } /* if "`nrhs2'"!="" */
+
+ *list `rhsnms' in -`newobs'/-1
+ *if "`nrhs2'"!="" { list `rhsnms2' in -`newobs'/-1 }
+
+ *specify routine below that estimation command should call
+
+ if "`e(cmd)'"=="slogit" { local routine "slogit" } // 26Mar2005
+ if "`e(cmd)'"=="mprobit" { local routine "mprobit" } // 28Feb2005
+ if "`e(cmd)'"=="ztp" { local routine "zt" } // 050218
+ if "`e(cmd)'"=="ztnb" { local routine "zt" }
+ if "`e(cmd)'"=="clogit" { local routine "clogit" }
+ if "`e(cmd)'"=="cloglog" { local routine "binary" }
+ if "`e(cmd)'"=="cnreg" { local routine "tobit" }
+ if "`e(cmd)'"=="fit" { local routine "regress" }
+ if "`e(cmd)'"=="gologit" { local routine "gologit" }
+ if "`e(cmd)'"=="intreg" { local routine "tobit" }
+ if "`e(cmd)'"=="logistic" { local routine "binary" }
+ if "`e(cmd)'"=="logit" { local routine "binary" }
+ if "`e(cmd)'"=="mlogit" { local routine "mlogit" }
+ if "`e(cmd)'"=="nbreg" { local routine "count" }
+ if "`e(cmd)'"=="ologit" { local routine "ordered" }
+ if "`e(cmd)'"=="oprobit" { local routine "ordered" }
+ if "`e(cmd)'"=="poisson" { local routine "count" }
+ if "`e(cmd)'"=="probit" { local routine "binary" }
+ if "`e(cmd)'"=="regress" { local routine "regress" }
+ if "`e(cmd)'"=="tobit" { local routine "tobit" }
+ if "`e(cmd)'"=="zinb" { local routine "zeroinf" }
+ if "`e(cmd)'"=="zip" { local routine "zeroinf" }
+
+*Note: these routines define a local macro `newvars', which is a list of
+* all matrices that _pepred will return to the calling program.
+
+*NB!?: predictions are done for all observations because you can't use temporary
+*variables as an if condition after predict (if `added' == 1)
+
+*BINARY ROUTINE
+
+ if "`routine'" == "binary" {
+ local newvars "xb stdp p1 p0 xb_hi p1_hi p0_hi xb_lo p1_lo p0_lo"
+
+ quietly {
+
+ *use predict to get xb and std err of prediction
+ predict `xb', xb
+ predict `stdp', stdp
+ *2008-07-09
+ global stdp = `stdp'[1]
+
+ *calculate upper and lower ci for xb
+ gen `xb_hi' = `xb' + (`zwidth'*`stdp')
+ gen `xb_lo' = `xb' - (`zwidth'*`stdp')
+
+ *convert ci bounds into probabilities
+ if "`e(cmd)'"=="logit" | "`e(cmd)'"=="logistic" {
+ gen `p1' = exp(`xb')/(1+exp(`xb'))
+ gen `p1_hi' = exp(`xb_hi')/(1+exp(`xb_hi'))
+ gen `p1_lo' = exp(`xb_lo')/(1+exp(`xb_lo'))
+ }
+ if "`e(cmd)'"=="probit" {
+ gen `p1' = normprob(`xb')
+ gen `p1_hi' = normprob(`xb_hi')
+ gen `p1_lo' = normprob(`xb_lo')
+ }
+ if "`e(cmd)'"=="cloglog" {
+ gen `p1' = 1 - exp(-exp(`xb'))
+ gen `p1_hi' = 1 - exp(-exp(`xb_hi'))
+ gen `p1_lo' = 1 - exp(-exp(`xb_lo'))
+ }
+
+ *use prob(1) values to calculate corresponding prob(0) values
+ gen `p0' = 1 - `p1'
+ gen `p0_hi' = 1 - `p1_hi'
+ gen `p0_lo' = 1 - `p1_lo'
+
+ } /* quietly */
+ }
+
+* ORDERED ROUTINE
+
+ if "`routine'" == "ordered" {
+ quietly {
+
+ *get information about categories of dependent variables
+ _pecats
+ local ncats = r(numcats)
+ local catvals "`r(catvals)'"
+
+ *use predict to get probabilities for each outcome
+ *cycle through each category
+ local i = 1
+ while `i' <= `ncats' {
+ tempvar p`i'
+ local newvars "`newvars'p`i' "
+ local catval : word `i' of `catvals'
+ *_PEtemp has to be used because temporary variable causes error
+ capture drop _PEtemp
+ predict _PEtemp, p outcome(`catval')
+ gen `p`i'' = _PEtemp
+ local i = `i' + 1
+ }
+
+ *use predict to get probability of xb and std err of prediction
+ local newvars "`newvars'xb stdp xb_hi xb_lo"
+ capture drop _PEtemp
+ predict _PEtemp, xb
+ qui gen `xb' = _PEtemp
+ capture drop _PEtemp
+ predict _PEtemp, stdp
+ qui gen `stdp' = _PEtemp
+ *2008-07-09
+ global stdp = `stdp'[1]
+
+ *calculate upper and lower ci's for xb
+ gen `xb_hi' = `xb' + (`zwidth'*`stdp')
+ gen `xb_lo' = `xb' - (`zwidth'*`stdp')
+
+ } /* quietly { */
+ } /* if "`routine'" == "ordered" */
+
+* MLOGIT ROUTINE
+
+ if "`routine'" == "mlogit" {
+
+ *get information on categories of dependent variable
+ _pecats
+ local ncats = r(numcats)
+ local catvals "`r(catvals)'"
+ local refval "`r(refval)'"
+
+ local i = 1
+ quietly {
+ while `i' <= `ncats' {
+ tempvar p`i' xb`i' stdp`i' sdp`i' xb_hi`i' xb_lo`i'
+ local newvars "`newvars'p`i' "
+
+ *use predict to get probabilities for each outcome
+ local catval : word `i' of `catvals'
+ capture drop _PEtemp
+ predict _PEtemp, p outcome(`catval')
+ gen `p`i'' = _PEtemp
+
+ *if `i' != `ncats', then outcome is not base category
+ if `i' != `ncats' {
+ local newvars "`newvars'xb`i' stdp`i' sdp`i' "
+ capture drop _PEtemp
+ *use predict to get standard error of prediction
+ predict _PEtemp, stdp outcome(`catval')
+ qui gen `stdp`i'' = _PEtemp
+ capture drop _PEtemp
+ *use predict to get standard error of difference in prediction
+ predict _PEtemp, stddp outcome(`catval', `refval')
+ qui gen `sdp`i'' = _PEtemp
+ capture drop _PEtemp
+ *use predict to get xb
+ predict _PEtemp, xb outcome(`catval')
+ qui gen `xb`i'' = _PEtemp
+ *calculate upper and lower bounds of ci
+ qui gen `xb_hi`i'' = `xb`i'' + (`zwidth'*`stdp`i'')
+ qui gen `xb_lo`i'' = `xb`i'' - (`zwidth'*`stdp`i'')
+ }
+ local i = `i' + 1
+ } /* while `i' <= `ncats' */
+ }
+ }
+
+* MPROBIT 28Feb2005
+
+ if "`routine'" == "mprobit" {
+
+ *get information on categories of dependent variable
+ _pecats
+ local ncats = r(numcats)
+ local catvals "`r(catvals)'"
+ local refval "`r(refval)'"
+
+ local i = 1
+ quietly {
+ while `i' <= `ncats' {
+ tempvar p`i' xb`i' /*stdp`i' sdp`i' xb_hi`i' xb_lo`i'*/
+ local newvars "`newvars'p`i' "
+ *use predict to get probabilities for each outcome
+ local catval : word `i' of `catvals'
+ capture drop _PEtemp
+ predict _PEtemp, p outcome(`catval')
+ gen `p`i'' = _PEtemp
+
+ *if `i' != `ncats', then outcome is not base category
+ if `i' != `ncats' {
+ local newvars "`newvars'xb`i' " /*stdp`i' sdp`i' "*/
+ capture drop _PEtemp
+ *use predict to get standard error of prediction
+ capture drop _PEtemp
+ *use predict to get standard error of difference in prediction
+ capture drop _PEtemp
+ *use predict to get xb
+ predict _PEtemp, xb outcome(`catval')
+ qui gen `xb`i'' = _PEtemp
+ }
+ local i = `i' + 1
+ } /* while `i' <= `ncats' */
+ }
+ }
+
+
+* SLOGIT 26Mar2005
+
+ if "`routine'" == "slogit" {
+ *get information on categories of dependent variable
+ _pecats
+ local ncats = r(numcats)
+ local catvals "`r(catvals)'"
+ local refval "`r(refval)'"
+
+ local i = 1
+ quietly {
+ while `i' <= `ncats' {
+ tempvar p`i' xb`i' /*stdp`i' sdp`i' xb_hi`i' xb_lo`i'*/
+ local newvars "`newvars'p`i' "
+ *use predict to get probabilities for each outcome
+ local catval : word `i' of `catvals'
+ capture drop _PEtemp
+ predict _PEtemp, p outcome(`catval')
+ gen `p`i'' = _PEtemp
+ local i = `i' + 1
+ } /* while `i' <= `ncats' */
+ } /* quietly */
+ } /* if "`routine'" == "slogit" */
+
+ if "`routine'" == "gologit" {
+
+ *get information about number of categories
+ _pecats
+ local ncats = r(numcats)
+ local catvals "`r(catvals)'"
+ local numeqs = `ncats'-1 /* number of equations */
+ quietly {
+
+ *cycle through each equation
+ local i = 1
+ while `i' <= `numeqs' {
+ tempvar xb`i' pcut`i'
+ *use predict to get xb for each equation
+ predict `xb`i'', eq(mleq`i')
+ local newvars "`newvars'xb`i' "
+ *convert xb into prob(y<=`i')
+ gen `pcut`i'' = exp(`xb`i'')/(1+exp(`xb`i''))
+ local i = `i' + 1
+ }
+
+ *setting variables to indicate that prob(y<=0)=0 and prob(y<=`ncats)=1
+ tempvar pcut`ncats' pcut0
+ gen `pcut`ncats''=0
+ gen `pcut0'=1
+
+ *cycle through categories
+ local i = 1
+ while `i' <= `ncats' {
+ tempvar p`i'
+ local newvars "`newvars'p`i' "
+ local j = `i' - 1
+ *calculate prob(y=i) as prob(y<=i) - prob(y<=[i-1])
+ gen `p`i'' = `pcut`j''-`pcut`i''
+ local i = `i' + 1
+ } /* while `i' <= `ncats' */
+ } /* quietly */
+ } /* if "`routine'" == "gologit" */
+
+* COUNT MODEL ROUTINE
+
+ if "`routine'"=="count" | "`routine'" == "zt" { // 050218
+ quietly {
+
+ *get alpha if nbreg
+ *zt 18Feb2005
+ if "`e(cmd)'"=="nbreg" | "`e(cmd)'"=="ztnb" {
+ sca `alpha' = e(alpha)
+ sca `ai' = 1/`alpha'
+ *`gai' used to calculate probabilities
+ sca `gai' = exp(lngamma(`ai'))
+ if `gai'==. {
+ di in r "problem with alpha from nbreg prohibits " /*
+ */ "estimation of predicted probabilities"
+ exit 198
+ }
+ }
+
+ *use predict to get mu, xb, and std err of prediction
+ *zt add Cmu for conditional mu 050218
+ tempname Cmu
+ local newvars "mu xb stdp "
+ capture drop _PEtemp
+ predict double _PEtemp, ir /* does not handle offset or exposure */
+ gen `mu' = _PEtemp
+ capture drop _PEtemp
+ predict double _PEtemp, xb
+ gen `xb' = _PEtemp
+ capture drop _PEtemp
+ predict double _PEtemp, stdp
+ gen `stdp' = _PEtemp
+ *zt Cmu 18Feb2005
+ * compute conditional rate
+ if "`e(cmd)'"=="ztnb" | "`e(cmd)'"=="ztp" {
+ capture drop _PEtemp
+ predict double _PEtemp, cm
+ gen `Cmu' = _PEtemp
+ local newvars "mu xb stdp Cmu "
+ }
+
+ *ci's for poisson (doesn't work for nbreg because of alpha)
+ *zt and compute upper and lower 18Feb2005
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="ztp" {
+ local newvars "`newvars'xb_hi xb_lo mu_hi mu_lo "
+ gen `xb_hi' = `xb' + (`zwidth'*`stdp')
+ gen `xb_lo' = `xb' - (`zwidth'*`stdp')
+ gen `mu_hi' = exp(`xb_hi')
+ gen `mu_lo' = exp(`xb_lo')
+ }
+
+ *calculate prob of observing a given count [Prob(y=1)]
+ *cycle from 0 to maximum count wanted
+ local i = 0
+ while `i' <= `max_i' {
+ tempvar p`i'
+ local newvars "`newvars'p`i' "
+ *predicting a particular count from mu
+ *zt 18Feb2005
+ if "`e(cmd)'"=="poisson" | "`e(cmd)'"=="ztp" {
+ * usual poisson formula
+ qui gen double `p`i'' = ((exp(-`mu'))*(`mu'^`i')) / /*
+ */ (round(exp(lnfact(`i'))), 1)
+ tempname p_hi`i' p_lo`i'
+ local newvars "`newvars'p_hi`i' p_lo`i' "
+ qui gen double `p_hi`i'' = /*
+ */ ((exp(-`mu_hi'))*(`mu_hi'^`i')) / /*
+ */ (round(exp(lnfact(`i'))), 1)
+ qui gen double `p_lo`i'' /*
+ */ = ((exp(-`mu_lo'))*(`mu_lo'^`i')) /*
+ */ / (round(exp(lnfact(`i'))), 1)
+ }
+
+ *zt 18Feb2005
+ if "`e(cmd)'"=="nbreg" | "`e(cmd)'"=="ztnb" {
+ capture drop _PEtemp
+ qui gen double _PEtemp = ( exp(lngamma(`i'+`ai')) /*
+ */ / ( round(exp(lnfact(`i')),1) * exp(lngamma(`ai')) ) ) /*
+ */ * ((`ai'/(`ai'+`mu'))^`ai') * ((`mu'/(`ai'+`mu'))^`i')
+ qui gen double `p`i'' = _PEtemp
+ }
+ local i = `i' + 1
+ }
+ return scalar maxcount = `max_i'
+ } /* quietly */
+
+*-> GENERATE CONDITIONAL PREDICTED PROBABILITIES
+ *zt compute conditional predictions 18Feb2005
+ if "`e(cmd)'"=="ztp" | "`e(cmd)'"=="ztnb" {
+ local i 1
+ while `i' <= `max_i' {
+ tempvar Cp`i' // C for Conditional
+ local newvars "`newvars'Cp`i' "
+ * divide by prob not equal to 0
+ quietly gen `Cp`i'' = `p`i''/(1-`p0')
+ label variable `Cp`i'' "Pr(y=`i'|y>0) `modelis'"
+ local i = `i' + 1
+ }
+ } // zt
+
+ } /* if "`routine'" == "count" */
+
+
+* ZERO-INFLATED COUNT MODEL ROUTINE
+
+ if "`routine'"=="zeroinf" {
+ quietly {
+ * mucount == mu from count portion of model - 15Apr2005
+ * mu == expected y
+ local newvars "mu mucount xb stdp p "
+ capture drop _PEtemp
+ * E(y)
+ predict double _PEtemp, n /* does not handle offset or exposure */
+ gen double `mu' = _PEtemp
+ capture drop _PEtemp
+ predict double _PEtemp, xb
+ * xb from the count portion of the model
+ gen double `xb' = _PEtemp
+ capture drop _PEtemp
+ predict double _PEtemp, stdp
+ gen `stdp' = _PEtemp
+ capture drop _PEtemp
+ predict double _PEtemp, p
+ gen `p' = _PEtemp
+ * E(y | not always 0) - 15Apr2005
+ quietly gen double `mucount' = `mu'/(1-`p')
+ mat `b' = e(b)
+ if "`e(cmd)'"=="zinb" {
+ local temp = colsof(`b')
+ sca `alpha' = `b'[1, `temp']
+ sca `alpha' = exp(`alpha')
+ sca `ai' = 1/`alpha'
+ sca `gai' = exp(lngamma(`ai'))
+ if `gai'==. {
+ di in r "problem with alpha from zinb prohibits " /*
+ */ "estimation of predicted probabilities"
+ exit 198
+ }
+ *take alpha off beta matrix
+ local temp = `temp' - 1
+ mat `b' = `b'[1, 1..`temp']
+ }
+
+ *make beta matrix for inflate equation
+ local temp = `nrhs' + 2
+ local temp2 = colsof(`b')
+ mat `b_inf' = `b'[1,`temp'..`temp2']
+
+ *calculate xb of the inflate model
+ local newvars "`newvars'xb_inf "
+ gen double `xb_inf' = 0 if `added' == 1
+ local i = 1
+ while `i' <= `nrhs2' {
+ local infvar : word `i' of `rhsnms2'
+ sca `infby' = `b_inf'[1,`i']
+ replace `xb_inf' = `xb_inf' + (`infby'*`infvar')
+ local i = `i' + 1
+ }
+ *add constant
+ replace `xb_inf' = `xb_inf' + `b_inf'[1, `i']
+
+ *calculate prob(inflate==1)
+ if "`e(inflate)'"=="logit" {
+ gen `p1_inf' = exp(`xb_inf')/(1+exp(`xb_inf'))
+ }
+ if "`e(inflate)'"=="probit" {
+ gen `p1_inf' = normprob(`xb_inf')
+ }
+
+ *calculate prob(inflate==0)
+ gen `p0_inf' = 1 - `p1_inf'
+
+ *return prob(inflate==1) as `always0'
+ local newvars "`newvars'always0 "
+ gen `always0' = `p1_inf'
+
+ *predicting a particular count from mucount
+ local i = 0
+ while `i' <= `max_i' {
+ tempvar p`i'
+ local newvars "`newvars'p`i' "
+ * use mucount not mu! 15Apr2005
+ if "`e(cmd)'"=="zip" {
+ qui gen double `p`i'' = /*
+ */ ((exp(-`mucount'))*(`mucount'^`i'))/(round(exp(lnfact(`i'))), 1)
+ }
+ * use mucount not mu! 15Apr2005
+ if "`e(cmd)'"=="zinb" {
+ capture drop _PEtemp
+ qui gen double _PEtemp = ( exp(lngamma(`i'+`ai')) /*
+ */ / (round(exp(lnfact(`i')),1) * exp(lngamma(`ai')))) /*
+ */ * ((`ai'/(`ai'+`mucount'))^`ai') * ((`mucount'/(`ai'+`mucount'))^`i')
+ qui gen double `p`i'' = _PEtemp
+ }
+
+ *adjust counts for always zeros
+ qui replace `p`i'' = `p`i''*`p0_inf'
+
+ local i = `i' + 1
+ }
+ *adjust prob(y=0) for always zeros
+ replace `p0' = `p0' + `always0'
+ return scalar maxcount = `max_i'
+
+ } /* quietly */
+ } /* if "`routine'" == "zeroinf" */
+
+* TOBIT ROUTINE
+
+ if "`routine'" == "tobit" {
+* remove stdf 6/23/2006
+* local newvars "`newvars'xb xb_hi xb_lo stdp stdf "
+ local newvars "`newvars'xb xb_hi xb_lo stdp "
+ quietly {
+ predict `xb', xb
+ predict `stdp', stdp
+ *2008-07-09
+ global stdp = `stdp'[1]
+
+ * remove stdf 6/23/2006
+ * predict `stdf', stdf
+ gen `xb_hi' = `xb' + (`zwidth'*`stdp')
+ gen `xb_lo' = `xb' - (`zwidth'*`stdp')
+ }
+ }
+
+* REGRESS ROUTINE
+
+ if "`routine'" == "regress" {
+ * remove stdf 6/23/2006
+ * local newvars "`newvars'xb xb_hi xb_lo stdp stdf "
+ local newvars "`newvars'xb xb_hi xb_lo stdp "
+ quietly {
+ predict `xb', xb
+ predict `stdp', stdp
+ *2008-07-09
+ global stdp = `stdp'[1]
+
+ * remove stdf 6/23/2006
+ * predict `stdf', stdf
+ gen `xb_hi' = `xb' + (`zwidth'*`stdp')
+ gen `xb_lo' = `xb' - (`zwidth'*`stdp')
+ }
+ }
+
+** MAKE RETURN MATRICES
+
+ *return level
+ return local level `level'
+ tokenize "`newvars'"
+
+ *cycle through all the new variables created by routine above
+ local i = 1
+ while "``i''" != "" {
+
+ *make matrix tmatnam with all observations for a given new variable
+ local tmatnam = "_``i''"
+ if length("`tmatnam'") > 7 {
+ local tmatnam = substr("`tmatnam'", 1, 7)
+ }
+ tempname `tmatnam'
+ mat ``tmatnam'' = J(`newobs', 1, 0)
+ local i2 = 1
+ while `i2' <= `newobs' {
+ local outob = `oldn' + `i2'
+ mat ``tmatnam''[`i2',1] = ```i'''[`outob']
+ local i2 = `i2' + 1
+ }
+ *return matrix so available to calling program
+ return matrix ``i'' ``tmatnam''
+ local i = `i' + 1
+ }
+
+end
+
+
+exit
+
+15Apr2005 - correct error for zip and zinb (see changes in _pepred, _pecollect, _peciboot
+
+ E(y) was used incorrectly rather than E(y|~always0).
+
+ _pepred[3|5|7, 2] used to be mu defined as rate in count portion of model E(y|not always 0)
+
+ _pepred[3|5|7, 2] now is the overall rate E(y); listed as simply mu.
+
+ _pepred[3|5|7, 3] rate in count portion of model E(y|not always 0); listed as mucount.
+
+To simplify changes in _peciboot, E(y) is referred to as mu; E(y|~always0) is mucount.
+
+* version 1.6.7 2008-07-09
+* - save se of ystar predictions
+* version 1.6.6 23Jun2006 fix stdf bug for regress and tobit
+* version 1.6.5 15Apr2005 fix rate used for zip/zinb (see notes at end)
+* version 1.6.4 13Apr2005
+* version 1.6.3 27Mar2005 slogit
+* version 1.6.2 28Feb2005 mprobit
+* version 1.6.1 18Feb2005 zt models
+* version 1.6.0 3/29/01
diff --git a/Modules/ado/plus/_/_pepred.hlp b/Modules/ado/plus/_/_pepred.hlp
new file mode 100644
index 0000000..f5d62ae
--- /dev/null
+++ b/Modules/ado/plus/_/_pepred.hlp
@@ -0,0 +1,54 @@
+.-
+help for ^_pepred^
+.-
+
+ _pepred [, level(integer) maxcnt(integer)]
+
+^_pepred^ is a utility program designed to generate predicted values from a
+series of specified values of the independent variables. _pepred takes as
+input the matrix PE_in; each row is an observation and the columns are
+values for the independent variables in the regression model. ^_pepred^
+temporarily adds these observations to the dataset and generates predicted
+values. _pepred puts the predicted values in return matrices that can then
+be used by the calling program.
+
+Options
+-------
+
+^level()^ sets the level of the confidence interval for predicted values
+ or probabilities for the estimation commands for which these are
+ provided.
+
+^maxcnt()^ is the maximum count value for which the probability is computed
+ in count models. Default is 9.
+
+Return Values
+-------------
+
+Scalars
+ r(always0) : pr(Always0) for zip and zinb
+ r(xb): value of xb
+ r(xb_lo): lower bound of confidence interval for xb
+ r(xb_hi): upper bound of confidence interval for xb
+ r(p0): predicted prob of 0 for binary model
+ r(p0_lo): lower bound of confidence interval for predicted probability of 0
+ r(p0_hi): upper bound of confidence interval for predicted probability of 0
+ r(p1): predicted prob of 1 for binary model
+ r(p1_lo): lower bound of confidence interval for predicted probability of 1
+ r(p1_hi): upper bound of confidence interval for predicted probability of 1
+ r(mu): predicted count or rate for count models
+
+Macros:
+ r(level) : confidence level for commands that have this
+
+Matrices:
+ r(probs): predicted probabilities for multiple categories or counts
+ r(values): values of outcome categories for rows of r(probs)
+ r(x): x values for independent variables
+ r(x2): x values for independent variables in second equation (^zip^, ^zinb^)
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_perhs.ado b/Modules/ado/plus/_/_perhs.ado
new file mode 100644
index 0000000..6591f90
--- /dev/null
+++ b/Modules/ado/plus/_/_perhs.ado
@@ -0,0 +1,107 @@
+*! version 1.6.6 2010-06-30 parse out o. names
+* version 1.6.5 13Apr2005
+* version 1.6.4 2005-01-23 fix with zip and nocon
+
+* determine rhs variables
+
+capture program drop _perhs
+program define _perhs, rclass
+ version 6.0
+ * if name is passed as option it will parse these names
+ local beta "`1'"
+ if "`beta'" == "" {
+ tempname beta
+ matrix `beta' = e(b)
+ }
+ local varnms : colnames(`beta')
+
+
+* 1.6 6 - strip out omitted coefficients with names o.
+ local no_o ""
+ foreach v in `varnms' {
+ local iso = substr("`v'",1,2)
+ if "`iso'"!="o." {
+ local no_o "`no_o' `v'"
+ }
+ }
+ local varnms `no_o'
+
+ tokenize "`varnms'", parse(" ")
+
+ local iszi = 0 /* is it a zip model? */
+ if "`e(cmd)'"=="zip" | "`e(cmd)'"=="zinb" {
+ _penocon /* check if there is a constant */
+ local ncon = 1 - `r(nocon)' /* 1 if constant, else 0 */
+ local iszi = 1 /* it is a zip */
+ }
+
+ * strip off _cons, _cut & _se
+ local rhsnm ""
+
+ *050123 only for nonzip
+ if `iszi'==0 {
+ local hascon "no"
+ local i 1
+ while "``i''" != "" {
+ * version 1.6.3 2004-12-22 - wrong rhs names if mlogit, nocon
+ * When it finds the same variable a second time, program sets
+ * local hascon to yes even though there is not a constant.
+ * without this it would repeat all variables ncat-1 times.
+ if "`i'"=="1" {
+ local nm1 "``i''"
+ }
+ else if "`nm1'" == "``i''" {
+ local hascon "yes"
+ }
+
+ if "``i''" == "_cons" & "`hascon'"=="no" {
+ local hascon "yes"
+ local start2 = `i' + 1
+ }
+ if "``i''" != "_cons" /*
+ */ & "``i''" != "_se" /*
+ */ & substr("``i''",1,4) != "_cut" /*
+ */ & "`hascon'"=="no" {
+ local rhsnm "`rhsnm' ``i''"
+ }
+ local i = `i' + 1
+ }
+ local nvar : word count `rhsnm'
+ } /* 050123 not zip */
+
+ *050123 if zip, have to count differently for case with no constant
+ if `iszi'==1 {
+ local nvar = e(df_m) /* # vars in count model */
+ local i = 1
+ while `i'<=`nvar' {
+ local rhsnm "`rhsnm' ``i''"
+ local ++i
+ }
+ local i = `i' + `ncon' /* if constant, skip it */
+ local rhsnm2 ""
+ local nvar2 = e(df_c) - 1 /* # vars in inf model */
+ while `i'<=`nvar'+`nvar2'+`ncon' {
+ local rhsnm2 "`rhsnm2' ``i''"
+ local ++i
+ }
+ } /* end of case for zip/zinb */
+
+ * specail case for mlogit
+ if "`e(cmd)'"=="mlogit" {
+ parse "`rhsnm'", parse(" ")
+ local rhsnm2 ""
+ local i 1
+ while `i' <= `nvar' {
+ local rhsnm2 "`rhsnm2' ``i''"
+ local i = `i' + 1
+ }
+ local rhsnm "`rhsnm2'"
+ local rhsnm2 ""
+ }
+
+ return local rhsnms "`rhsnm'"
+ return local nrhs "`nvar'"
+ return local rhsnms2 "`rhsnm2'"
+ return local nrhs2 "`nvar2'"
+
+end
diff --git a/Modules/ado/plus/_/_perhs.hlp b/Modules/ado/plus/_/_perhs.hlp
new file mode 100644
index 0000000..ab1db0d
--- /dev/null
+++ b/Modules/ado/plus/_/_perhs.hlp
@@ -0,0 +1,46 @@
+.-
+help for ^_perhs^ - 1.6.2 - 2/20/00
+.-
+
+Utility to determine names and number of right hand size variables
+in regression models
+------------------------------------------------------------------
+
+ ^_perhs^
+
+Description
+-----------
+
+^_perhs^ returns the number of right hand side variables and their names
+ for regression models.
+
+Works with regress, logit, probit, ologit, oprobit, mlogit, tobit,
+ zip, zinb, poisson, nbreg.
+
+Returns
+-------
+
+r(nrhs) : local with number of rhs variables, excluding intercept.
+
+r(rhsnms): local with names of rhs variables.
+
+Examples within a program
+-------------------------
+
+ ...
+ _perhs
+ local nvars = `r(nrhs)' + 1
+ local varnms "`e(depvar)' `r(rhsnms)'"
+
+ local i = 1
+ while `i'<=`nvars' {
+ local nmtoget : word `i' of `varnms'
+ :::
+ local i=`i'+1
+ }
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_pesum.ado b/Modules/ado/plus/_/_pesum.ado
new file mode 100644
index 0000000..3cfbb1f
--- /dev/null
+++ b/Modules/ado/plus/_/_pesum.ado
@@ -0,0 +1,87 @@
+*! version 1.6.2 1/6/01
+
+capture program drop _pesum
+program define _pesum, rclass
+ version 6.0
+ tempvar b tmp
+ syntax [fweight aweight pweight] [if] [in][,Median Dummy Two]
+
+* get weight info - if weight not specified in _pesum looks to see if estimation
+* was done with weights anyway - this way one can either have _pesum handle the
+* weights or let _pesum do it
+
+ local wtis "[`weight'`exp']"
+ if "`wtis'"=="" & "`e(wtype)'"!="" {
+ local weight "`e(wtype)'"
+ local wtis "[`e(wtype)'`e(wexp)']"
+ }
+ if "`weight'"=="pweight" {
+ local wtis "[aweight`e(wexp)']"
+ di in r "Warning: " in g "pweights are being treated as aweights to compute SDs"
+ }
+ if "`weight'"=="iweight" {
+ di in r "Error: command is incompatible with iweights."
+ exit
+ }
+
+* get names of variables
+ _perhs
+ local nvars = `r(nrhs)' + 1
+ local varnms "`e(depvar)' `r(rhsnms)'"
+ * get variables in 2nd eq for zip and zinb
+ if "`two'"=="two" {
+ local nvars = `r(nrhs2)' + 1
+ local varnms "`e(depvar)' `r(rhsnms2)'"
+ }
+ * intreg has two lhs vars; select only 1st one
+ if "`e(cmd)'"=="intreg" {
+ local nmtoget : word 1 of `varnms'
+ local varnms "`nmtoget' `r(rhsnms)'"
+ }
+
+* Matrices for results
+ tempname Smean Ssd Smin Smax Sdummy Smedian SN
+ mat `Smean' = J(1,`nvars',-99999)
+ mat colnames `Smean' = `varnms'
+ mat `Ssd' = `Smean'
+ mat `Smin' = `Smean'
+ mat `Smax' = `Smean'
+ mat `Sdummy' = `Smean'
+ mat `Smedian' = `Smean'
+
+* loop through variables
+ local i = 1
+ while `i'<=`nvars' {
+ local nmtoget : word `i' of `varnms'
+ quietly sum `nmtoget' `wtis' `if' `in'
+ scalar `SN' = r(N)
+ if `SN' == 0 {
+ * selection criteria left no observations
+ return scalar SN = `SN'
+ exit
+ }
+ mat `Smean'[1,`i'] = r(mean)
+ mat `Ssd'[1,`i'] = sqrt(r(Var))
+ mat `Smin'[1,`i'] = r(min)
+ mat `Smax'[1,`i'] = r(max)
+ if "`dummy'"=="dummy" {
+ * doesn't need weights. Won't change if is dummy
+ _pedum `nmtoget' `if' `in'
+ mat `Sdummy'[1,`i'] = r(dummy)
+ }
+ if "`median'"=="median" {
+ quietly _pctile `nmtoget' `if' `in' `wtis'
+ mat `Smedian'[1,`i'] = r(r1)
+ }
+ local i=`i'+1
+ }
+
+ return matrix Smean `Smean'
+ return matrix Ssd `Ssd'
+ return matrix Smin `Smin'
+ return matrix Smax `Smax'
+ return matrix Sdummy `Sdummy'
+ return matrix Smedian `Smedian'
+ return scalar SN = `SN'
+
+end
diff --git a/Modules/ado/plus/_/_pesum.hlp b/Modules/ado/plus/_/_pesum.hlp
new file mode 100644
index 0000000..13380a3
--- /dev/null
+++ b/Modules/ado/plus/_/_pesum.hlp
@@ -0,0 +1,66 @@
+.-
+help for ^_pesum^ - 1.6.1 - 1/20/00
+.-
+
+Utility to get descriptive statistics for variables in a regression model
+-------------------------------------------------------------------------
+
+ ^_pesum^ [^if^ exp] [^in^ range] [,^m^edian ^d^ummy ^t^wo]
+
+
+Description
+-----------
+
+^_pesum^ gets the mean, standard deviation, minimum and maximum for the
+ variables in a regression. Optionally, it determines the medians and
+ whether the variables are 0|1|. . Matrices are returned with the first
+ column containing statistics for the dependent variables, with the
+ remaining columns containing information for the independent variables.
+
+Note: ^_pesum^ assumes that ^_peife^ has been applied to the ^if^
+ condition.
+
+Options
+-------
+
+^median^ Return ^r(Smedian)^ with medians for the variables.
+
+^dummy^ Return ^r(Sdummy)^ with medians for the variables.
+
+^two^ Return summary statistics for the second equation in for ^zip^ and
+ ^zinb^ models.
+
+Returned Results
+----------------
+
+Matrices: Colums are in the order dependent variable, independent variables.
+
+ ^r(Smean)^ - means
+ ^r(Ssd)^ - standard deviations
+ ^r(Smin)^ & ^r(Smax)^ - minimums and maximums
+ ^r(Sdummy)^ - 1 if dummy variable, else 0; if ^dummy^ option
+ is specified.
+ ^r(Smedian)^ - medians if ^median^ option is specified.
+
+Scalars: ^r(SN) - sample size
+
+Example with a Program
+-----------------------
+
+ if "`opt'"=="mean"|"`opt'"=="min"|"`opt'"=="max" {
+ _pesum `if' `in',`all'
+ mat pe_base = r(S`opt')
+ }
+ else if "`opt'"=="median" {
+ _pesum `if' `in',median `all'
+ mat pe_base = r(Smedian)
+ }
+
+Also see
+--------
+On-line: help for ^_peife^, ^_perhs^
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
diff --git a/Modules/ado/plus/_/_petrap.ado b/Modules/ado/plus/_/_petrap.ado
new file mode 100644
index 0000000..2e0e9f9
--- /dev/null
+++ b/Modules/ado/plus/_/_petrap.ado
@@ -0,0 +1,79 @@
+*! 1.0.0 - 28 jun 2006
+
+/*
+
+cmd() - name of command that should appear in error message
+
+force - ignore errors
+
+robust - error if robust standard errors used
+cluster - error if cluster() specified
+weight - error if pweight, aweight, iweight specified
+pweight - error if pweight specified
+aweight - error if aweight specified
+iweight - error if iweight specified
+
+*/
+
+program define _petrap
+
+ version 9
+
+ syntax [, cmd(string) Robust Cluster Weight PWeight AWeight IWeight SVY FORCE]
+
+ if "`cmd'" == "" {
+ local cmd "program"
+ }
+
+ local vcetype = e(vcetype)
+ local clustvar = e(clustvar)
+ local wtype = e(wtype)
+ local ecmd = e(cmd)
+ local epredict = e(predict)
+
+
+ * trap svy - possibly overkill for detecting if svy estimation performed but manuals obscure
+ * about info provided under version control
+ if ("`svyest'" == "svy_est" | substr("`ecmd'", 1, 3) == "svy" | substr("`epredict'", 1, 3) == "svy") ///
+ & "`svy'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work with svy commands"
+ }
+
+ * trap robust
+ if "`vcetype'" == "Robust" & "`robust'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work with robust vcetype"
+ exit 999
+ }
+
+ * trap cluster
+ if ("`clustvar'" != "." & "`clustvar'" != "") & "`cluster'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work if cluster() specified"
+ exit 999
+ }
+
+ * trap pweight, iweight, aweight
+ if ("`wtype'" == "pweight" | "`wtype'" == "aweight" | "`wtype'" == "iweight") & "`weight'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work if `wtype' specified"
+ exit 999
+ }
+
+ * trap pweight
+ if ("`wtype'" == "pweight") & "`pweight'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work if `wtype' specified"
+ exit 999
+ }
+
+ * trap aweight
+ if ("`wtype'" == "aweight") & "`aweight'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work if `wtype' specified"
+ exit 999
+ }
+
+ * trap iweight
+ if ("`wtype'" == "iweight") & "`iweight'" != "" & "`force'" == "" {
+ di as err "`cmd' does not work if `wtype' specified"
+ exit 999
+ }
+
+
+end
diff --git a/Modules/ado/plus/_/_petrap.hlp b/Modules/ado/plus/_/_petrap.hlp
new file mode 100644
index 0000000..1cb739c
--- /dev/null
+++ b/Modules/ado/plus/_/_petrap.hlp
@@ -0,0 +1,42 @@
+.-
+help for ^_petrap^ - 28 Jun 2006
+.-
+
+Check to see if model estimation incompatible with postestimation command
+-------------------------------------------------------------------------
+
+ ^_petrap^ [,^cmd^(string) ^svy^ ^r^obust ^c^luster ^w^eight ^pw^eight
+ ^iw^eight ^aw^eight ^force^ ]
+
+
+Description
+-----------
+
+^_petrap^ produces an error message if the previous model estimated uses
+ any of the specified options. It is intended to use for trapping
+ errors in models incompatible with estimation command.
+
+Options
+-------
+
+^cmd()^ name of command that should appear in error message. if not
+ specified, then "program" is used
+
+^force^ will ignore conditions, and thus return with no errors
+
+^robust^ exits with error if robust standard errors used in estimated model
+
+^cluster^ exits with error if cluster() specified
+
+^weight^ exits with error if pweight, aweight, or iweight specified
+
+^pweight^ exits with error if pweight specified
+
+^aweight^ exits with error if aweight specified
+
+^iweight^ exits with error if iweight specified
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
diff --git a/Modules/ado/plus/_/_peunvec.ado b/Modules/ado/plus/_/_peunvec.ado
new file mode 100644
index 0000000..895ffc4
--- /dev/null
+++ b/Modules/ado/plus/_/_peunvec.ado
@@ -0,0 +1,22 @@
+*! version 1.6.1 1/18/03
+
+capture program drop _peunvec
+program define _peunvec, rclass
+version 7
+ tempname oldbeta newbeta newrow
+ mat `oldbeta' = e(b)
+ _perhs
+ local cols = `r(nrhs)'+1
+ local rows = colsof(`oldbeta')/`cols'
+ local i = 1
+ while `i' <= `rows' {
+ local start = ((`i'-1) * `cols') + 1
+ local end = `start' + `cols' - 1
+ mat `newrow' = `oldbeta'[1, `start'..`end']
+ mat `newbeta' = nullmat(`newbeta') \ `newrow'
+ local i = `i' + 1
+ }
+ mat coleq `newbeta' = _
+ mat list `newbeta'
+ return matrix b `newbeta'
+end
diff --git a/Modules/ado/plus/_/_peunvec.hlp b/Modules/ado/plus/_/_peunvec.hlp
new file mode 100644
index 0000000..2d54780
--- /dev/null
+++ b/Modules/ado/plus/_/_peunvec.hlp
@@ -0,0 +1,17 @@
+.-
+help for ^_peunvec^
+.-
+
+ ^_peunvec^
+
+^_peunvec^ takes regression estimates that are kept as a vector (like ^mlogit^
+results in Stata 6) and transforms them to a matrix (like ^mlogit^ results in
+Stata 5).
+
+The input is taken from e(b), and the new matrix is saved as r(b).
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
diff --git a/Modules/ado/plus/_/_pexstring.ado b/Modules/ado/plus/_/_pexstring.ado
new file mode 100644
index 0000000..88428a8
--- /dev/null
+++ b/Modules/ado/plus/_/_pexstring.ado
@@ -0,0 +1,18 @@
+*! version 0.2.1 2005Jun20 - fix for long string jf
+* version 0.2.0 2005-02-03
+
+// change values in PE_in to string x(a=1 b=2..)
+
+capture program drop _pexstring
+program _pexstring, rclass
+ version 8
+ local cols = colsof(PE_in)
+ local xnames : colnames PE_in
+ local xis ""
+ foreach c of numlist 1/`cols' {
+ local xnm : word `c' of `xnames'
+ local xval = PE_in[1,`c']
+ local xis "`xis' `xnm'=`xval'"
+ }
+ return local xis "`xis'"
+end
diff --git a/Modules/ado/plus/a/adoedit.ado b/Modules/ado/plus/a/adoedit.ado
new file mode 100644
index 0000000..2ed9712
--- /dev/null
+++ b/Modules/ado/plus/a/adoedit.ado
@@ -0,0 +1,77 @@
+
+*! Dan Blanchette 1.1 dan.blanchette@duke.edu 08Feb2005
+*! Center of Entrepreneurship and Innovation Duke University's Fuqua School of Business
+** research computing, unc-ch
+* Stata fixed Linux problem of not being able to edit a file in a directory starting with "~"
+* Added "Caution" note when requesting to edit a Stata ado file.
+** Dan Blanchette 1.0.3 06 Nov 2003 made it work in Linux
+*! NJC 1.0.2 31 Dec 2002
+** CFB 1.0.1 26Dec2002 cloned from adotype
+* NJC 1.2.1 1 December 1999
+** NJC 1.2.2 6 December 1999
+* NJC 1.2.3 14 December 1999
+** AJM 1.3 5 August 2009 (Eliminated file size check for versions 11 and greater.)
+
+program def adoedit, rclass
+ version 8.0
+
+
+ if "`1'" == "" | "`2'" != "" {
+ di as err "incorrect syntax"
+ exit 198
+ }
+ args cmd
+
+ /* ends with .ado */
+ if substr(`"`cmd'"',length(`"`cmd'"')-3,length(`"`cmd'"'))==".ado" {
+ local filen `"`cmd'"'
+ }
+ else {
+ local filen `"`cmd'.ado"'
+ }
+
+ findfile `filen'
+
+ // here will exit 601 if `cmd' not found
+
+ local file `"`r(fn)'"'
+
+ local tfile : subinstr local file "\" "/" , all
+
+ if index(`"`tfile'"',"/ado/base") | index(`"`tfile'"',"/ado/updates") {
+ di " "
+ di as err "Caution, you are requesting to edit an ado file provided by Stata."
+ di as err "If this is really what you want, consider first copying the file to {input}`: sysdir PERSONAL' {error}."
+ di " "
+ more
+ di " "
+ }
+
+ capture hexdump `"`file'"', analyze
+ local size = r(filesize)
+
+ * Eliminates file size check for versions 11 and greater.
+ if c(stata_version) < 11 {
+
+ if `size' < 32000 & `size' > 0 {
+ doedit `"`file'"'
+ discard
+ return local adofile `"`file'"'
+ exit 0
+ }
+ else {
+ di as txt _n "Sorry, files larger than 32,000 bytes cannot be do-edited."
+ di as txt "You must use another text editor for this file."
+ error 603
+ }
+ }
+
+ else if c(stata_version) >= 11 {
+ doedit `"`file'"'
+ discard
+ return local adofile `"`file'"'
+ exit 0
+ }
+
+end
+
diff --git a/Modules/ado/plus/a/adoedit.hlp b/Modules/ado/plus/a/adoedit.hlp
new file mode 100644
index 0000000..cb23827
--- /dev/null
+++ b/Modules/ado/plus/a/adoedit.hlp
@@ -0,0 +1,87 @@
+{smcl}
+{* 5Aug2009}{...}
+{* 17Jan2008}{...}
+{* 06Nov2003}{...}
+{hline}
+help for {hi:adoedit} {right:manual: {hi:[R] none}}
+{right:dialog: {hi: none} }
+{hline}
+
+
+{title:Edit ado-file in Stata's do-file editor}
+
+{p 8 17 2}{cmd:adoedit}
+{it:cmdname}
+{p_end}
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:adoedit} attempts to edit whichever ado-file named {cmd:cmdname.ado} is first on the
+current {help adopath:adopath}. In Stata Version 10 and earlier, one cannot edit files
+larger than 32,000 bytes in the do-file editor, nor can one edit built-in commands.
+The file size limitation is removed for Stata Version 11 and later.
+
+{p 4 4 2}
+This routine is designed for use by those who are writing their own ado-files;
+users are exhorted to make a copy of any official ado-files, and to save modified official
+ado-files in the ado directory, rather than the Stata directory.{p_end}
+
+{p 4 4 2}
+{cmd:adoedit cmdname.ado}
+is tolerated.{p_end}
+
+{p 4 4 2}
+After a successful edit, the {cmd:discard} command is issued so that Stata will load the
+revised ado-file. This will also clear any estimates from the last estimation.{p_end}
+
+{p 4 4 2}
+If you wish to edit ado-files with a different text editor, please see
+{stata findit fedit:fedit} and the {stata findit texteditors:texteditors} modules on the
+{help ssc:SSC} archive.{p_end}
+
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. adoedit tsspell}{p_end}
+
+
+{title:Saved Results}
+
+{p 4 8 2}
+The {cmd:adoedit} command saves in {cmd:r()}:{p_end}
+
+{synoptset 20 tabbed}{...}
+{p2col 5 20 24 2: Macros}{p_end}
+{synopt:{cmd:r(adofile)}}the ado-file name and full path{p_end}
+
+
+{title:Author}
+
+{p 4 4 2}
+Dan Blanchette {break}
+Center of Entrepreneurship and Innovation {break}
+Duke University's Fuqua School of Business {break}
+Dan.Blanchette@Duke.edu{p_end}
+
+
+{title:Acknowledgements}
+
+{p 4 4 2}
+This program grew out of previous work by:{p_end}
+
+{p 6 4 2}
+Nicholas J. Cox, University of Durham, U.K.{p_end}
+
+{p 4 4 2}
+and{p_end}
+
+{p 6 4 2}
+Christopher F Baum, Boston College, USA{p_end}
+
+
+{title:Also see}
+
+{p 4 13 2}On-line: {help doedit:doedit} {help fildfile:findfile},
+{help fedit:fedit} (if installed){p_end}
+
diff --git a/Modules/ado/plus/a/alphlist.ado b/Modules/ado/plus/a/alphlist.ado
new file mode 100644
index 0000000..2f892b0
--- /dev/null
+++ b/Modules/ado/plus/a/alphlist.ado
@@ -0,0 +1,23 @@
+program def alphlist, rclass
+*! NJC 1.1.1 28 June 2001
+* NJC 1.1.0 6 June 2000
+* NJC 1.0.0 27 Jan 2000
+ version 6.0
+ syntax , [ Capitals Underscore Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ if "`capitals'" != "" {
+ local newlist "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"
+ }
+ else local newlist "a b c d e f g h i j k l m n o p q r s t u v w x y z"
+
+ if "`underscore'" != "" { local newlist "`newlist' _" }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
diff --git a/Modules/ado/plus/a/alphlist.hlp b/Modules/ado/plus/a/alphlist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/a/alphlist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/a/anaoption.ado b/Modules/ado/plus/a/anaoption.ado
new file mode 100644
index 0000000..46e436a
--- /dev/null
+++ b/Modules/ado/plus/a/anaoption.ado
@@ -0,0 +1,48 @@
+*! version 1 27may2007
+*! Jean-Benoit Hardouin
+*
+************************************************************************************************************
+* Stata program : anaoption
+*
+* Historic
+* Version 1 (2007-05-27): Jean-Benoit Hardouin
+*
+* Jean-benoit Hardouin, phD, Assistant Professor
+* Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences
+* University of Nantes - Faculty of Pharmaceutical Sciences
+* France
+* jean-benoit.hardouin@anaqol.org
+*
+* News about this program :http://www.anaqol.org
+* FreeIRT Project website : http://www.freeirt.org
+*
+* Copyright 2007 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 anaoption ,rclas
+version 7.0
+syntax [, DETails minvi(real .03) siglevel(real 0.05) minsize(real 0)]
+
+return scalar minvi=`minvi'
+return scalar siglevel=`siglevel'
+return scalar minsize=`minsize'
+return local details `details'
+
+
+end
+
diff --git a/Modules/ado/plus/a/asprvalue.ado b/Modules/ado/plus/a/asprvalue.ado
new file mode 100644
index 0000000..1b8f7ce
--- /dev/null
+++ b/Modules/ado/plus/a/asprvalue.ado
@@ -0,0 +1,697 @@
+*! 0.3.2 2009-03-14 | long freese | fix mean calculation
+
+** predictions for asmprobit
+
+capture program drop asprvalue
+capture program drop _Prvasmp
+program define asprvalue, rclass
+
+version 9
+
+ if e(cmd) == "asmprobit" {
+ _Prvasmp `0' // local program just for asmprobit -- see below
+ return add
+ exit
+ }
+
+ preserve
+
+ syntax [, x(passthru) Cat(string) Base(string) Save Diff Rest(string) BRief Full]
+
+ * need to sort to calculate means below so accurate for unbalanced panels
+ local idvar "`e(group)'"
+ tempname recordnum
+ sort `idvar', stable
+ by `idvar' : gen `recordnum' = _n
+
+ tempname b
+ mat `b' = e(b)
+ local allnames : colnames `b'
+
+ * check if there are any interactions, so that otherwise warning message can be specified
+ local anyX "no"
+
+ * make list of case-specific variables
+ foreach var of local allnames {
+ local i = index("`var'", "X")
+ if `i' != 0 {
+ local anyX "yes"
+ * is it an alternativeXcase-specific-variable interaction?
+ local temppreX = substr("`var'", 1, `i'-1)
+ local temppostX = substr("`var'", `i'+1, .)
+ * assume that preX are all cats -- TO DO: insert check?
+ local catslist "`catslist' `temppreX'"
+ local isAxA "no"
+ foreach var2 of local allnames {
+ if "`temppostX'"=="`var2'" | "`temppostX'"=="`base'" {
+ local isAxA "yes"
+ local aXalist "`aXalist' `var'"
+ }
+ }
+ * is it an alternativeXalternative interaction?
+ if "`isAxA'" == "no" {
+ local aXclist "`aXclist' `var'"
+ local csvlist "`csvlist' `temppostX'"
+ }
+ }
+ }
+
+
+ * if cat is specified, that is the list of categories
+ if "`cat'"!= "" {
+ local catslist = "`cat'"
+ }
+
+ * make sure either cat() or interactions specified
+ if "`cat'"=="" & "`anyX'"=="no" {
+ di as err "cat() must be specified if no interactions in model"
+ error 999
+ }
+
+ local catslist : list uniq catslist
+ local ncatsmin1 : word count `catslist'
+ local numcats = `ncatsmin1' + 1
+ local csvlist : list uniq csvlist
+
+ local asvlist : list allnames - aXclist
+ local asvlist : list asvlist - catslist
+ local asvlist : list asvlist - aXalist
+
+ /*
+ di "altXasv interactions: `aXalist'"
+ di "altXcase interactions: `aXclist'"
+ di "alternatives: `catslist'"
+ di "altspec vars: `asvlist'"
+ di "casespec vars: `csvlist'"
+ di "number of alternatives `ncatsmin1'"
+ */
+
+ * decode x() values
+ tokenize `x', parse("()")
+ local x "`3'"
+ local x : subinstr local x "=" " ", all
+ tokenize `x', parse(" ")
+ while "`1'" != "" & "`2'" != "" {
+
+ capture confirm number `3'
+ if _rc == 0 {
+ * TO DO: check that `1' is alternative-specific variables
+ forvalues i = 1(1)`numcats' {
+ local iplus1 = `i' + 1
+ confirm number ``iplus1''
+ local V`1'V`i' = ``iplus1''
+ }
+ macro shift `iplus1'
+ }
+
+ else {
+ local V`1' = `2'
+ macro shift 2
+ }
+ }
+
+ * HANDLE REST OPTION
+
+ * rest() = mean by default
+ if "`rest'" == "" {
+ local rest "mean"
+ }
+ *check that rest option includes an allowable option
+ if "`rest'" != "mean" & "`rest'" != "asmean" {
+ di as err "rest(`rest') not allowed"
+ error 999
+ }
+
+ foreach var of local csvlist {
+ if "`V`var''" == "" {
+ if "`rest'" == "mean" | "`rest'" == "asmean" {
+* qui su `var' if e(sample) == 1 & `recordnum' == 1
+ qui su `var' if e(sample) == 1 // FIX TO MEAN CALCULATION 9/2012
+ local V`var' = r(mean)
+ }
+ }
+ }
+
+ foreach var of local asvlist {
+ if "`V`var''" == "" & "`V`var'V1'" == "" {
+ if "`rest'" == "mean" {
+* qui su `var' if e(sample) == 1 & `recordnum' == 1
+ qui su `var' if e(sample) == 1 // FIX TO MEAN CALCULATION 9/2012
+ forvalues i = 1(1)`numcats' {
+ local V`var'V`i' = r(mean)
+ }
+ }
+ if "`rest'" == "asmean" {
+ tempname refdum
+ * this variable will equal 1 for only those cases that indicate base
+ qui gen `refdum' = 1 if e(sample) == 1
+ local i = 1
+ foreach catname of local catslist {
+ qui su `var' if `catname' == 1 & e(sample) == 1
+ local V`var'V`i' = r(mean)
+ * turn off refdum for variables indicating category
+ qui replace `refdum' = 0 if `catname' == 1 & e(sample) == 1
+ local i = `i' + 1
+ }
+ * use refdum to get mean for reference category
+ qui su `var' if `refdum' == 1 & e(sample) == 1
+ local V`var'V`i' = r(mean)
+ }
+ }
+ }
+
+ * add observations to bottom of dataset
+
+ local N = _N
+ local firstobs = `N' + 1 // firstobs is the reference number of the first added obs
+ local lastobs = `firstobs'+`ncatsmin1'
+
+ qui set obs `lastobs'
+ capture drop _addedobs
+ qui gen _addedobs = 1 if _n >= `firstobs'
+
+ * find unique value for new observations
+ local unique "no"
+ local i = 1234567
+ while "`unique'" == "no" {
+ qui count if `idvar' == `i'
+ if r(N) == 0 {
+ local unique "yes"
+ }
+ local i = `i' + 1234567
+ }
+ qui replace `idvar' = `i' in `firstobs'/`lastobs'
+ qui replace `idvar' = `i' in `firstobs'/`lastobs'
+
+ foreach cat of local catslist {
+ local obs = `firstobs'
+ foreach cat2 of local catslist {
+
+ * set dummy variables indicating which row is which alternative
+ qui replace `cat' = 1 in `obs' if "`cat'" == "`cat2'"
+ qui replace `cat' = 0 in `obs' if "`cat'" != "`cat2'"
+
+ * set values for aXc interactions
+ foreach csvar of local csvlist {
+ qui replace `cat'X`csvar' = `V`csvar'' in `obs' if "`cat'" == "`cat2'"
+ qui replace `cat'X`csvar' = 0 in `obs' if "`cat'" != "`cat2'"
+ }
+
+ local obs = `obs' + 1
+ }
+
+ * set all alternative dummies to zero for row indicating reference category
+ qui replace `cat' = 0 in `obs'
+
+ * set all aXc to zero for row corresponding to reference category
+ foreach csvar of local csvlist {
+ qui replace `cat'X`csvar' = 0 in `obs'
+ }
+
+ }
+
+ * set values for alternative-specific variables
+ foreach alt of local asvlist {
+ if "`V`alt''" != "" {
+ qui replace `alt' = `V`alt'' in `firstobs'/`lastobs'
+ }
+ else {
+ forvalues i = 1(1)`numcats' {
+ local obs = `firstobs' + `i' - 1
+ qui replace `alt' = `V`alt'V`i'' in `obs'
+ }
+ }
+ }
+
+ * set values for aXa interactions
+ foreach var of local aXalist {
+ local i = index("`var'", "X")
+ local temppreX = substr("`var'", 1, `i'-1)
+ local temppostX = substr("`var'", `i'+1, .)
+ qui replace `var' = `temppreX'*`temppostX' if _addedobs == 1
+ }
+
+ * generate predicted probabilities
+ tempname prob
+
+ * 5/26/06 WORKAROUND FOR STATA BUG (?!) WHERE PREDICT RESORTS DATA
+ tempname order
+ gen `order' = _n
+ qui predict `prob' if _addedobs == 1
+ sort `order'
+
+ * reference category name
+ if "`base'" == "" {
+ local base = "base"
+ }
+
+* DISPLAY RESULTS
+* heading
+
+ local ecmd "`e(cmd)'"
+ local edepvar "`e(depvar)'"
+ di _n as res "`ecmd'" as txt ": Predictions for " as res "`edepvar'"
+
+* display predicted probabilities
+
+ local obs = `firstobs'
+ capture mat drop asprvres
+ tempname tmpprob
+
+ foreach cat of local catslist {
+ sca `tmpprob' = `prob'[`obs']
+
+ mat asprvres = (nullmat(asprvres) \ `tmpprob')
+
+ local obs = `obs' + 1
+ }
+ sca `tmpprob' = `prob'[`obs']
+ mat asprvres = (nullmat(asprvres) \ `tmpprob')
+
+ mat rownames asprvres = `catslist' `base'
+ mat colnames asprvres = prob
+
+ if "`diff'" != "" {
+ mat changesav = asprvres - _ASPRVsav
+ tempname display
+ mat `display' = (asprvres, _ASPRVsav, changesav)
+ mat colnames `display' = Current Saved Diff
+ mat list `display', noh
+ }
+ else {
+ mat list asprvres, noh
+ }
+
+* display base values for case-specific variables
+
+ if "`csvlist'" != "" {
+ capture mat drop csvals
+ foreach var of local csvlist {
+ mat csvals = (nullmat(csvals) , `V`var'')
+ }
+ mat colnames csvals = `csvlist'
+ mat rownames csvals = x=
+
+ if "`brief'" == "" {
+ di _n as txt "case-specific variables"
+
+ if "`diff'" != "" {
+ mat changecsv = csvals - _ASPRVcsv
+ tempname displaycsv
+ mat `displaycsv' = (csvals \ _ASPRVcsv \ changecsv)
+ mat rownames `displaycsv' = Current Saved Diff
+ mat list `displaycsv', noh
+ }
+ else {
+ mat list csvals, noh
+ }
+ }
+
+ }
+
+* display base values for alternative-specific variables
+
+ if "`asvlist'" != "" {
+ capture mat drop asvals
+ foreach alt of local asvlist {
+ capture mat drop _tmp
+ if "`V`alt''" != "" {
+ mat _tmp = J(1, `numcats', `V`alt'')
+ }
+ else {
+ forvalues i = 1(1)`numcats' {
+ mat _tmp = (nullmat(_tmp) , `V`alt'V`i'')
+ }
+ }
+ mat asvals = (nullmat(asvals) \ _tmp)
+ }
+ mat rownames asvals = `asvlist'
+ mat colnames asvals = `catslist' `base'
+
+ if "`brief'" == "" {
+ di _n as txt "alternative-specific variables"
+
+ if "`diff'" != "" {
+
+ tempname curasv
+ mat `curasv' = asvals
+
+ tempname savedasv
+ mat `savedasv' = _ASPRVasv
+ mat changeasv = asvals - `savedasv'
+
+ mat roweq `curasv' = Current
+ mat roweq `savedasv' = Saved
+ mat roweq changeasv = Dif
+
+ tempname displayasv
+ mat `displayasv' = (`curasv' \ `savedasv' \ changeasv)
+ mat list `displayasv', noh
+ }
+ else {
+ mat list asvals, noh
+ }
+ }
+ }
+
+* display all added observations and values if desired
+
+ if "`full'" != "" {
+ list `allnames' if _addedobs == 1, noobs
+ }
+
+ if "`save'" != "" {
+ mat _ASPRVsav = asprvres
+ if "`csvlist'" != "" {
+ mat _ASPRVcsv = csvals
+ }
+ if "`asvlist'" != "" {
+ mat _ASPRVasv = asvals
+ }
+ }
+
+* return results
+ if "`diff'" != "" { //! added bj 24jul2008
+ capture return matrix p = changesav, copy //!
+ capture return matrix csv = changecsv, copy //!
+ capture return matrix asv = changeasv, copy //!
+ } //!
+ else { //!
+ capture return matrix p = asprvres, copy
+ capture return matrix csv = csvals, copy
+ capture return matrix asv = asvals, copy
+ } //!
+
+restore
+
+end
+
+program define _Prvasmp, rclass
+
+version 9
+
+preserve
+
+ syntax [, x(passthru) Cat(string) Base(string) Save Diff Rest(string) BRief Full]
+
+ if "`cat'" != "" {
+ di as err "(note: cat() ignored when using asprvalue with asmprobit)"
+ }
+ if "`base'" != "" {
+ di as err "(note: base() ignored when using asprvalue with asmprobit)"
+ }
+
+ local altvar = e(altvar)
+
+ local numcats = e(k_alt)
+ local asvlist "`e(indvars)'"
+ local csvlist "`e(ind2vars)'"
+ if "`csvlist'" == "" {
+ local csvlist "`e(casevars)'"
+ }
+ local idvar "`e(casevar)'"
+ if "`idvar'" == "" {
+ local idvar "`e(case)'"
+ }
+
+ * need to sort to calculate means below so accurate for unbalanced panels
+ tempname recordnum
+ sort `idvar', stable
+ by `idvar' : gen `recordnum' = _n
+
+
+ * add values to bottom of dataset
+
+ local N = _N
+ local firstobs = `N' + 1
+ local lastobs = `firstobs' + `numcats' - 1
+
+ qui set obs `lastobs'
+ capture drop _addedobs
+ qui gen _addedobs = 1 if _n >= `firstobs'
+
+ * find unique value for new observations
+ local unique "no"
+ local i = 1234567
+ while "`unique'" == "no" {
+ qui count if `idvar' == `i'
+ if r(N) == 0 {
+ local unique "yes"
+ }
+ local i = `i' + 1234567
+ }
+ qui replace `idvar' = `i' in `firstobs'/`lastobs'
+
+ * write values for alternative variable with values of alternatives
+ _pecats `altvar' if e(sample)
+
+ local catvals "`r(catvals)'"
+ forvalues i = 1(1)`numcats' {
+ local cat`i' : word `i' of `catvals'
+ local catslist "`catslist' `e(alt`i')'"
+
+ local obsnum = `firstobs' + `i' - 1
+ qui replace `altvar' = `cat`i'' in `obsnum'
+ }
+
+ * decode x() values
+ tokenize `x', parse("()")
+ local x "`3'"
+ local x : subinstr local x "=" " ", all
+ tokenize `x', parse(" ")
+ while "`1'" != "" & "`2'" != "" {
+
+ * if `3' exists and is a number, alternative-specific variables being specified
+ capture confirm number `3'
+ if _rc == 0 {
+ * TO DO: check that `1' is alternative-specific variable
+ forvalues i = 1(1)`numcats' {
+ local iplus1 = `i' + 1
+ confirm number ``iplus1''
+ local V`1'V`i' = ``iplus1''
+ }
+ macro shift `iplus1'
+ }
+
+ else {
+ local V`1' = `2'
+ macro shift 2
+ }
+ }
+
+ * HANDLE REST OPTION
+
+ * rest() = mean by default
+ if "`rest'" == "" {
+ local rest "mean"
+ }
+ *check that rest option includes an allowable option
+ if "`rest'" != "mean" & "`rest'" != "asmean" {
+ di as err "rest(`rest') not allowed"
+ error 999
+ }
+
+ foreach var of local csvlist {
+ if "`V`var''" == "" {
+ if "`rest'" == "mean" | "`rest'" == "asmean" {
+* qui su `var' if e(sample) == 1 & `recordnum' == 1
+ qui su `var' if e(sample) == 1 // FIX TO MEAN CALCULATION 9/2012
+ local V`var' = r(mean)
+ }
+ }
+ }
+
+ foreach var of local asvlist {
+ if "`V`var''" == "" & "`V`var'V1'" == "" {
+ if "`rest'" == "mean" {
+* qui su `var' if e(sample) == 1 & `recordnum' == 1
+ qui su `var' if e(sample) == 1 // FIX TO MEAN CALCULATION 9/2012
+ forvalues i = 1(1)`numcats' {
+ local V`var'V`i' = r(mean)
+ }
+ }
+ if "`rest'" == "asmean" {
+ forvalues i = 1(1)`numcats' {
+ qui su `var' if `altvar' == `cat`i'' & e(sample) == 1
+ local V`var'V`i' = r(mean)
+ }
+ }
+ }
+ }
+
+ * set values for alternative-specific variables
+ foreach alt of local asvlist {
+ if "`V`alt''" != "" {
+ qui replace `alt' = `V`alt'' in `firstobs'/`lastobs'
+ }
+ else {
+ forvalues i = 1(1)`numcats' {
+ local obs = `firstobs' + `i' - 1
+ qui replace `alt' = `V`alt'V`i'' in `obs'
+ }
+ }
+ }
+
+ * set values for case-specific variables
+ foreach var of local csvlist {
+ qui replace `var' = `V`var'' in `firstobs'/`lastobs'
+ }
+
+ * generate predicted probabilities
+ tempname prob
+
+** 5/26/06 WORKAROUND FOR STATA BUG (?!) WHERE PREDICT RESORTS DATA
+ tempname order
+ gen `order' = _n
+ * 2008-06-15 list `order' if _addedobs == 1
+ qui predict `prob' if _addedobs == 1
+ sort `order'
+
+* DISPLAY RESULTS -- whole routine almost the same as asprvalue but not quite
+
+* heading
+
+ local ecmd "`e(cmd)'"
+ local edepvar "`e(depvar)'"
+ di _n as res "`ecmd'" as txt ": Predictions for " as res "`edepvar'"
+
+* display predicted probabilities
+
+ local obs = `firstobs'
+ capture mat drop asprvres
+ tempname tmpprob
+ foreach cat of local catslist {
+ sca `tmpprob' = `prob'[`obs']
+
+ mat asprvres = (nullmat(asprvres) \ `tmpprob')
+
+ local obs = `obs' + 1
+ }
+
+ mat rownames asprvres = `catslist'
+ mat colnames asprvres = prob
+
+ if "`diff'" != "" {
+ mat changesav = asprvres - _ASPRVsav
+ tempname display
+ mat `display' = (asprvres, _ASPRVsav, changesav)
+ mat colnames `display' = Current Saved Diff
+ mat list `display', noh
+ }
+ else {
+ mat list asprvres, noh
+ }
+
+* display base values for case-specific variables
+
+ if "`csvlist'" != "" {
+ capture mat drop csvals
+ foreach var of local csvlist {
+ mat csvals = (nullmat(csvals) , `V`var'')
+ }
+ mat colnames csvals = `csvlist'
+ mat rownames csvals = x=
+
+ if "`brief'" == "" {
+ di _n as txt "case-specific variables"
+
+ if "`diff'" != "" {
+ mat changecsv = csvals - _ASPRVcsv
+ tempname displaycsv
+ mat `displaycsv' = (csvals \ _ASPRVcsv \ changecsv)
+ mat rownames `displaycsv' = Current Saved Diff
+ mat list `displaycsv', noh
+ }
+ else {
+ mat list csvals, noh
+ }
+ }
+ }
+
+* display base values for alternative-specific variables
+
+ if "`asvlist'" != "" {
+ capture mat drop asvals
+ foreach alt of local asvlist {
+ capture mat drop _tmp
+ if "`V`alt''" != "" {
+ mat _tmp = J(1, `numcats', `V`alt'')
+ }
+ else {
+ forvalues i = 1(1)`numcats' {
+ mat _tmp = (nullmat(_tmp) , `V`alt'V`i'')
+ }
+ }
+ mat asvals = (nullmat(asvals) \ _tmp)
+ }
+ mat rownames asvals = `asvlist'
+ mat colnames asvals = `catslist'
+
+ if "`brief'" == "" {
+ di _n as txt "alternative-specific variables"
+
+ if "`diff'" != "" {
+
+ tempname curasv
+ mat `curasv' = asvals
+
+ tempname savedasv
+ mat `savedasv' = _ASPRVasv
+ mat changeasv = asvals - `savedasv'
+
+ mat roweq `curasv' = Current
+ mat roweq `savedasv' = Saved
+ mat roweq changeasv = Dif
+
+ tempname displayasv
+ mat `displayasv' = (`curasv' \ `savedasv' \ changeasv)
+ mat list `displayasv', noh
+ }
+ else {
+ mat list asvals, noh
+ }
+ }
+ }
+
+* display all added observations and values if desired
+
+ if "`full'" != "" {
+ list `allnames' if _addedobs == 1, noobs
+ }
+
+ if "`save'" != "" {
+ mat _ASPRVsav = asprvres
+ if "`csvlist'" != "" {
+ mat _ASPRVcsv = csvals
+ }
+ if "`asvlist'" != "" {
+ mat _ASPRVasv = asvals
+ }
+ }
+
+* return results
+capture return matrix p = asprvres, copy
+capture return matrix csv = csvals, copy
+capture return matrix asv = asvals, copy
+
+restore
+
+end
+
+exit
+
+* 0.2.0 - jf - 5/26/06 - workaround for bug in Stata where predict resorts
+* 0.1.9 - jf - 12/19/05 - add returns
+* 0.1.8 - jf - 9/8/05 - warning but not error with cat() or base() with asmprobit
+* 0.1.7 - jf - 7/24/05 - fix asmean for asmprobit bug
+* 0.1.6 - jf - 7/19/05 - add heading to output
+* 0.1.5 - jf - 7/18/05 - bug fix
+* 0.1.4 - jf - 7/15/05 - add asmprobit (kludgy) - jf
+* 0.1.3 - jf - 7/15/05 - fix to allow = in x()
+* 0.1.2 - jf - 7/11/05 - bug fix
+* 0.1.1 - jf - 6/15/05 - change refcat() to base()
+* 0.1.0 - jf - 6/11/05
+* 0.2.1 - jf - 7/2/07 - fix for changes in stata 7 asmprobit routine
+* 0.3.0a - bj 24jul2008 for work with estout
+* 0.3.0 2008-06-15 jsl
+* 0.3.1 2009-03-14
diff --git a/Modules/ado/plus/a/asprvalue.hlp b/Modules/ado/plus/a/asprvalue.hlp
new file mode 100644
index 0000000..2b3a827
--- /dev/null
+++ b/Modules/ado/plus/a/asprvalue.hlp
@@ -0,0 +1,122 @@
+{smcl}
+{* 03Nov2005}{...}
+{hline}
+help for {hi:asprvalue}{right:03Nov2005}
+{hline}
+
+{title:Predicted probabilities for models with alternative-specific variables}
+
+{p 8 15 2}{cmd:asprvalue} [{cmd:,}
+{cmd:x(}{it:variables_and_values}{cmd:)}
+{cmdab:r:est(}{it:stat}{cmd:)}
+{cmdab:b:ase(}{it:refcatname}{cmd:)}
+{cmdab:c:at(}{it:catnames}{cmd:)}
+{cmdab:s:ave}
+{cmdab:d:iff}
+{cmdab:br:ief}
+
+{p 4 4 2}
+where {it:variables_and_values} is an alternating list of variables
+and numeric values
+
+{p 4 4 2}
+{it:stat} is either mean or asmean (alternative-specific means for alternative-specific variables)
+
+{p 4 4 2}
+{cmd:asprvalue} is intended to be used to compute predicted probabilities for logit or probit models
+that can combine case- and alternative-specific variables. For these models, predicted probabilities
+depend on the values of the independent variables, which may or may not vary over the alternatives for
+a particular case. {cmd:asprvalue} allows you to specify the values of the independent variables and
+presents predicted probabilities for the different alternatives. The command presently works after
+{helpb clogit}, {helpb rologit}, or {helpb asmprobit}.
+
+{p 4 4 2}
+{cmd:IMPORTANT:} For {helpb clogit} and {helpb rologit} models, case-specific variables are specified
+by a set of interactions with dummy variables for the alternatives. {cmd:asprvalue} can only be used
+if these interaction variables are named {it:alternative_name}X{it:case_specific_varname}. In other
+words, if the dummy variables for the alternatives are named "car" and "bus" and a case-specific
+variable is "male", the interactions must be named "carXmale" and "busXmale". These names for the
+interactions correspond with the names used if the data have been arranged for estimation using
+the command {cmd:case2choice}. A capital "X" cannot be used in the names of any of the other
+variables in the model.
+
+{title:Options}
+
+{p 4 8 2}
+{cmd:save} saves current values of indepenent variables and predictions
+for computing changes using the diff option.
+
+{p 4 8 2}
+{cmd:diff} computes difference between current predictions and those
+that were saved.
+
+{p 4 8 2}
+{cmd:x()} sets the values of independent variables for calculating
+predicted values. For case-specific variables, the list must alternate
+variable names and values. For alternative-specific variables, the list
+may either be followed by a single value to be assigned to all alternatives
+or J values if there are J alternatives. For {helpb clogit} or {helpb rologit}
+, when J values are specified, these
+are assigned to the alternatives in the order they have been specified by
+{cmd:cat()} or in the estimation command, with the value to be assigned to the
+reference category being last. For {helpb asmprobit}, the different alternatives are specified
+using a single variable rather than a series of dummy variables, and values for
+alternative-specific variables should be ordered to correspond with the ascending
+values of the variable.
+
+
+{p 4 8 2}
+{cmd:rest()} sets the values for variables unspecified in {cmd:x()}. The default
+is {it:mean}, which holds all unspecified variables to their case-specific means.
+One can also specific "asmean", which holds unspecified alternative-specific
+variables to their alternative-specific means. For example, if "time" was an
+alternative-specific variable, {it:mean} would assign all alternatives the
+mean of "time" over all individuals and alternatives, while {it:asmean} would assign
+each alternative the mean of "time" for that alternative.
+
+{p 4 8 2}
+{cmd:base()} specifies the name of the base (reference) category. If this is not
+specified, "base" will be used to refer to this category in the output. This option
+should not be used after {helpb asmprobit}.
+
+{p 4 8 2}
+{cmd:cat()} specifies the names of the dummy variables in the model used to
+indicate different alternatives (the alternative-specific intercepts). {cmd:cat()} only
+needs to be specified if the model includes no case-specific variables, as otherwise
+this list is inferred from the names of the interaction terms for case-specific
+variables. The name of the reference category should not be included in {cmd:cat()}. This option
+should not be used after {helpb asmprobit}.
+
+{p 4 8 2}
+{cmd:brief} prints only limited output.
+
+{title:Examples}
+
+{p 4 4 2}
+{cmd:. use "http://www.stata-press.com/data/lfr/nomocc2.dta", clear}{break}
+{cmd:. gen busXhinc = bus*hinc}{break}
+{cmd:. gen trainXhinc = train*hinc}{break}
+{cmd:. gen busXpsize = bus*psize}{break}
+{cmd:. gen trainXpsize = train*psize}{break}
+{cmd:. clogit choice train* bus* time invc , group(id)}{break}
+{cmd:. asprvalue, x(time 600 invc 30 hinc 40 psize 0) base(car)}{break}
+
+{p 4 4 2}
+{cmd:. asprvalue, x(psize 0) base(car) save}{break}
+{cmd:. asprvalue, x(psize 1) base(car) dif}{break}
+
+{p 4 4 2}
+{cmd:. asprvalue, x(psize 0) base(car) rest(asmean) save}{break}
+{cmd:. asprvalue, x(psize 1) base(car) rest(asmean) dif}{break}
+
+{p 4 4 2}
+{cmd:. asprvalue, x(time 600 hinc 40 psize 1) base(car) save}{break}
+{cmd:. asprvalue, x(time 700 600 600 hinc 40 psize 1) base(car) dif}{break}
+{cmd:. asprvalue, x(time 600 700 600 hinc 40 psize 1) base(car) dif}{break}
+{cmd:. asprvalue, x(time 600 600 700 hinc 40 psize 1) base(car) dif}{break}
+
+{title:Authors}
+
+ Jeremy Freese and J. Scott Long
+ {browse www.indiana.edu/~jslsoc/spost.htm}
+ spostsup@indiana.edu
diff --git a/Modules/ado/plus/b/bagroup.ado b/Modules/ado/plus/b/bagroup.ado
new file mode 100644
index 0000000..b487941
--- /dev/null
+++ b/Modules/ado/plus/b/bagroup.ado
@@ -0,0 +1,220 @@
+*! bagroup.ado written 8/5/1997 by PTS version 1.2.2 (STB-55: sbe33)
+*! modified Bland-Altman plots for more than two measures
+*! one plot per figure
+*!
+*! Syntax: bagroup varlist if in, rows avlab difflab obs_c
+
+
+* modified 3/8/1998 to allow for larger symbols if there are repetitions
+* modified 7/8/1998 to use all possible pairs, and to allow for ylines
+* modified 11/11/1998 to give n, means, sd of vars in table
+* modified 2/2/2000 to accommodate xlab & ylab options & warn against xlab, ylab without options
+
+set trace off
+
+cap prog drop bagroup
+prog define bagroup
+ local varlist "req ex min(3)"
+ local if "opt"
+ local in "opt"
+ local options "format(str) rows(int 999) XLABel(str) YLABel(str) avlab(str) difflab(str) title(str) saving(str) obs(int 2) listwise text(real 100) *"
+
+ parse "`*'"
+ if index("`options'","xlab") ~= 0 | index("`options'","ylab") ~= 0 {
+ di in red "xlabel and ylabel without values not permitted"
+ exit 198
+ }
+
+
+ tempvar touse
+ mark `touse' `if' `in'
+
+ local nvars : word count `varlist'
+ if "`listwise'" ~= "" {local obs = `nvars'}
+ cap assert `obs' >= 2 & `obs' <= `nvars'
+ if _rc { di in red "obs must be between 2 and the number of variables: " in ye `nvars'
+ exit _rc}
+ tempvar obs_c
+ qui gen `obs_c' = 0
+ parse "`varlist'", parse(" ")
+ while "`1'" ~= "" {
+ qui replace `obs_c' = `obs_c' + (`1' ~= .)
+ mac shift
+ }
+
+ qui replace `touse' = 0 if `obs_c' < `obs'
+
+ if "`format'" == "" { local format "%5.2f" }
+
+ tempvar av diff
+ qui egen `av' = rmean(`varlist') `if' `in'
+ qui gen `diff' = .
+ _table `varlist', av(`av') diff(`diff') touse(`touse') format(`format') obs_c(`obs_c')
+
+ if "`xlabel'" == "" {
+ nicenum xlabel = $xmin $xmax
+ local xlabel "xlabel($xlabel)"
+ global xlabel
+ }
+ else local xlabel "xlabel(`xlabel')"
+
+ if "`ylabel'" == "" {
+ nicenum ylabel = $rrmin $rrmax
+ parse "$ylabel" , parse (",")
+ assert "`2'" == ","
+ if `1' > $rrmin {
+ local ymin = 2*`1' - `3'
+ global ylabel "`ymin',$ylabel"
+ }
+ local ylabel "ylabel($ylabel)"
+ global ylabel
+ }
+ else local ylabel "ylabel(`ylabel')"
+
+ if "`avlab'" ~= "" { local avlab avlab("`avlab'") }
+ if "`difflab'" ~= "" { local difflab difflab("`difflab'") }
+ if "`title'" ~= "" { local title title("`title'") }
+ if "`saving'" ~= "" { local saving saving(`saving') }
+
+ qui replace `diff' = .
+ cap noi _graph `varlist', av(`av') diff (`diff') touse(`touse') rows(`rows') /*
+*/ `xlabel' `ylabel' `avlab' `difflab' `saving' `title' `options' obs_c(`obs_c') text(`text')
+ if _rc {di in red "error in graph options"
+ exit _rc}
+
+ cap gph close
+
+end bagroup
+
+
+prog define _table
+
+ local varlist "req ex "
+ local options "av(str) diff(str) touse(str) format(str) title(str) obs_c(str)"
+ parse "`*'"
+ di _n(2) in gr "Comparisons with the average of the other measures"
+ di _n in gr "Variable | Obs Mean SD Difference Reference Range "
+ di in gr "---------+----------------------------------------------------------"
+ parse "`varlist'", parse(" ")
+ while "`1'" ~ = "" {
+
+ qui replace `diff' = (`1' - `av')* `obs_c'/(`obs_c'-1) if `touse'
+ qui summ `diff' if `touse'
+ local mean = _result(3)
+ local lrr = _result(3) - 2*_result(4)^.5
+ local urr = _result(3) + 2*_result(4)^.5
+
+ if "`rrmin'" == "" { local rrmin = `lrr' }
+ else if `lrr' < `rrmin' { local rrmin = `lrr' }
+ if "`rrmax'" == "" { local rrmax = `urr' }
+ else if `urr' > `rrmax' { local rrmax = `urr' }
+
+* set trace on
+ summ `av' , mean
+ if "`xmin'" == "" { local xmin = _result(5) }
+ else if _result(5) < `xmin' { local xmin = _result(5) }
+ if "`xmax'" == "" { local xmax = _result(6) }
+ else if _result(6) > `xmax' { local xmax = _result(6) }
+
+ qui corr `av' `diff' if `touse'
+ local r = _result(4)
+ local n = _result(1)
+ local sig = tprob(`n'-2, `r'*((`n'-2)/(1-`r'^2))^.5)
+ qui summ `1' if `touse'
+
+ #delim ;
+ di in gr "`1'" _col(10) "|"
+ _col(12) in ye %7.0f `n'
+ _col(22) `format' _result(3)
+ _col(32) `format' _result(4)^.5
+ _col(40) `format' `mean'
+ _col(54) `format' `lrr' in gr " to " in ye `format' `urr';
+ #delim cr
+ mac shift
+ }
+
+
+ global xmin = `xmin'
+ global xmax = `xmax'
+ global rrmin = `rrmin'
+ global rrmax = `rrmax'
+end _table
+
+
+prog define _graph
+ local varlist "req ex min(3)"
+ local options "av(str) diff(str) touse(str) rows(int 999) avlab(str) difflab(str) title(str) saving(str) obs_c(str) yline(str) text(real 100) *"
+
+ parse "`*'"
+ if "`yline'" ~= "" { local yline ",`yline'" }
+
+ if "`avlab'" == "" {local avlab " " }
+ if "`difflab'" == "" {local difflab " " }
+ if "`saving'" ~= "" { local saving saving(`saving') }
+
+ label var `av' "`avlab'"
+ label var `diff' "`difflab'"
+
+ local nvar: word count `varlist'
+ if "`rows'" == "999" { local rows = int(`nvar'^.5) }
+ local cols = int(`nvar' / `rows')
+ if `cols'*`rows' < `nvar' {
+ local cols = `cols' + 1
+ }
+
+ local rlow = 0
+ local rmax = 23063
+ if "`title'" ~= "" {local rmax = 20000 }
+ local clow = 0
+ local cmax = 32000
+
+ local dr = `rmax'/`rows' - 100
+ local dc = `cmax'/`cols' - 100
+
+ cap noi gph open, `saving'
+ if "title" ~= "" {
+ gph pen 1
+ gph font 1000 500
+ gph text 22000 16000 0 0 `title'
+ }
+
+ parse "`varlist'", parse(" ")
+ while "`1'" ~ = "" {
+
+ qui replace `diff' = (`1' - `av')* `obs_c'/(`obs_c'-1) if `touse'
+ qui summ `diff' if `touse'
+ local mean = _result(3)
+ local lrr = _result(3) - 2*_result(4)^.5
+ local urr = _result(3) + 2*_result(4)^.5
+ local rhigh = `rlow' + `dr'
+ local chigh = `clow' + `dc'
+
+ local lab1 : var label `1'
+ if "`lab1'" == "" { local lab1 "`1'" }
+
+ sort `diff' `av'
+ tempvar f n
+ qui by `diff' `av' : gen `f' = _N if `touse'
+ qui by `diff' `av' : gen `n' = _n if `touse'
+
+ local r_tx = int(400 * `text'/100)
+ local c_tx = int(200 * `text'/100)
+
+
+
+ #delim ;
+ cap noi graph `diff' `av' if `touse' & `n' == 1 [fw=`f'], s(o) `xlabel' `ylabel' yline(`lrr', `mean', `urr' `yline')
+ `options' title("`lab1'")
+ bbox(`rlow', `clow', `rhigh', `chigh', `r_tx',`c_tx', 0);
+ #delim cr
+
+ local clow = `clow' + `dc'
+ if `clow' + `dc' > `cmax' {
+ local clow = 0
+ local rlow = `rlow' + `dr'
+ }
+ mac shift
+ }
+ gph close
+
+end _graph
diff --git a/Modules/ado/plus/b/bagroup.hlp b/Modules/ado/plus/b/bagroup.hlp
new file mode 100644
index 0000000..5cb943c
--- /dev/null
+++ b/Modules/ado/plus/b/bagroup.hlp
@@ -0,0 +1,60 @@
+.-
+help for ^bagroup^ (STB-55: sbe33)
+.-
+
+Modified Bland-Altman plots
+---------------------------
+
+ ^bagroup^ varlist [^if^ exp] [^in^ range] [^,^ ^format(^str^)^ ^rows(^#^)^
+ ^avlab(^str^)^ ^difflab(^str^)^ ^title(^str^)^ ^obs(^#^)^
+ ^listwise^ graph_options ]
+
+
+Description
+-----------
+
+^bagroup^ produces modified Bland-Altman plots.
+
+
+Options
+-------
+
+^format(^str^)^ sets the format for display of results.
+
+^rows(^#^)^ specifies the number of rows of graphs to be shown.
+
+^avlab(^str^)^ gives a variable label to the average before plotting the graph.
+
+^difflab(^str^)^ gives a variable label to the difference before plotting the
+ graph.
+
+^title(^str^)^ adds a single title to the block of graphs.
+
+^obs(^#^)^ specifies the minimum number of nonmissing values per observations
+ needed for a point to be plotted.
+
+^listwise^ specifies listwise deletion of missing data. Default is pairwise.
+ Only observations with no missing values are used.
+
+graph_options are any of the options allowed with ^graph, twoway^.
+
+
+Example
+-------
+
+ . ^use tan_part^
+ . ^bagroup pct_*^
+
+
+Author
+------
+ Paul Seed
+ GKT School of Medicine
+ King's London, UK
+ email: paul.seed@@kcl.ac.uk
+
+
+Also see
+--------
+
+ STB: STB-55 sbe33
diff --git a/Modules/ado/plus/b/bamat.ado b/Modules/ado/plus/b/bamat.ado
new file mode 100644
index 0000000..f9caac0
--- /dev/null
+++ b/Modules/ado/plus/b/bamat.ado
@@ -0,0 +1,300 @@
+*! bamat Version 1.2.2 written 11 June 1997 by P T Seed (STB-55: sbe33)
+*!
+*! A matrix of Bland-Altman plots for a series of variables
+*! bamat varlist, graph_options
+
+* Amended 7 August 1998 to allow for saving graphs
+*
+* Amended 3 May 2000 by arr@stata to suppress intermediary graphs and
+* display only the final matrix of Bland-Altman plots
+
+prog define bamat
+ version 5.0
+
+
+ local varlist "req ex min(3)"
+ local if "opt"
+ local in "opt"
+ local options "noTABle TItle(string) saving(string) data nograph markout FORmat(string) XLAbel(string) YLAbel(string) text(str) *"
+
+ parse "`*'"
+ if index("`options'","xlab") ~= 0 | index("`options'","ylab") ~= 0 {
+ di in red "xlabel and ylabel without values not permitted"
+ exit 198
+ }
+
+ parse "`varlist'", parse(" ")
+
+ if "`table'" == "notable" & "`graph'" == "nograph" & "`data'" == "" {
+ di in red "Either table data or graph options must be chosen"
+ exit 194 }
+
+ preserve
+ tempvar touse
+ mark `touse' `if'
+ if "`markout'" ~= "" {markout `touse' `varlist'}
+ if "`format'" == "" { local format "%6.3f" }
+ if "`saving'" ~= "" { local saving "saving(`saving')" }
+
+ if "`table'" ~= "notable" {
+ _table `varlist' if `touse', format(`format') `data'
+ }
+
+ if "`graph'" ~= "nograph" |"`data'" ~= "" {
+ _limits `varlist' if `touse'
+ if "`xlabel'" == "" | "`xlabel'" == "xlabel" {
+ _mynnum xlabel $xmin $xmax
+ local xlabel "xlabel($xlabel)"
+ }
+ else {local xlabel "xlabel(`xlabel')" }
+
+ if "`ylabel'" == "" {
+ _mynnum ylabel $ymin $ymax
+ local ylabel "ylabel($ylabel)"
+ }
+ else {local ylabel "ylabel(`ylabel')" }
+
+ #delim ;
+ di _n in gr "Range of x values is " in ye %6.0g $xmin in gr " to " in ye %6.0g $xmax
+ in gr ", range of y values is " in ye %6.0g $ymin in gr " to " in ye %6.0g $ymax;
+ #delim cr
+ if "`title'" == "" {_graph `varlist' if `touse', `graph' `saving' `xlabel' `ylabel' `data' `options' }
+ else {_graph `varlist' if `touse', title("`title'") `graph' `saving' `xlabel' `ylabel' `data' `options' }
+ }
+end bamat
+
+prog define _table
+ local varlist "req ex"
+ local if "opt"
+ local options "data format(str)"
+ parse "`*'"
+
+ tempvar touse
+ mark `touse' `if'
+
+ di in gr _new "Reference ranges for differences between two methods""
+ #delimit;
+ di in gr _new(2) "Method 1" _col(10) "Method 2" _col(20) "Mean"
+ _col(30) "[95% Reference Range]"
+ _col(54) "Minimum" _col(64) "Maximum" ;
+ #delimit cr
+ di in gr _dup(70) "-"
+
+ tempvar av diff
+ qui gen `av' = .
+ qui gen `diff' = .
+
+ local nvar : word count `varlist'
+ local i = 2
+ while `i' <= `nvar' {
+
+ local j = 1
+ while `j' < `i' {
+* di "i = |`i'|, j = |`j'|"
+ qui replace `diff' = ``i'' - ``j'' `if'
+ label var `diff' " "
+ qui replace `av' = (``i'' + ``j'')/2 `if'
+ label var `av' " "
+ qui summ `diff' `if'
+ local mean = _result(3)
+ local lrr = `mean' - 2*_result(4)^.5
+ local urr = `mean' + 2*_result(4)^.5
+ local min = _result(5)
+ local max = _result(6)
+ di in gr "``i''" _col(10) "``j''" _col(20) in ye `format' `mean' /*
+*/ _col(30) `format' `lrr' _col(40) `format' `urr' _col(52) `format' `min' _col(62) `format' `max'
+ local j = `j' +1
+ }
+ local i = `i' + 1
+ }
+ di in gr _dup(70) "-"
+end _table
+
+
+prog define _data
+ local av `1'
+ local diff `2'
+ local m1 `3'
+ local m2 `4'
+ di _n in gr _dup(40) "-"
+ di in gr "Data for graph comparing `m1' and `m2'"
+ di in gr "Difference" _col(20) "Average"
+ di in gr _dup(40) "-"
+ local k = 1
+ while `k' <= _N {
+ if `av'[`k'] ~= . & `diff'[`k'] ~= . { di `diff'[`k'] _col(20) `av'[`k'] }
+ local k = `k' + 1
+ }
+ di in gr _dup(40) "-" _n
+end _data
+
+
+prog define _graph
+ local varlist "req ex"
+ local if "req"
+ local options "title(str) saving(str) xlabel(str) ylabel(str) nograph data *"
+
+ parse "`*'",
+ if "`saving'" ~= "" { local saving "saving(`saving')" }
+
+ local nvar : word count `varlist'
+ tempvar diff av
+ qui gen `diff' = .
+ qui gen `av' = .
+ label var `diff' " "
+ label var `av' " "
+
+ local gonoff : set graphics
+ set graphics off
+ local i = 1
+ while `i' <= `nvar' {
+ local j = 1
+ while `j' <= `nvar' {
+ qui replace `diff' = ``i'' - ``j'' `if'
+ qui replace `av' = (``i'' + ``j'')/2 `if'
+ tempfile g`i'`j'
+ local graph2 "`graph2' `i'`j'"
+ local graphs "`graphs' `g`i'`j''"
+ if `i' == `j' & "`graph'" == "" { _namegr ``i'', saving(`g`i'`j'', replace) }
+* set trace on
+ else if `i' ~= `j'{
+ qui summ `diff'
+ local mean = _result(3)
+ local lrr = _result(3) - 2*_result(4)^.5
+ local urr = _result(3) + 2*_result(4)^.5
+ if "`graph'" == "" {
+ sort `diff' `av'
+* set trace off
+ tempvar f n
+ qui by `diff' `av' : gen `f' = _N if `diff' ~= . & `av' ~= .
+ qui by `diff' `av' : gen `n' = _n if `diff' ~= . & `av' ~= .
+
+ qui graph `diff' `av' `if' & `n' == 1 [fw=`f'], xlabel(`xlabel') /*
+*/ylabel(`ylabel') `options' saving(`g`i'`j'', replace) yline(`lrr', `mean', `urr')
+ }
+ if "`data'" ~= "" { _data `av' `diff' ``i'' ``j''}
+ }
+ local j = `j' + 1
+ }
+ local i = `i' + 1
+ }
+ set graphics `gonoff'
+
+ if "`graph'" == "" { graph using `graphs', title("`title'") `saving' }
+end _graph
+
+prog define _namegr
+ local varlist "req ex"
+ local options "saving(string)"
+ parse "`*'"
+
+ local f1 = 3000
+ local f2 = 1400
+
+
+ parse "`varlist'", parse (" ")
+ local lab1 : var label `1'
+ if "`lab1'" == "" { local lab1 "`1'" }
+
+ qui gph open, saving(`saving')
+ qui gph font `f1' `f2'
+ qui gph text 11188 16000 0 0 `lab1'
+ qui gph close
+end _namegr
+
+prog define _limits
+ local varlist "req ex"
+ local if "opt"
+ parse "`*'"
+ tempvar av diff
+
+ qui gen `diff' = `2' - `1'
+ qui gen `av' = (`2' + `1')/2
+ qui summ `av' `if'
+ global xmin = _result(5)
+ global xmax = _result(6)
+ qui summ `diff' `if'
+ global ymin = _result(5)
+ global ymax = _result(6)
+
+ local nvar : word count `varlist'
+ local i = 3
+ while `i' <= `nvar' {
+
+ local j = 1
+ while `j' < `i' {
+ qui replace `diff' = ``i'' - ``j'' `if'
+ qui replace `av' = (``i'' + ``j'')/2 `if'
+ qui summ `av' `if'
+ if _result(5) < $xmin { global xmin = _result(5) }
+ if _result(6) > $xmax { global xmax = _result(6) }
+ qui summ `diff' `if'
+ if _result(5) < $ymin { global ymin = _result(5) }
+ if _result(6) > $ymax { global ymax = _result(6) }
+ local j = `j' + 1
+ }
+ local i = `i' + 1
+ }
+ if $ymax + $ymin > 0 { global ymin = -$ymax }
+ else { global ymax = -$ymin }
+end _limits
+
+prog define _mynnum
+*! _mynnum Version 1.00 20/3/1997 PTS
+*! a version of nicenum to handle numbers less than 1
+*! usage: _mynnum global_macro minimum maximum mumber_of_ticks
+ version 5.0
+ local macro "`1'"
+ if `2' ~= `3' {
+ if `2' < `3' {
+ local min `2'
+ local max `3'
+ }
+ else {
+ local min `3'
+ local max `2'
+ }
+ }
+ else {
+ di in red "Numbers do not differ"
+ exit 198
+ }
+ local nticks `4'
+ if "`nticks'" == "" { local nticks = 5 }
+ else { cap confirm integer `nticks'
+ assert `nticks' > 2
+ if _rc ~= 0 {
+ di in red "Number of ticks requested must be at least 2"
+ exit 198
+ }
+ }
+
+ local gap = 10^(int(log10(`max' - `min'))-1)
+
+ local nt = int((`max' - `min' )/`gap') + 1
+ while `nt' < `nticks' {
+ local gap = `gap'/10
+ local nt = int((`max' - `min' )/`gap') + 1
+ }
+
+ if `nt' > `nticks' - 1 {
+ local gap = `gap' * 2
+ local nt = int((`max' - `min' )/`gap') + 1
+ }
+ if `nt' > `nticks' - 1 {
+ local gap = `gap' * 2.5
+ }
+ if `nt' > `nticks' - 1 {
+ local gap = `gap' * 2
+ }
+
+
+ local tick = `gap'*int(`min'/`gap')
+ while `tick' > `min' { local tick = `tick' - `gap' }
+ global `macro' "`tick'"
+ while `tick' < `max' {
+ local tick = `tick' + `gap'
+ global `macro' "$`macro', `tick'"
+ }
+
+end _mynnum
diff --git a/Modules/ado/plus/b/bamat.hlp b/Modules/ado/plus/b/bamat.hlp
new file mode 100644
index 0000000..db58d36
--- /dev/null
+++ b/Modules/ado/plus/b/bamat.hlp
@@ -0,0 +1,64 @@
+.-
+help for ^bamat^ (STB-55: sbe33)
+.-
+
+Multiple Bland-Altman plots
+---------------------------
+
+ ^bamat^ varlist [^if^ exp] [^in^ range] [^, for^mat^(^str^)^ ^notable^
+ ^data^ ^avlab(^str^)^ ^difflab(^str^)^ ^obs(^#^)^
+ ^listwise^ ^ti^tle^(^str^)^ graph_options ]
+
+
+Description
+-----------
+
+^bamat^ produces a matrix of Bland-Altman plots for all possible pairs of
+variables.
+
+
+Options
+-------
+
+^format(^str^)^
+sets the format for display of results.
+
+^notable^ suppresses display of results data list data used in plotting
+ each graph.
+
+^avlab(^str^)^ gives a variable label to the average before plotting the graph.
+
+^difflab(^str^)^ gives a variable label to the difference before plotting
+ the graph.
+
+^obs(^#^)^ specifies the minimum number of nonmissing values per observations
+ needed for a point to be plotted. The default value is 2.
+
+^listwise^ specifies listwise deletion of missing data. Default is
+ pairwise. Only observations with no missing values are used.
+
+^title(^str^)^ adds a single title to the block of graphs.
+
+graph_options are any of the options allowed with ^graph, twoway^.
+
+
+Example
+-------
+
+ . ^use tan_part^
+ . ^bamat pct_*^
+
+
+Author
+------
+ Paul Seed
+ GKT School of Medicine
+ King's London, UK
+ email: paul.seed@@kcl.ac.uk
+
+
+Also see
+--------
+
+ STB: STB-55 sbe33
+
diff --git a/Modules/ado/plus/b/baplot.ado b/Modules/ado/plus/b/baplot.ado
new file mode 100644
index 0000000..5b12935
--- /dev/null
+++ b/Modules/ado/plus/b/baplot.ado
@@ -0,0 +1,218 @@
+*! baplot.ado version 1.21 written by PTS (p.seed@umds.ac.uk) (STB-55: sbe33)
+*! Produces Bland-Altman plots for two variables
+*! See Bland & Altman Lancet Feb 8 1986, pp 307-310
+*!
+*! syntax: baplot var1 var2 if in, symbol(symbol) format(%6.3f) avlab("Average") difflab("Difference") yline(str) textsize(#) other graph options
+
+* Now allows choice of symbol, and extra ylines Feb 8 1996
+* larger plotting symbols for overlapping points
+* Silly comparisons taken out
+
+
+cap prog drop baplot
+prog define baplot
+version 6.0
+
+* set trace off
+
+ syntax varlist(min=2 max=2 numeric) [if] [in], /*
+*/ [Symbol(string) format(string) avlab(string) difflab(string) /*
+*/ novars noGRaph ci zero mean yline(string) diag saving(string) /*
+*/ text(real 100) ratio(real 1) *]"
+
+ parse "`varlist'", parse(" ")
+ local m1 "`1'"
+ local m2 "`2'"
+
+ if "`symbol'" == "" { local symbol "o" }
+ if "`format'" == "" {local format "%6.3f" }
+ if "`saving'" ~= "" { local saving "saving(`saving')"}
+ if "`ci'" ~= "" {local mean = "mean" }
+
+
+ preserve
+ tempvar touse
+ mark `touse' `if' `in'
+ markout `touse' `m1' `m2'
+ qui keep if `touse'
+
+ tempvar av diff
+ if "`avlab'" == "" { local avlab "Average"}
+ if lower("`avlab'") == "nolab" { local avlab " "}
+
+ if "`difflab'" == "" { local difflab "Difference" }
+ if lower("`difflab'") == "nolab" { local difflab " "}
+ qui gen `av' = (`m1' + `m2')/2
+ qui gen `diff' = `m1' - `m2'
+ label var `av' "`avlab'"
+ label var `diff' "`difflab'"
+
+ qui summ `diff' if `touse'
+ local xbar = _result(3)
+ local sd = _result(4)^.5
+ local n = _result(2)
+ local se = `sd'/`n'^.5
+ local t = invt(_result(2)-1, .95)
+ local lrr = `xbar' - 2*`sd'
+ local urr = `xbar' + 2*`sd'
+ local min = _result(5)
+ local max = _result(6)
+ local lcb = `xbar' - `t'*`se'
+ local ucb = `xbar' + `t'*`se'
+
+ summ `av', meanonly
+ local xmin = _result(5)
+ local xmax = _result(6)
+
+ local yline "`lrr', `urr'"
+ if "`ci'" ~= "" {
+ local yline "`yline', `lcb', `ucb'"
+ }
+ if "`mean'" ~= "" | "`zero'" == "" {local yline "`yline', `xbar'"}
+ if "`zero'" ~= "" {local yline "`yline', 0"}
+
+ qui corr `av' `diff'
+ local r = _result(4)
+ local n = _result(1)
+ local sig = tprob(`n'-2, `r'*((`n'-2)/(1-`r'^2))^.5)
+
+
+ #delim ;
+ di in gr _n "Bland-Altman comparison of `m1' and `m2'";
+ di in gr "Limits of agreement (Reference Range for difference): " in ye `format' `lrr'
+ in gr " to " in ye `format' `urr' ;
+ di in gr "Mean difference: " in ye `format' `xbar'
+ in gr " (CI " in ye `format' `lcb'
+ in gr " to " in ye `format' `ucb'
+ in gr ") ";
+ di in gr "Range : " in ye `format' `xmin'
+ in gr " to " in ye `format' `xmax';
+ di in gr "Pitman's Test of difference in variance: r = " in ye `format' `r'
+ in gr ", n = " in ye `n'
+ in gr ", p =" in ye `format' `sig' ;
+ #delim cr
+
+ if "`vars'" ~= "" {
+ qui corr `m1' `m2', cov
+ local tau = _result(4)
+ qui summ `m1'
+ local err1 = _result(4) - `tau'
+ qui summ `m2'
+ local err2 = _result(4) - `tau'
+ di in gr "Estimated variance of true measure: " in ye `format' `tau'
+ di in gr "Estimated error variance (`1'): " in ye `format' `err1'
+ di in gr "Estimated error variance (`2'): " in ye `format' `err2'
+ di in gr "Very low or negative error variances may indiate that modelling assumptions are violated."
+ }
+
+ global S_1 `xbar'
+ global S_2 `lrr'
+ global S_3 `urr'
+
+ if "`graph'" == "" & "`diag'" == "" {
+ sort `diff' `av'
+ tempvar f n
+ qui by `diff' `av': gen `f' = _N if `diff' ~= . & `av' ~= .
+ qui by `diff' `av': gen `n' = _n if `diff' ~= . & `av' ~= .
+ graph `diff' `av' if `touse' & `n' == 1 [fw=`f'], symbol(`symbol') `xlabel' `ylabel' yline(`yline') `saving' `options'
+ }
+
+ else if "`diag'" ~= "" {
+
+ local nobs = _N + 1
+ qui set obs `nobs'
+ qui replace `m2' = 0 if `m2' == .
+
+* loa
+ tempvar lb ub
+ qui gen `ub' = `m2' + `xbar' + 2*`sd'
+ qui replace `ub' = . if `ub' < 0
+ summ `ub', mean
+ qui replace `ub' = . if `ub' > _result(5) & `ub' < _result(6)
+
+ qui gen `lb' = `m2' + `xbar' - 2*`sd'
+ summ `lb', mean
+ if _result(5) < 0 {
+ qui replace `lb' = . if `lb' < 0
+ local nobs = _N + 1
+ qui set obs `nobs'
+ qui replace `lb' = 0 if _n == _N
+ qui replace `m2' = 2*`sd' - `xbar' if _n == _N
+ }
+ summ `lb', mean
+ qui replace `lb' = . if `lb' > _result(5) & `lb' < _result(6)
+
+* ci
+ if "`ci'" ~= "" {
+ tempvar lci uci
+ qui gen `lci' = `m2' + `xbar' - invt(`n'-1,0.95)*`sd'/`n'^.5
+ qui gen `uci' = `m2' + `xbar' + invt(`n'-1,0.95)*`sd'/`n'^.5
+ summ `lci', mean
+ if _result(5) < 0 {
+ qui replace `lci' = . if `lci' < 0
+ local nobs = _N + 1
+ qui set obs `nobs'
+ qui replace `lci' = 0 if _n == _N
+ qui replace `m2' = invt(`n'-1,0.95)*`sd'/`n'^.5 - `xbar' if _n == _N
+ }
+ summ `uci', mean
+ if _result(5) < 0 {
+ qui replace `uci' = . if `uci' < 0
+ local nobs = _N + 1
+ qui set obs `nobs'
+ qui replace `uci' = 0 if _n == _N
+ qui replace `m2' = - invt(`n'-1,0.95)*`sd'/`n'^.5 - `xbar' if _n == _N
+ }
+ summ `lci', mean
+ qui replace `lci' = . if `lci' > _result(5) & `lci' < _result(6)
+ summ `uci', mean
+ qui replace `uci' = . if `uci' > _result(5) & `lci' < _result(6)
+ }
+
+ summ `m2' if `m2' ~= ., mean
+ tempvar diag
+
+* zero
+ if "`zero'" ~= "" | "`mean'" == "" {
+ qui gen `diag' = `m2' if `m2' == _result(5) | `m2' == _result(6)
+ }
+
+* mean
+ else {
+ qui gen `diag' = `m2' + `xbar' if `m2' == _result(5) | `m2' == _result(6)
+ summ `diag', mean
+ if _result(5) < 0 {
+ qui replace `diag' = . if `diag' < 0
+ local nobs = _N + 1
+ qui set obs `nobs'
+ qui replace `diag' = 0 if _n == _N
+ qui replace `m2' = - `xbar' if _n == _N
+ }
+ }
+
+ sort `m1' `m2'
+ tempvar f n
+ qui by `m1' `m2': gen `f' = _N
+ qui by `m1' `m2': gen `n' = _n
+
+ if ("`xlabel'" == "" | "`ylabel'" == "") & index("`options'","xlab") == 0 & index("`options'","ylab") == 0 {
+ nicenum labels = 0 `m1' `m2'
+ local xlabel xlab($labels)
+ local ylabel ylab($labels)
+ }
+
+ local r_tx = int(923 * `text'/100)
+ local c_tx = int(444 * `text'/100)
+ local c_min = int(16000 - (23063*`ratio'/2))
+ local c_max = int(16000 + (23063*`ratio'/2))
+di "bbox(0,`c_min',23063,`c_max',`r_tx',`c_tx',0) "
+
+ gph open, `saving'
+ graph `m1' `diag' `ub' `lb' `lci' `uci' `m2' if `n' == 1 [fw=`f'], /*
+*/ `xlabel' `ylabel' s(oiiiii) c(.lllll) sort /*
+*/ bbox(0,`c_min',23063,`c_max',`r_tx',`c_tx',0) `options'
+ gph close
+ }
+
+end
+exit
diff --git a/Modules/ado/plus/b/baplot.hlp b/Modules/ado/plus/b/baplot.hlp
new file mode 100644
index 0000000..3797975
--- /dev/null
+++ b/Modules/ado/plus/b/baplot.hlp
@@ -0,0 +1,51 @@
+.-
+help for ^baplot^ (STB-55: sbe33)
+.-
+
+Bland-Altman plots
+------------------
+
+ ^baplot^ varname1 varname2 [^if^ exp] [^in^ range] [^, format(^str^)^
+ ^avlab(^str^) difflab(^str^)^ graph_options]
+
+
+Description
+-----------
+
+^baplot^ produces Bland-Altman plots, that is, plots of the difference of
+paired variables versus their average.
+
+
+Options
+-------
+
+^format(^str^)^ sets the format for the results given.
+
+^avlab(^str^)^ gives a variable label to the average before plotting the graph.
+
+^difflab(^str^)^ gives a variable label to the difference before plotting the
+ graph.
+
+graph_options are any of the options allowed with ^graph, twoway^.
+
+
+Examples
+--------
+
+ . ^use col_icp^
+ . ^baplot icp colorime, avlab("ICPOES vs Colorimetry)^
+
+
+Author
+------
+ Paul Seed
+ GKT School of Medicine
+ King's London, UK
+ email: paul.seed@@kcl.ac.uk
+
+
+Also see
+--------
+
+ STB: STB-55 sbe33
+
diff --git a/Modules/ado/plus/b/batplot.ado b/Modules/ado/plus/b/batplot.ado
new file mode 100644
index 0000000..19f8e2e
--- /dev/null
+++ b/Modules/ado/plus/b/batplot.ado
@@ -0,0 +1,269 @@
+*! Date : 19 May 2009
+*! Version : 1.12
+*! Authors : Adrian Mander
+*! Email : adrian.mander@mrc-bsu.cam.ac.uk
+*! Description : Bland-Altman plots with trend adjustment
+
+/*
+17/5/06 v1.3 add-in the middle line
+6/10/06 v1.4 Handle multiple data points at the same point by using frequency option
+ Also add Scatter option just to add options to the scatter part of the plot
+2/9/07 v1.5 Changed version from 8 to 9.2
+11/12/07 v1.6 Extended the shaded area
+14/12/07 v1.7 Add limits of agreement into the info option
+11/2/08 v1.8 BUGs fixed and extended the shading to the xlimits
+17/4/08 v1.9 BUG fix.. the info limits were the wrong way round!
+9/5/08 v1.10 Allowing shading to extend beyond data to any limit you like
+11/5/08 v1.11 Added the range to be displayed for the averages
+19/5/2009 v1.12 Changed email address
+11/6/12 v1.13 Added extra option for titles and number of decimal places in display
+*/
+
+prog def batplot, rclass
+version 9.2
+syntax varlist (min=2 max=2) [if] [in] [,NOtrend INFO VALabel(varname) MOPTIONS(string asis) XLABel(numlist) SHADING(numlist min=2 max=2) SCatter(string asis) NOGraph DP(int 2) *]
+local gopt "`options'"
+
+if "`moptions'"~="" local mopt `"moptions(`moptions')"'
+
+preserve
+tempvar touse
+mark `touse' `if' `in'
+markout `touse' `m1' `m2'
+qui keep if `touse'
+
+if "`xlabel'"~="" {
+ local glab `"xlabel(`xlabel')"'
+ local i 0
+ foreach xv of local xlabel {
+ if `i++'==0 local sxmin "`xv'"
+ local sxmax "`xv'"
+ }
+ local shade "shade(`sxmin' `sxmax')"
+}
+
+/* To stop the shading going the whole length of the x-axis */
+if "`shading'"~="" {
+ local i 0
+ foreach s of local shading {
+ if `i++'==0 local smin "`s'"
+ else local smax "`s'"
+ }
+ if `smin'<`smax' local shade "shade(`smin' `smax')"
+ else local shade "shade(`smax' `smin')"
+}
+
+
+/* NOW do the trend version */
+
+if "`valabel'"~="" local add "val(`valabel')"
+
+_calctrend `varlist', `gopt' `notrend' `info' `add' `mopt' sc(`scatter') `glab' `shade' `nograph' dp(`dp')
+
+
+ return local mean = "`r(mean)'"
+ return local b0 = "`r(b0)'"
+ return local b1 = "`r(b1)'"
+ return local c0 = "`r(c0)'"
+ return local c1 = "`r(c1)'"
+ return local eqn = "`r(eqn)'"
+ return local upper = "`r(upper)'"
+ return local lower = "`r(lower)'"
+
+restore
+end
+
+
+/* calculate trend and do a BA plot with trend */
+
+prog def _calctrend,rclass
+syntax [varlist] [,NOTREND INFO VALabel(varname) MOPTIONS(string asis) SCatter(string asis) shade(numlist) NOGraph DP(int 2) *]
+local xopt "`options'"
+
+if "`shade'"~="" {
+ local i 0
+ foreach s of local shade {
+ if `i++'==0 local a "`s'"
+ local b "`s'"
+ }
+ local sxmin = `a'
+ local sxmax = `b'
+}
+
+local i 1
+foreach var of varlist `varlist' {
+ local v`i++' "`var'"
+}
+
+tempvar av diff
+
+qui gen `av' = (`v1' + `v2')/2
+qui gen `diff' = `v1' - `v2'
+local ytit "Difference (`v1'-`v2')"
+local xtit "Average of `v1' and `v2'"
+
+lab var `diff' "Diff"
+lab var `av' "Mean"
+
+if "`notrend'"~="" {
+ qui summ `diff'
+ local xbar = `r(mean)'
+ local sd = `r(Var)'^.5
+ local n = `r(N)'
+ local se = `sd'/`n'^.5
+ local t = invttail(`n'-1, .95)
+ local lrr = `xbar' - invnorm(0.975)*`sd' /* 95% lower limit of agreement */
+ local urr = `xbar' + invnorm(0.975)*`sd' /* 95% upper limit of agreement */
+ local mrr = `xbar' /* 95% mean agreement */
+
+ di "{text}Mean difference = {res}`mrr'"
+ di "{text}Limits of agreement = ({res}`lrr'{text},{res}`urr'{text})"
+
+ local min = `r(min)'
+ local max = `r(max)'
+ local lcb = `xbar' - `t'*`se'
+ local ucb = `xbar' + `t'*`se'
+ qui summ `av'
+ local xmin = `r(min)'
+ local xmax = `r(max)'
+ local a : di %5.3f `xmin'
+ local b : di %5.3f `xmax'
+ local range = "Averages lie between `a' and `b'"
+ di "{text}Averages lie between {res} `a' {text}and {res}`b'"
+ qui corr `av' `diff'
+ local r = `r(rho)'
+ local n = `r(N)'
+ local sig = ttail(`n'-2, `r'*((`n'-2)/(1-`r'^2))^.5)
+
+ tempvar uy ly my
+
+/* The bit to extend the shade */
+
+ local obs =`c(N)'+2
+ qui set obs `obs'
+ if "`sxmin'"~="" qui replace `av'=`sxmin' in `obs--'
+ if "`sxmax'"~="" qui replace `av'=`sxmax' in `obs'
+
+ qui gen `uy' = `urr'
+ qui gen `ly' = `lrr'
+ qui gen `my' = `mrr'
+
+ sort `av'
+
+ if "`info'"~="" {
+ local te1:di %6.3f `mrr'
+ local te2:di %6.3f `lrr'
+ local te3:di %6.3f `urr'
+
+ qui count if (`diff'>`urr' | `diff'<`lrr' ) & `diff'~=.
+ local nout = `r(N)'
+ qui count if `diff'~=.
+ local n = `r(N)'
+ local pctout : di %6.2f `nout'/`n'*100
+ local xopt `"`xopt' subtitle("`nout'/`n' = `pctout'% outside the limits of agreement" "Mean difference `te1'" "95% limits of agreement (`te2',`te3')" "`range'") "'
+ }
+ if "`valabel'"~="" {
+ tempvar label
+ qui gen `label' = ""
+ cap confirm string variable `valabel'
+ if _rc~=0 qui replace `label' = string(`valabel') if `diff'>`urr' | `diff'<`lrr'
+ else qui replace `label' = `valabel' if `diff'>`urr' | `diff'<`lrr'
+ local scatteropt "mlabel(`label') note(Points outside limits labelled by `valabel')"
+ }
+
+ tempvar freq
+ qui bysort `diff' `av':gen `freq'=_N
+ local fopt "[fw=`freq']"
+ if index("`scatter'","jitter")~=0 local fopt ""
+
+if "`nograph'"=="" twoway (rarea `uy' `ly' `av', bc(gs13) sort) (scatter `diff' `av' `fopt', m(o) `scatteropt' `scatter' `moptions' ) (line `my' `av',lp(dash) sort ) , ////
+ legend(off) ytitle(`ytit') xtitle(`xtit') xlabel(`xmin' `xmax') `xopt'
+
+ return local lower = `lrr'
+ return local upper = `urr'
+ return local mean = `mrr'
+}
+
+else {
+ qui reg `diff' `av'
+ local b1 = _b[`av']
+ local b0 = _b[_cons]
+ local sd = `e(rmse)'
+ qui predict resid , resid
+ qui gen absresid = abs(resid)
+
+ /* Analysis of the residuals */
+
+ qui reg absresid `av'
+ local c0 = _b[_cons]
+ local c1=_b[`av']
+
+ qui su `diff'
+ local max = `r(max)'
+ local min = `r(min)'
+ qui su `av'
+ local xmax = r(max)
+ local xmin = r(min)
+
+ local max: di %5.3f `xmax'
+ local min: di %5.3f `xmin'
+
+ tempvar y uy ly x
+
+/* The bit to extend the shade */
+
+ local obs =`c(N)'+2
+ qui set obs `obs'
+ if "`sxmin'"~="" qui replace `av'=`sxmin' in `obs--'
+ if "`sxmax'"~="" qui replace `av'=`sxmax' in `obs'
+
+ sort `av'
+ qui gen `y' = `b0'+`b1'*`av'
+ qui gen `uy' = `b0'+`b1'*`av' + 2.46*(`c0'+`c1'*`av')
+ qui gen `ly' = `b0'+`b1'*`av' - 2.46*(`c0'+`c1'*`av')
+
+ if "`info'"~="" {
+ qui count if (`diff'>`uy' | `diff'<`ly') & `diff'~=.
+ local nout = `r(N)'
+ qui count if `diff'~=.
+ local n = `r(N)'
+ local mdp = `dp'+3
+ local mdp1 = `dp'+4
+
+ local pctout : di %`mdp1'.`dp'f `nout'/`n'*100
+ local te0 : di %`mdp'.`dp'f `b0'
+ local te1 : di %`mdp'.`dp'f `b1'
+ local te2 : di %`mdp'.`dp'f `c0'
+ local te3 : di %`mdp'.`dp'f `c1'
+ local xopt `"`xopt' subtitle("`nout'/`n' = `pctout'% outside the limits of agreement" "Mean Diff = `te0'+ `te1'*Average " "Limits +/- 2.46*(`te2' + `te3'*Average) ") "'
+ }
+ if "`valabel'"~="" {
+ tempvar label
+ qui gen `label' = ""
+ cap confirm string variable `valabel'
+ if _rc~=0 qui replace `label' = string(`valabel') if `diff'>`uy' | `diff'<`ly'
+ else qui replace `label' = `valabel' if `diff'>`uy' | `diff'<`ly'
+ local scatteropt "mlabel(`label') note(Points outside limits labelled by `valabel')"
+ }
+
+ tempvar freq
+ qui bysort `diff' `av':gen `freq'=_N
+ local fopt "[fw=`freq']"
+ if index("`scatter'","jitter")~=0 local fopt ""
+
+if "`nograph'"=="" {
+ twoway (rarea `uy' `ly' `av', bc(gs13) sort)(scatter `diff' `av' `fopt', `scatteropt' `scatter') /*
+*/(line `y' `av', lp(dash) sort) , legend(off) ytitle(`ytit') xtitle(`xtit') xlabel(`xmin' `xmax') `xopt'
+}
+
+ return local b0 = `b0'
+ return local b1 = `b1'
+ return local c0 = `c0'
+ return local c1 = `c1'
+ return local eqn = "`b0'+`b1'*av"
+ return local upper = "`b0'+`b1'*Average + 2.46*(`c0'+`c1'*Average)"
+ return local lower = "`b0'+`b1'*Average - 2.46*(`c0'+`c1'*Average)"
+
+}
+
+end
diff --git a/Modules/ado/plus/b/batplot.hlp b/Modules/ado/plus/b/batplot.hlp
new file mode 100644
index 0000000..618342d
--- /dev/null
+++ b/Modules/ado/plus/b/batplot.hlp
@@ -0,0 +1,128 @@
+{smcl}
+{* 9May2008}{...}
+{cmd:help batplot}
+{hline}
+
+{title:Title}
+
+ {hi: Produces a Bland-Altman plot when there is a relationship between paired differences and their average}
+
+
+{title:Syntax}
+
+{p 8 17 2}
+{cmdab:batplot} {it:varname1 varname2} [if] [in]
+[{cmd:,} {it:options}]
+
+{synoptset 20 tabbed}{...}
+{synopthdr}
+{synoptline}
+{syntab:Main}
+{synopt:{opt info:}} specifies that the percentage of points outside the limits of agreement are displayed as a subtitle.{p_end}
+{synopt:{opt val:abel}({varname})} specifies that the points outside the limits of agreement be labelled using the variable {it:varname}.{p_end}
+{synopt:{opt shading:}(min max)} specifies the extent of shading beyond the range of the data.{p_end}
+{synopt:{opt notrend:}} specifies that the original Bland-Altman plot (without a trend) be plotted.{p_end}
+{synopt:{opt moptions:}} specifies options for the markers that lie outside the limits of agreement.{p_end}
+{synopt:{opt sc:atter}} specifies options for the scatter part of the final plot, see {help scatter}.{p_end}
+{synopt:{help twoway_options}} specifies options for example titles and labels.{p_end}
+{synoptline}
+{p2colreset}{...}
+
+
+{title:Description}
+
+{pstd}
+{cmd:batplot} produces a Bland-Altman plot adjusted for trend.
+
+{pstd}
+The standard Bland-Altman plot is between the difference of paired variables versus the average, this is produced
+using the {bf:notrend} option. The main addition that this command handles is when there is a linear relationship between
+the the paired difference and the paired average. A regression model is used to adjust the limits of agreement accordingly.
+This is particularly useful when the two variables might be measured on different scales and hence a straight conversion
+factor would recalibrate the two variables.
+
+{title:Options}
+
+{dlgtab:Main}
+
+{phang}
+{opt info:} specifies that the percentage of points outside the limits of agreement are displayed as a subtitle. Additionally
+when using the notrend option the limits of agreement and mean difference are included in the subtitle.
+
+{phang}
+{opt val:abel}({varname}) specifies that the points outside the limits of agreement be labelled using the variable {it:varname}.
+
+{phang}
+{opt shading:}(min max) specifies the extent of shading beyond the range of the data. The default is that the limits of
+shading is determined by the values in the {hi:xlabel} option.
+
+{phang}
+{opt notrend:} specifies that the original Bland-Altman plot (without a trend) be plotted.
+
+{phang}
+{opt moptions:} specifies options for the markers that lie outside the limits of agreement, the options can be anything from
+the scatter marker options {help scatter##marker_options}.
+
+{phang}
+{opt sc:atter} specifies options for the scatter part of the final plot.
+
+{title:Examples}
+
+{pstd}
+Using the {hi:auto.dta} dataset supplied with STATA 8 this command can check whether there is agreement between
+turning circle (ft) and miles per gallon, click the highlighted text in order,
+
+{phang}{stata sysuse auto, clear}
+
+{phang}{stata batplot mpg turn}
+
+{pstd}
+This is the most basic graphic and using twoway options the look can be improved by clicking below,
+
+{phang}
+{stata batplot mpg turn, title(Agreement between mpg and turn) xlab(26(4)38) }
+
+{pstd}
+By specifying extra options the outlying points can be labelled and identified by the car make,
+
+{phang}
+{stata batplot mpg turn, title(Agreement between mpg and turn) info valabel(make) xlab(26(4)38) }
+
+{pstd}
+To obtain the original Bland Altman plot use the notrend option,
+
+{phang}
+{stata batplot mpg turn, title(Agreement between mpg and turn) info valabel(make) notrend xlab(26(4)38) }
+
+{pstd}
+To improve the labelling of the point VW it may be preferable to change the clock position of the label i.e.
+labels could appear to the left of the point. This is handled below with {hi: moptions()}.
+
+{phang}
+{stata batplot mpg turn, title(Agreement between mpg and turn) info valabel(make) notrend xlab(26(4)38) moptions(mlabp(9))}
+
+{pstd}
+Additionally in the case of multiple scatter points by using the {hi:scatter()} option the user can specify to "{hi:jitter}" datapoints
+
+{phang}
+{stata batplot mpg turn, notrend xlab(26(4)38) moptions(mlabp(9)) sc(jitter(4))}
+
+
+{title:Author}
+
+{p}
+Adrian Mander, MRC Human Nutrition Research, Cambridge, UK.
+
+Email {browse "mailto:adrian.mander@mrc-hnr.cam.ac.uk":adrian.mander@mrc-hnr.cam.ac.uk}
+
+{title:Also see}
+
+Related commands
+
+HELP FILES
+{help baplot} (if installed)
+
+
+
+
+
diff --git a/Modules/ado/plus/b/binolist.ado b/Modules/ado/plus/b/binolist.ado
new file mode 100644
index 0000000..22eccb7
--- /dev/null
+++ b/Modules/ado/plus/b/binolist.ado
@@ -0,0 +1,22 @@
+program def binolist, rclass
+*! NJC 1.1.0 6 June 2000
+* NJC 1.0.0 25 Jan 2000
+ version 6.0
+ syntax , K(numlist int max=1 >0) [ Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ local i = 1
+ while `i' <= `k' {
+ local val = comb(`k'-1, `i'-1)
+ local newlist "`newlist' `val'"
+ local i = `i' + 1
+ }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
diff --git a/Modules/ado/plus/b/binolist.hlp b/Modules/ado/plus/b/binolist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/b/binolist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/b/blandaltman.ado b/Modules/ado/plus/b/blandaltman.ado
new file mode 100644
index 0000000..3c0e844
--- /dev/null
+++ b/Modules/ado/plus/b/blandaltman.ado
@@ -0,0 +1,89 @@
+
+***********************************************************************************************************************
+**** Program blandaltman (one parameter against another parameter) startet ********************************************
+***********************************************************************************************************************
+
+* set more off
+* capture program drop blandaltman
+ program blandaltman
+ syntax varlist(max=2)
+
+ // prepare for Bland Altman Interreader
+ tempvar diff_xy
+ tempvar avg_xy
+ tempvar lower
+ tempvar higher
+ tempvar MW
+ tempvar SE
+ tempvar CIhigher
+ tempvar CIlower
+
+ generate `diff_xy'=0
+ generate `avg_xy'=0
+ generate `lower'=0
+ generate `higher'=0
+ generate `MW'=0
+ generate `SE'=0
+ generate `CIhigher'=0
+ generate `CIlower'=0
+
+ // count the variable: how many variable are in the list?
+ local noofvars : word count `varlist'
+ display as text "The variable list of this program counts " `noofvars' " variables"
+ display as result " "
+ display as result " "
+
+ // Interreader
+ local x = 1
+ local y = 1
+ foreach varx of varlist `varlist' {
+ foreach vary of varlist `varlist'{
+ if `y' >`x'{
+ quietly replace `avg_xy'=(`varx'+`vary')/2
+ quietly replace `diff_xy'=`varx'-`vary'
+ display as result " Bland Altman Plot of `varx' and `vary'"
+ quietly sum `diff_xy'
+ quietly return list
+ quietly replace `MW'=r(mean)
+ quietly replace `lower'=r(mean)-2*r(sd)
+ quietly replace `higher'=r(mean)+2*r(sd)
+ quietly replace `SE'=(r(sd))/(sqrt(r(N)))
+ quietly replace `CIlower'=r(mean)-2*`SE'
+ quietly replace `CIhigher'=r(mean)+2*`SE'
+ display as result "- mean of difference between `varx' and `vary' is "r(mean)
+ display as result "- sd of difference between `varx' and `vary' is "r(sd)
+ display as result "- lower limit of difference between `varx' and `vary' is " `lower'
+ display as result "- higher limit of difference between `varx' and `vary' is " `higher'
+ display as result "- Limits of agreement (Reference Range for difference): " `lower' " to " `higher'
+ display as result "- Mean difference:" `MW' " (CI " `CIlower' " to " `CIhigher' ")"
+ display as result " "
+ display as result " "
+
+ label var `diff_xy' "Values"
+ label var `MW' "mean of difference"
+ label var `lower' "lower limit of agreement"
+ label var `higher' "higher limit of agreement"
+ twoway (scatter `diff_xy' `avg_xy', msymbol(smcircle_hollow) mcolor(ebblue)) (line `MW' `avg_xy', lcolor(red))(line `lower' `avg_xy', lcolor(black) ) (line `higher' `avg_xy', lcolor(black) ), title(Bland Altman Plot, size(8)) subtitle(,size(5)) xtitle(Average of `varx' and `vary') ytitle(Difference of `varx' and `vary') caption() note(NOTE) legend(off)
+ }
+ local y = `y'+1
+ }
+ local y = 1
+ local x =`x'+1
+ }
+ end
+
+***********************************************************************************************************************
+**** Program blandaltman (one parameter against another parameter) endet **********************************************
+***********************************************************************************************************************
+
+
+
+
+// EXAMPLE
+
+* sysuse bpwide.dta
+
+ // to create a bland altman plot use the command "blandaltman" with variable1 and variable2
+* blandaltman bp_before bp_after
+
+
\ No newline at end of file
diff --git a/Modules/ado/plus/b/bollenstine.ado b/Modules/ado/plus/b/bollenstine.ado
new file mode 100644
index 0000000..1c5b8e4
--- /dev/null
+++ b/Modules/ado/plus/b/bollenstine.ado
@@ -0,0 +1,187 @@
+*! Bollen-Stine bootstrap, v.1.3, Stas Kolenikov
+program define bollenstine, eclass
+
+ syntax, [Reps(int 200) SAVing(str) notable noheader nolegend ///
+ SAFER CONFAOPTions(str) *]
+
+
+ * this is a post-estimation command following confa1
+ if "`e(cmd)'" ~= "confa1" & "`e(cmd)'" ~= "confa" error 301
+
+ * the low level preserve
+ preserve
+ tempfile pres
+ tempname confares
+ est store `confares'
+ qui save `pres'
+
+ qui keep if e(sample)
+ local T = e(lr_u)
+
+ local safer cap noi
+
+ if "`saving'" == "" {
+ tempfile bsres
+ local saving `bsres'
+ }
+
+ if "`e(cmd)'" == "confa1" {
+
+ local varlist = "`e(depvar)'"
+ local p : word count `varlist'
+
+ tempname Sigma bb
+ mat `Sigma' = e(Model)
+ mat `bb' = e(b)
+
+ mata: CONFA1_BSrotate("`Sigma'","`varlist'")
+
+ `safer' bootstrap _b (T: T = e(lr_u)) (reject: reject = (e(lr_u) > `T') ) , ///
+ reps(`reps') saving(`saving') notable noheader nolegend ///
+ reject( e(converged) == 0) `options' ///
+ : confa1 `varlist' , from(`bb', skip) `confaoptions'
+ * may need some other options, too!
+ nobreak if "`safer'"~="" & _rc {
+ * for whatever reason, the bootstrap broke down
+ qui use `pres' , clear
+ qui est restore `confares'
+ qui est drop `confares'
+ error _rc
+ }
+ * just to display the results
+ * the covariance matrix should have been reposted by the -bootstrap-!
+
+ * we still need to trick Stata back into confa1!
+ ereturn local cmd confa1
+
+ }
+
+ else if "`e(cmd)'" == "confa" {
+
+ local varlist = "`e(observed)'"
+ local p : word count `varlist'
+
+ tempname Sigma bb
+ mat `Sigma' = e(Sigma)
+ mat `bb' = e(b)
+
+ mata: CONFA1_BSrotate("`Sigma'","`varlist'")
+
+ * set up the call
+ local k = 1
+ while "`e(factor`k')'" ~= "" {
+ local call `call' (`e(factor`k')')
+ local ++k
+ }
+
+ * the first call and resetting the from vector
+ cap confa `call' , from(`bb') `confaoptions'
+ if _rc {
+ di as err "cannot execute confa with rotated data only"
+ restore
+ qui est restore `confares'
+ cap est drop `confares'
+ exit 309
+ }
+ mat `bb' = e(b)
+ if ~strpos("`confaoptions'", "from") local from from(`bb')
+
+ * correlated errors?
+ * unit variance identification?
+
+ `safer' bootstrap _b (T: T = e(lr_u)) (reject: reject = (e(lr_u) > `T') ) , ///
+ reps(`reps') saving(`saving') notable noheader nolegend ///
+ reject( e(converged) == 0) `options' ///
+ : confa `call' , `from' `confaoptions'
+ * may need some other options, too!
+ nobreak if "`safer'"~="" & _rc {
+ * for whatever reason, the bootstrap broke down
+ qui use `pres' , clear
+ qui est restore `confares'
+ cap est drop `confares'
+ error _rc
+ }
+ * the covariance matrix should have been reposted by the -bootstrap-!
+
+ * we still need to trick Stata back into confa!
+ ereturn local cmd confa
+ }
+
+ else {
+ * what on earth was that?
+ error 301
+ }
+
+
+ * the bootstrap test on T
+ gettoken bsres blah : saving , parse(",")
+ * to strip off replace option, if there is any
+ qui use `bsres', clear
+ sum reject_reject, mean
+
+ local pBS = r(mean)
+ local BBS = r(N)
+
+ qui sum T_T, det
+ local q05 = r(p5)
+ local q95 = r(p95)
+
+ qui use `pres', clear
+ qui est restore `confares'
+ qui est drop `confares'
+
+ ereturn scalar p_u_BS = `pBS'
+ ereturn scalar B_BS = `BBS'
+* ereturn scalar lr_u = `T'
+* ereturn scalar p_u = chi2tail(e(df_u),e(lr_u))
+
+ ereturn scalar T_BS_05 = `q05'
+ ereturn scalar T_BS_95 = `q95'
+ ereturn local vce BollenStine
+ ereturn local vcetype Bollen-Stine
+
+ `e(cmd)'
+
+end
+
+cap mata: mata drop CONFA1_BSrotate()
+mata:
+void CONFA1_BSrotate(
+ string SigmaName, // the parameter matrix name
+ string varnames // the variable names
+ ) {
+
+ // declarations
+ real matrix data // views of the data
+ real matrix Sigma, SS, S2, SS2 // the covariance matrices and temp matrices
+ real matrix means // the means -- need modifications for weighted data!!!
+ real scalar p, n // dimension, no. obs
+
+ // get the data in
+ st_view(data=., ., tokens(varnames) )
+ n=rows(data)
+ p=cols(data)
+
+ Sigma = st_matrix(SigmaName)
+
+ // probability weights!!!
+ means = colsum(data)/n
+ SS = (cross(data,data)-n*means'*means)/(n-1)
+
+ S2 = cholesky(Sigma)
+ SS2 = cholesky(SS)
+ SS2 = solveupper(SS2',I(rows(SS)))
+
+ data[,] = data*SS2*S2'
+
+}
+
+end
+
+
+exit
+
+History:
+v.1.1 -- Jan 9, 2007
+v.1.2 -- Mar 26, 2008: confa1 options added; reject() added
+v.1.3 -- July 12, 2008: upgraded to confa
diff --git a/Modules/ado/plus/b/bollenstine.sthlp b/Modules/ado/plus/b/bollenstine.sthlp
new file mode 100644
index 0000000..4a98dbc
--- /dev/null
+++ b/Modules/ado/plus/b/bollenstine.sthlp
@@ -0,0 +1,88 @@
+{smcl}
+{* *! version 1.3 28Oct2008}{...}
+{cmd:help bollenstine} {right: ({browse "http://www.stata-journal.com/article.html?article=st0169":SJ9-3: st0169})}
+{hline}
+
+{title:Title}
+
+{p2colset 5 20 22 2}{...}
+{p2col :{hi:bollenstine} {hline 2}}Bollen-Stine bootstrap following confirmatory factor analysis
+{p2colreset}{...}
+
+
+{title:Syntax}
+
+{p 8 19 2}
+{cmd:bollenstine} [{cmd:,} {cmdab:r:eps(}{it:#}{cmd:) }
+{cmdab:sav:ing(}{it:filename}{cmd:) }
+{cmdab:confaopt:ions(}{it:string}{cmd:)}
+{it:bootstrap_options}]
+{p_end}
+
+
+{title:Description}
+
+{pstd}{cmd:bollenstine} performs the Bollen and Stine (1992) bootstrap
+following structural equation models (confirmatory factor analysis) estimation.
+The original data are rotated to conform to the fitted structure.
+By default, {cmd:bollenstine} refits the model
+with rotated data and uses the estimates as
+starting values in each bootstrap iteration. It also rejects samples
+where convergence was not achieved (implemented through the {cmd:reject(e(converged) == 0)} option supplied to
+{helpb bootstrap}).
+
+
+{title:Options}
+
+{phang}{cmd:reps(}{it:#}{cmd:)} specifies the number of bootstrap replications.
+The default is {cmd:reps(200)}.{p_end}
+
+{phang}{cmd:saving(}{it:filename}{cmd:)} specifies the file
+where the simulation results (the parameter estimates and the fit statistics)
+are to be stored. The default is a temporary file that will
+be deleted as soon as {cmd:bollenstine} finishes.{p_end}
+
+{phang}{opt confaoptions(string)} allows the transfer of {cmd:confa}
+options to {cmd:bollenstine}. If nondefault model options ({cmd:unitvar()} and
+{cmd:correlated()}) were used, one would need to use them with
+{cmd:bollenstine} as well.
+
+{phang}All nonstandard model options, like {cmd:unitvar()} or {cmd:correlated()},
+must be specified with {cmd:bollenstine} to produce correct results!
+
+{phang}All other options are assumed to be {it:bootstrap_options}
+and passed through to {helpb bootstrap}.
+
+
+{title:Example}
+
+{phang2}{cmd:. use hs-cfa}{p_end}
+{phang2}{cmd:. confa (vis: x1 x2 x3) (text: x4 x5 x6) (math: x7 x8 x9), from(iv) correlated(x7:x8)}{p_end}
+{phang2}{cmd:. set seed 10101}{p_end}
+{phang2}{cmd:. bollenstine, reps(200) confaoptions(iter(20) corr(x7:x8))}
+
+
+{title:Reference}
+
+{phang}{bind:}Bollen, K., and R. Stine. 1992.
+Bootstrapping goodness-of-fit measures in structural
+equation models. {it:Sociological Methods and Research} 21: 205-229.
+{p_end}
+
+
+{title:Author}
+
+{pstd}Stanislav Kolenikov{p_end}
+{pstd}Department of Statistics{p_end}
+{pstd}University of Missouri{p_end}
+{pstd}Columbia, MO{p_end}
+{pstd}kolenikovs@missouri.edu{p_end}
+
+
+{title:Also see}
+
+{psee}
+Article: {it:Stata Journal}, volume 9, number 3: {browse "http://www.stata-journal.com/article.html?article=st0169":st0169}
+
+{psee}Online: {helpb confa}, {helpb confa_estat:confa postestimation},
+{helpb bootstrap} (if installed){p_end}
diff --git a/Modules/ado/plus/b/bothlist.ado b/Modules/ado/plus/b/bothlist.ado
new file mode 100644
index 0000000..4976dc9
--- /dev/null
+++ b/Modules/ado/plus/b/bothlist.ado
@@ -0,0 +1,89 @@
+program def bothlist, rclass
+*! NJC 1.3.0 6 June 2000
+* NJC 1.2.0 31 Jan 2000
+* NJC 1.1.0 22 Dec 1999
+* NJC 1.0.0 21 Dec 1999
+ version 6.0
+ gettoken lists 0 : 0, parse(",")
+ if "`lists'" == "" | "`lists'" == "," { /* no \ */
+ di in r "incorrect syntax: no separator"
+ exit 198
+ }
+
+ tokenize "`lists'", parse("\")
+ if "`4'" != "" {
+ di in r "incorrect syntax: too much stuff"
+ exit 198
+ }
+ if "`1'" == "\" { /* list1 empty */
+ if "`2'" == "\" {
+ di in r "incorrect syntax: one \ only"
+ exit 198
+ }
+ local list2 "`2'" /* might be empty */
+ }
+ else if "`2'" == "\" {
+ local list1 "`1'"
+ local list2 "`3'" /* might be empty */
+ }
+ else {
+ di in r "incorrect syntax: what to compare?"
+ exit 198
+ }
+
+ syntax [ , Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ * remove duplicates from `list1'
+
+ tokenize `list1'
+ local list1 "`1'"
+ mac shift
+
+ while "`1'" != "" {
+ local n1 : word count `list1'
+ local i = 1
+ local putin = 1
+ while `i' <= `n1' {
+ local word : word `i' of `list1'
+ if "`word'" == "`1'" {
+ local putin = 0
+ local i = `n1'
+ }
+ local i = `i' + 1
+ }
+ if `putin' { local list1 "`list1' `1'" }
+ mac shift
+ }
+
+ * what is in both lists?
+
+ local n1 : word count `list1'
+ tokenize `list1'
+ local n2 : word count `list2'
+
+ local i = 1
+ while `i' <= `n1' {
+ local j = 1
+ local putin = 0
+ while `j' <= `n2' {
+ local word : word `j' of `list2'
+ if "`word'" == "``i''" {
+ local putin = 1
+ local j = `n2'
+ }
+ local j = `j' + 1
+ }
+ if `putin' { local newlist "`newlist' ``i''" }
+ local i = `i' + 1
+ }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
+
diff --git a/Modules/ado/plus/b/bothlist.hlp b/Modules/ado/plus/b/bothlist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/b/bothlist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/b/brant.ado b/Modules/ado/plus/b/brant.ado
new file mode 100644
index 0000000..fc547a7
--- /dev/null
+++ b/Modules/ado/plus/b/brant.ado
@@ -0,0 +1,297 @@
+*! version 1.6.0 3/29/01
+
+capture program drop brant
+program define brant, rclass
+version 6
+ tempvar touse
+ tempname bout d pvals ivchi ivout step1 step2 ologit
+ tempname XpWmmX iXpWmmX XpWmlX XpWllX iXpWllX DB DBp iDvBDp
+ syntax [, detail]
+
+ if "`e(cmd)'"!="ologit" {
+ di in r "brant can only be used after ologit"
+ exit
+ }
+
+ *to make output stata 6 or stata 7 compatible
+ cap version 7
+ if _rc!=0 {
+ local vers7 "no"
+ local smcl ""
+ local dash "-"
+ local vline "|"
+ local plussgn "+"
+ local topt "-"
+ local bottomt "-"
+ }
+ else { local vers7 "yes"
+ local smcl "in smcl "
+ local dash "{c -}"
+ local vline "{c |}"
+ local plussgn "{c +}"
+ local topt "{c TT}"
+ local bottomt "{c BT}"
+ }
+ version 6.0
+
+ local ocmd "`e(cmd)'"
+ if "`ocmd'"=="ologit" { local bcmd "logit" }
+ local depvar "`e(depvar)'"
+ gen `touse' = e(sample)
+ local wtis ""
+ if "`e(wtype)'"!="" {
+ di in r "-brant- does not work with ologit models with weights"
+ error 999
+ }
+ _perhs
+ local rhsnms "`r(rhsnms)'"
+ local nrhs "`r(nrhs)'"
+ _pecats
+ local numcats = `r(numcats)'
+ local catvals "`r(catvals)'"
+ local catnms "`r(catnms)'"
+ local catnms8 "`r(catnms8)'"
+ estimates hold `ologit'
+
+*** estimate series of binary logits
+ local i = 1
+ while `i' <= `numcats'-1 {
+ local splitat : word `i' of `catvals'
+ tempvar dummy
+ quietly gen `dummy' = 0 if `depvar' <= `splitat' & `touse'==1
+ quietly replace `dummy' = 1 if `depvar' > `splitat' & `touse'==1
+ quietly `bcmd' `dummy' `rhsnms' `wtis' if `touse' == 1
+ _perhs
+ local binnrhs = "`r(nrhs)'"
+ if `nrhs' != `binnrhs' {
+ di in r "not all independent variables can be retained in all binary logits"
+ di in r "brant test cannot be computed"
+ exit 999
+ }
+ tempvar prob`i'
+ quietly predict `prob`i''
+ tempname b`i' V`i' bc`i'
+ mat `b`i'' = e(b)
+ mat `b`i'' = `b`i''[1, 1..`nrhs']
+ mat `V`i'' = e(V)
+ mat `V`i'' = `V`i''[1..`nrhs', 1..`nrhs']
+ mat `bc`i'' = e(b) /* with constant--for detail output only */
+ mat `bc`i'' = `bc`i'''
+ local outname "y>`splitat'"
+ local outname = substr("`outname'", 1, 8)
+ mat colnames `bc`i'' = "`outname'"
+ mat `bout' = nullmat(`bout'), `bc`i''
+ local i = `i' + 1
+ }
+
+*** make variables for W(ml) matrices
+ local i = 1
+ while `i' <= `numcats'-1 {
+ local i2 = `i'
+ while `i2' <= `numcats'- 1 {
+ tempvar w`i'_`i2'
+ quietly gen `w`i'_`i2'' = `prob`i2'' - (`prob`i''*`prob`i2'')
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+*** calculate variance Bm, Bl
+ local i = 1
+ while `i' <= `numcats'-1 {
+ local i2 = `i'
+ while `i2' <= `numcats'- 1 {
+ quietly {
+ * inverse(X'W(mm)X)
+ matrix accum `XpWmmX' = `rhsnms' [iw=`w`i'_`i''] if `touse'==1
+ matrix `iXpWmmX' = inv(`XpWmmX')
+ * X'W(ml)X
+ matrix accum `XpWmlX' = `rhsnms' [iw=`w`i'_`i2''] if `touse'==1
+ * inverse(X'W(ll)X)
+ matrix accum `XpWllX' = `rhsnms' [iw=`w`i2'_`i2''] if `touse'==1
+ matrix `iXpWllX' = inv(`XpWllX')
+ * product of three matrices
+ matrix `step1' = `iXpWmmX' * `XpWmlX'
+ tempname vb`i'_`i2'
+ matrix `vb`i'_`i2'' = `step1' * `iXpWllX'
+ }
+ mat `vb`i'_`i2''= `vb`i'_`i2''[1..`nrhs',1..`nrhs']
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+ * define var(B) matrix
+ local i = 1
+ while `i' <= `numcats'-1 {
+ tempname row`i'
+ local i2 = 1
+ while `i2' <= `numcats'- 1 {
+ quietly {
+ if `i'==`i2' { mat `row`i'' = nullmat(`row`i''), `V`i'' }
+ if `i'<`i2' { mat `row`i'' = nullmat(`row`i'') , `vb`i'_`i2'' }
+ if `i'>`i2' { mat `row`i'' = nullmat(`row`i'') , `vb`i2'_`i''' }
+ }
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+ * combine matrices
+ tempname varb
+ local i = 1
+ while `i' <= `numcats'-1 {
+ mat `varb' = nullmat(`varb') \ `row`i''
+ local i = `i' + 1
+ }
+ * make beta vector
+ tempname bstar
+ local i = 1
+ while `i' <= `numcats'-1 {
+ mat `bstar' = nullmat(`bstar') , `b`i''
+ local i = `i' + 1
+ }
+ mat `bstar' = `bstar''
+
+ * create design matrix for wald test; make I, -I, and 0 matrices
+ tempname id negid zero
+ local dim = `nrhs'
+ mat `id' = I(`dim')
+ mat rownames `id' = `rhsnms'
+ mat colnames `id' = `rhsnms'
+ mat `negid' = -1*`id'
+ mat rownames `negid' = `rhsnms'
+ mat colnames `negid' = `rhsnms'
+ mat `zero' = J(`dim', `dim', 0)
+ mat rownames `zero' = `rhsnms'
+ mat colnames `zero' = `rhsnms'
+ * dummy matrix
+ local i = 1
+ while `i' <= `numcats'-2 {
+ tempname drow`i'
+ local i2 = 1
+ while `i2' <= `numcats'- 1 {
+ quietly {
+ tempname feed
+ if `i2'==1 { mat `feed' = `id' }
+ else if `i2'-`i'==1 { mat `feed' = `negid' }
+ else { mat `feed' = `zero' }
+ mat `drow`i'' = nullmat(`drow`i'') , `feed'
+ }
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+ * combine matrices
+ local i = 1
+ while `i' <= `numcats'-2 {
+ mat `d' = nullmat(`d') \ `drow`i''
+ local i = `i' + 1
+ }
+
+ * terms of wald test
+ mat `DB' = `d' * `bstar'
+ mat `DBp' = `DB''
+ mat `step1' = `d'*`varb'
+ mat `step2' = `step1' * (`d'')
+ mat `iDvBDp' = inv(`step2')
+
+*** calculate wald stat
+ tempname step1 wald waldout pout dfout
+ mat `step1' = `DBp' * `iDvBDp'
+ mat `wald' = `step1' * `DB'
+ sca `waldout' = `wald'[1,1]
+ sca `dfout' = `nrhs'*(`numcats'-2)
+ sca `pout' = chiprob(`dfout', `waldout')
+ tempname dtemp vbtemp bstemp
+ local i = 1
+ while `i' <= `nrhs' {
+ tempname d`i' vb`i' bstar`i'
+ local i2 = 1
+ while `i2' <= `numcats'-1 {
+ local row = ((`nrhs')*(`i2'-1)) + (`i')
+ tempname drow vbrow
+ local i3 = 1
+ while `i3' <= `numcats'-1 {
+ local column = ((`nrhs')*(`i3'-1)) + (`i')
+ if (`i2'<`numcats'-1) {
+ mat `dtemp' = `d'[`row',`column']
+ mat `drow' = nullmat(`drow') , `dtemp'
+ }
+ mat `vbtemp' = `varb'[`row',`column']
+ mat `vbrow' = nullmat(`vbrow') , `vbtemp'
+ local i3 = `i3' + 1
+ }
+ if (`i2'<`numcats'-1) { mat `d`i'' = nullmat(`d`i'') \ `drow' }
+ mat `vb`i'' = nullmat(`vb`i'') \ `vbrow'
+ mat `bstemp' = `bstar'[`row', 1]
+ mat `bstar`i'' = nullmat(`bstar`i'') \ `bstemp'
+ local i2 = `i2' + 1
+ }
+ local i = `i' + 1
+ }
+
+*** wald test for each independent variable
+ tempname waldiv
+ local i = 1
+ while `i' <= `nrhs' {
+ tempname DB DBp iDvBDp step1 step2
+ mat `DB' = `d`i'' * `bstar`i''
+ mat `DBp' = `DB''
+ mat `step1' = `d`i''*`vb`i''
+ mat `step2' = `step1' * (`d`i''')
+ mat `iDvBDp' = inv(`step2')
+ tempname step1 wald`i'
+ mat `step1' = `DBp' * `iDvBDp'
+ mat `wald`i'' = `step1' * `DB'
+ mat `waldiv' = nullmat(`waldiv') \ `wald`i''
+ local i = `i' + 1
+ }
+
+ if "`detail'"!="" {
+ di _n in gr "Estimated coefficients from j-1 binary regressions"
+ mat list `bout', noheader
+ }
+
+ di _n in g "Brant Test of Parallel Regression Assumption"
+ di _n `smcl' in g " Variable `vline' chi2 p>chi2 df"
+ di `smcl' _dup(13) in g "`dash'" "`plussgn'" _dup(26) in g "`dash'"
+ di `smcl' in g " All `vline'" in y /*
+ */ %10.2f `waldout' %9.3f `pout' %6.0f `dfout'
+ di `smcl' _dup(13) in g "`dash'" "`plussgn'" _dup(26) in g "`dash'"
+ * calculate p for individual wald tests
+ mat `pvals' = J(`nrhs', 1, 0)
+ local i = 1
+ local df = `numcats'-2
+ while `i' <= `nrhs' {
+ sca `ivchi' = `waldiv'[`i',1]
+ if `ivchi' >= 0 {
+ mat `pvals'[`i',1] = chiprob(`df',`ivchi')
+ }
+ if `ivchi' < 0 {
+ mat `pvals'[`i',1] = -999
+ }
+ local vnm : word `i' of `rhsnms'
+
+ *added for stata 7 compatibility
+ local printnm "`vnm'"
+ if "`vers7'"=="yes" { local printnm = abbrev("`printnm'", 12) }
+
+ di `smcl' in g %12s "`printnm'" _col(14) "`vline'" in y /*
+ */ %10.2f `ivchi' %9.3f `pvals'[`i',1] %6.0f `df'
+ local i = `i' + 1
+ }
+ di `smcl' _dup(13) in g "`dash'" "`bottomt'" _dup(26) in g "`dash'"
+ di _n in g /*
+ */ "A significant test statistic provides evidence that the parallel"
+ di in g "regression assumption has been violated."
+ mat `ivout' = `waldiv', `pvals'
+ mat rownames `ivout' = `rhsnms'
+ mat colnames `ivout' = chi2 p>chi2
+ estimates unhold `ologit'
+ return scalar chi2 = `waldout'
+ return scalar p = `pout'
+ return scalar df = `dfout'
+ return matrix ivtests `ivout'
+end
diff --git a/Modules/ado/plus/b/brant.hlp b/Modules/ado/plus/b/brant.hlp
new file mode 100644
index 0000000..5eff2e6
--- /dev/null
+++ b/Modules/ado/plus/b/brant.hlp
@@ -0,0 +1,54 @@
+.-
+help for ^brant^ - 1.0.1 - 11/26/00
+.-
+
+Perform Brant test of parallel regression assumption after @ologit@
+------------------------------------------------------------
+
+ ^brant^ [^,^ ^detail^]
+
+
+^brant^ is for use after ^ologit^; see help @ologit@.
+
+
+Description
+-----------
+
+^brant^ performs a Brant test of the parallel regression assumption (also
+called the proportional odds assumption) after ologit. The test compares
+slope coefficients of the J-1 binary logits implied by the ordered regression
+model. Stata reports both the results of an omnibus test for the entire
+model and tests of the assumption for each of the independent variables in
+the model.
+
+The Brant test can only be computed if all of the independent variables in
+the ordered model are retained in all of the implied binary models. This
+is most likely not to be the case with models that have few observations in
+the extreme categories and many independent variables.
+
+Options
+-------
+
+^detail^ specifies that the coefficients for each of the estimated binary
+logits should be presented.
+
+Example
+-------
+
+ . ^ologit warm yr89 male white age ed prst^
+ . ^brant^
+
+ . ^ologit warm yr89 male white age ed prst^
+ . ^brant, detail^
+
+Also see
+--------
+
+ Manual: ^[R] ologit^
+
+.-
+Authors: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
+
+
diff --git a/Modules/ado/plus/backup.trk b/Modules/ado/plus/backup.trk
new file mode 100644
index 0000000..370b899
--- /dev/null
+++ b/Modules/ado/plus/backup.trk
@@ -0,0 +1,1402 @@
+* 00000057
+*! version 1.0.0
+* Do not erase or edit this file
+* It is used by Stata to track the ado and help
+* files you have installed.
+
+S http://www.unc.edu/~skolenik/stata
+N polychoric.pkg
+D 15 Dec 2006
+U 1
+d polychoric -- The polychoric correlation package
+d
+d Author: Stas Kolenikov, skolenik@unc.edu
+d
+d This package provides routines to estimate
+d the polychoric, tetrachoric, polyserial and biserial
+d correlations and use them in principal component analysis.
+d Current version: 1.4
+f p\polychoric.ado
+f p\polychoricpca.ado
+f p\polych_ll.ado
+f p\polyser_ll.ado
+f p\polychoric.hlp
+f p\polychoricpca.hlp
+e
+S http://www.stata.com/stb/stb61
+N sg158_1.pkg
+D 5 Mar 2007
+U 3
+d STB-61 sg158_1. Update to random-effects ordered probit
+d STB insert by Guillaume R. Frechette, Ohio State University
+d Support: gurst1@@econ.ohio-state.edu
+d After installation, see help ^reoprob^
+f g\ghquadm.ado
+f g\ghquadm.hlp
+f r\reop_ll.ado
+f r\reopc_ll.ado
+f r\reoprob.ado
+f r\reoprob.hlp
+f r\rfpr_ll1.ado
+f r\rfprobit.ado
+f r\rfprobit.hlp
+e
+S http://www.stata-journal.com/software/sj5-4
+N st0067_2.pkg
+D 5 Jun 2007
+U 4
+d SJ5-4 st0067_2. Update: Multiple imputation of missing...
+d Update: Multiple imputation of missing values
+d by Patrick Royston, MRC Clinical Trials Unit, London, UK
+d Support: patrick.royston@@ctu.mrc.ac.uk
+d After installation, type help ^ice^, ^micombine^, and ^mijoin^
+f i\ice.ado
+f i\ice.hlp
+f m\micombine.ado
+f m\micombine.hlp
+f m\mijoin.ado
+f m\mijoin.hlp
+f m\misplit.ado
+f m\misplit.hlp
+f u\uvis.ado
+f u\uvis.hlp
+f c\cmdchk.ado
+e
+S http://fmwww.bc.edu/repec/bocode/m
+N metaninf.pkg
+D 10 Jan 2008
+U 7
+d 'METANINF': module to evaluate influence of a single study in meta-analysis estimation
+d
+d metaninf investigates the influence of each individual study on
+d the overall meta-analysis summary estimate. The command presents
+d a table and a graph of the results of an influence analysis in
+d which the meta-analysis is reestimated omitting each study in
+d turn. metaninf is a parallel program to metainf (Aurelio Tobias;
+d STB-47: sbe26; STB-56: sbe26.1) that uses metan (rather than
+d meta) as its calculation engine, thus allowing access to the
+d additional meta-analytic models offered therein. metaninf also
+d differs from metainf in that metaninf uses metan's syntax and a
+d subset of its options (rather than those of meta). Program mhplot
+d (a variation of Nicholas Cox's hplot) is a required support
+d program. This version (1.0.2) allows the jackknifed estimates to
+d be saved. A Stata 8 dialog is included.
+d
+d Distribution-Date: 20010619
+d
+d Author: Thomas Steichen
+d Support: email steichen@@triad.rr.com
+d
+f m\metaninf.ado
+f m\metaninf.hlp
+f m\mhplot.ado
+f m\metaninf.dlg
+e
+S http://fmwww.bc.edu/repec/bocode/m
+N metafunnel.pkg
+D 2 Apr 2008
+U 8
+d 'METAFUNNEL': module to produce funnel plots for meta-analysis
+d
+d metafunnel plots funnel plots. These graphical displays are
+d used to examine whether the results of a meta-analysis may have
+d been affected by publication or other types of bias.
+d
+d Distribution-Date: 20030827
+d
+d Author: Jonathan Sterne, University of Bristol
+d Support: email jonathan.sterne@@bristol.ac.uk
+d
+f m\metafunnel.ado
+f m\metafunnel.hlp
+f m\metafunnel.dlg
+e
+S http://fmwww.bc.edu/repec/bocode/m
+N metabias.pkg
+D 2 Apr 2008
+U 9
+d 'METABIAS': module to test for publication bias in meta-analysis
+d
+d metabias performs the Begg and Mazumdar adjusted rank correlation
+d test for publication bias and performs the Egger et al.
+d regression asymmetry test for publication bias. As options, it
+d provides a funnel graph of the data or the regression asymmetry
+d plot. This is version 1.2.4 of the software. This version has
+d been modified to run correctly under Stata Version 7 and later
+d (though it remains a version 6 program) and fixes a bug in the
+d stratified Egger p-value.
+d
+d Author: Thomas Steichen
+d Support: email steichen@@triad.rr.com
+d
+d Distribution-Date: 20040409
+f m\metabias.ado
+f m\metabias.hlp
+f m\metabias.dlg
+e
+S http://www.stata.com/stb/stb56
+N sbe20_1.pkg
+D 2 Apr 2008
+U 10
+d STB-56 sbe20_1. Update of galbr
+d STB insert by Aurelio Tobias, Universidad Miguel Hernandez
+d Alicante, Spain
+d Support: bledatobias@@ctv.es
+d After installation, see help ^galbr^
+f g\galbr.ado
+f g\galbr.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/l
+N loevh.pkg
+D 6 Nov 2008
+U 11
+d 'LOEVH': module to compute Guttman errors and Loevinger H coefficients
+d
+d LoevH computes the Loevinger H coefficients and the Guttman
+d errors (observed and expected) for each pair of items, between
+d one given item and all the others of a scale or among all the
+d possible pairs of items of a scale.
+d
+d KW: Loevinger H coefficients
+d KW: Guttman errors
+d KW: scale validation
+d
+d Requires: Stata version 7
+d
+d Distribution-Date: 20070621
+d
+d Author: Jean-Benoit Hardouin, University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f l\loevh.ado
+f l\loevh.hlp
+f a\anaoption.ado
+f t\traces.ado
+f t\traces.hlp
+f g\gengroup.ado
+f g\gengroup.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/d
+N delta.pkg
+D 24 Nov 2008
+U 13
+d 'DELTA': module to compute the Delta index of scale discrimination
+d
+d delta computes the generalized delta index of scale
+d discrimination developed by Hankins (2007) based on the original
+d work of Ferguson (1949). This index measures the scale's
+d ability to distinguish between individuals. A value of 1
+d indicates that the test has maximal discrimination (all
+d possible scores occur with the same frequency) and a value of 0
+d means that the test has minimal discrimination (all the
+d respondents have the same score). A value of 0.9 results from a
+d set of scores that is normally distributed. A value of 1 is
+d observed if the scores follow a uniform distribution. Individuals
+d with a missing score are omitted.
+d
+d KW: delta index
+d KW: psychometrics
+d KW: Cronbach alpha
+d KW: discrimination
+d
+d Requires: Stata version 7
+d
+d Distribution-Date: 20080312
+d
+d Author: Jean-Benoit Hardouin , University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f d\delta.ado
+f d\delta.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/m
+N metan.pkg
+D 3 Dec 2008
+U 15
+d 'METAN': module for fixed and random effects meta-analysis
+d
+d These routines provide facilities to conduct meta-analyses of
+d data from more than one study and to graph the results. Either
+d binary (event) or continuous data from two groups may be combined
+d using the metan command. Additionally, intervention effect
+d estimates with corresponding standard errors or confidence
+d intervals may be meta-analysed. Recently added facilities include
+d by() processing and an update to Stata 9 graphics. This is an
+d updated version of metan as published in STB-44, authored by
+d Michael J Bradburn, Jonathan J Deeks, Douglas G Altman. The
+d package includes a command to produce funnel plots to assess
+d small study effects, and L'Abbe plots to examine whether the
+d assumption of a common odds ratio, risk ratio or risk difference
+d is reasonable. Also included is the metannt program for binary
+d data, which displays estimated intervention effects in terms of
+d the absolute reduction in risk and number needed to treat. A
+d description of available Stata meta-analysis commands may be
+d found at http://www.stata.com/support/faqs/stat/meta.html.
+d
+d KW: meta-analysis
+d KW: fixed effects
+d KW: random effects
+d KW: forest plot
+d KW: l'Abbe plot
+d
+d Requires: Stata version 9 (version 7 for metan7)
+d
+d Distribution-Date: 20081117
+d
+d Author: Ross Harris, Department of Social Medicine, University of Bristol
+d Support: email ross.harris@@bristol.ac.uk
+d
+d Author: Mike Bradburn, Centre for Statistics in Medicine, University of Oxford
+d Support: email
+d
+d Author: Jon Deeks, Centre for Statistics in Medicine, University of Oxford
+d Support: email
+d
+d Author: Roger Harbord, Department of Social Medicine, University of Bristol
+d Support: email
+d
+d Author: Doug Altman, Centre for Statistics in Medicine, University of Oxford
+d Support: email
+d
+d Author: Thomas Steichen, RJRT
+d Support: email
+d
+d Author: Jonathan Sterne, Department of Social Medicine, University of Bristol
+d Support: email
+d
+f m\metan.ado
+f m\metan.hlp
+f l\labbe.ado
+f l\labbe.hlp
+f l\labbe.dlg
+f m\metan7.ado
+f m\metan7.hlp
+f m\metan7.dlg
+f m\metannt.ado
+f m\metannt.hlp
+f m\metannt.dlg
+f i\i2ci.ado
+f m\metan_examples.ado
+e
+S http://fmwww.bc.edu/repec/bocode/m
+N msp.pkg
+D 11 Dec 2008
+U 16
+d 'MSP': module to perform the Mokken Scale Procedure
+d
+d MSP implements the Mokken Scale Procedure defined by Hemker,
+d Sijtsma and Molenaar (1995). This procedure construct sub-scales
+d based on Loevinger H coefficients computed by LoevH (q.v.). The
+d results depend of a threshold "c" fixed by the user : the
+d authors of the procedure recommend to use a c exceeding 0.3. The
+d kernel of the first sub-scale can be fixed.
+d
+d KW: Mokken Scale Procedure
+d KW: MSP
+d KW: Loevinger H coefficients
+d KW: scale construction
+d
+d Requires: Stata version 7
+d
+d Distribution-Date: 20081108
+d
+d Author: Jean-Benoit Hardouin, University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f m\msp.ado
+f m\msp.hlp
+f l\loevh.ado
+f l\loevh.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/c
+N clv.pkg
+D 11 Dec 2008
+U 17
+d 'CLV': module to implement a clustering of variables around latent components
+d
+d clv clusters variables around latent components. The variables
+d are clustered by searching to minimize at each step the
+d decreasing of the T criterion computed as the sum of the first
+d eigenvalues of the matrices of data of all the clusters. A
+d hierarchical cluster analysis based on this criterion is
+d realized. A consolidation procedure can be run in a second time,
+d which allows assigning each variable to the more correlated
+d latent components. The procedure is described by Vigneau and
+d Qannari (Communications in Statistics - Simulation and
+d Computation, 2003).
+d
+d KW: Clustering around latent components
+d KW: Varclus
+d KW: CLV
+d KW: unidimensionality
+d
+d Requires: Stata version 8.0
+d
+d Distribution-Date: 20061014
+d
+d Author: Jean-Benoit Hardouin , University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f c\clv.ado
+f c\clv.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/s
+N simirt.pkg
+D 11 Dec 2008
+U 18
+d 'SIMIRT': module to process data generated by IRT models
+d
+d simirt allows creating a new dataset of responses to items
+d simulated by an unidimensional IRT model. The model can be
+d dichotomous (Rasch, OPLM, Birnbaum, 3PLM, 4PLM, 5PAM) or
+d polytomous (Rating Scale Model-RSM). It is possible to simulate
+d two sets of items linked, for each of them, to a specific latent
+d trait (which can be correlated). The Items Characteristic Curves
+d can be drawn.
+d
+d KW: simulation
+d KW: Rasch model
+d KW: Birnbaum model
+d KW: OPLM
+d KW: ICC
+d KW: Rating Scale Model
+d
+d Requires: Stata version 8
+d
+d Distribution-Date: 20061022
+d
+d Author: Jean-Benoit Hardouin, University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f s\simirt.ado
+f s\simirt.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/e
+N elapse.pkg
+D 11 Dec 2008
+U 19
+d 'ELAPSE': module to calculate elapsed time in procedure
+d
+d Elapse displays a string with the name of the operation, if
+d specified, and the time elapsed between start_time and current
+d time.
+d
+d Author: Fred Zimmerman, Stanford University
+d Support: email zimmer@@leland.Stanford.EDU
+d
+d Distribution-Date: 20031221
+f e\elapse.ado
+f e\elapse.hlp
+e
+S http://fmwww.bc.edu/RePEc/bocode/i
+N iccconf.pkg
+D 5 Feb 2009
+U 20
+d 'ICCCONF': module to compute a confidence interval for an intraclass correlation (ICC)
+d
+d iccconf is an immediate command that computes a confidence
+d interval for a single intraclass correlation (ICC). The
+d procedure is based on Rosner's approach using the F-test.
+d
+d KW: intra-class correlation
+d KW: confidence interval
+d
+d Requires: Stata version 8
+d
+d Distribution-Date: 20081119
+d
+d Author: Paul F. Visintainer, Baystate Health System
+d Support: email visint46@@gmail.com
+d
+f i\iccconf.ado
+f i\iccconf.hlp
+e
+S http://www.stata-journal.com/software/sj4-2
+N pr0012.pkg
+D 24 Feb 2009
+U 22
+d SJ4-2 pr0012. Submenu and dialogs for meta-analysis commands
+d Submenu and dialogs for meta-analysis commands
+d by Thomas J. Steichen
+d Support: steichen@@triad.rr.com
+d After installation, type help ^meta_dialog^
+f m\meta_dialog.hlp
+f f\funnel.dlg
+f g\galbr.dlg
+f l\labbe.dlg
+f m\metabias.dlg
+f m\metacum.dlg
+f m\meta.dlg
+f m\metafunnel.dlg
+f m\metainf.dlg
+f m\metan.dlg
+f m\metaninf.dlg
+f m\metannt.dlg
+f m\metap.dlg
+f m\metareg.dlg
+f m\metatrim.dlg
+e
+S http://www.stata-journal.com/software/sj8-4
+N sbe23_1.pkg
+D 24 Feb 2009
+U 23
+d SJ8-4 sbe23_1. Update: Meta-regression in Stata (revised)
+d Update: Meta-regression in Stata (revised)
+d by Roger Harbord, Department of Social Medicine,
+d University of Bristol, UK
+d Julian Higgins, MRC Biostatistics Unit, Cambridge, UK
+d Support: roger.harbord@@bristol.ac.uk
+d After installation, type help ^metareg^
+f m\metareg.ado
+f m\metareg_ll.ado
+f m\metareg_p.ado
+f m\metareg_pm.ado
+f m\metareg.hlp
+e
+S http://web.missouri.edu/~kolenikovs/stata
+N cfa1.pkg
+D 20 Mar 2009
+U 24
+d cfa1 -- a single factor confirmatory analysis model
+d
+d Author: Stas Kolenikov, kolenikovs@missouri.edu
+d
+d cfa1 fits the confirmatory analysis model by maximum likelihood.
+d The model is restricted to a single level single factor.
+f c\cfa1.ado
+f c\cfa1_lf.ado
+f c\cfa1.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/i
+N icc23.pkg
+D 26 Mar 2009
+U 25
+d 'ICC23': module that computes models 2 and 3 of the intra-class correlation
+d
+d ICC23 computes the intra-class correlation for random effects
+d models 2 and 3, as described by Shrout and Fleiss, 1979.
+d (-loneway- computes model 1). The module uses StataÂs repeated
+d measures ANOVA command to retrieve the appropriate estimates and
+d degrees of freedom. Keywords: intra-class correlation, random
+d effects model, mixed effects model
+d
+d
+d Requires: Stata version 9
+d
+d Distribution-Date: 20090325
+d
+d Author: Paul F. Visintainer, Baystate Health System
+d Support: email visint46@@gmail.com
+d
+d Author: Luis C.Orozco, Facultad de Salud, Universidad Industrial de Santander, Colombia
+d Support: email lcorovar@@gmail.com
+d
+f i\icc23.ado
+f i\icc23.hlp
+e
+S http://www.stata.com/stb/stb35
+N sg65.pkg
+D 26 Mar 2009
+U 26
+d STB-35 sg65. Computing intraclass correlations and large ANOVAs.
+d STB insert by John R. Gleason, Syracuse University.
+d Support: 73241.717@@compuserve.com
+d After installation, see help ^l1way^ and help ^iclassr2^.
+f i\iclassr.ado
+f i\iclassr.hlp
+f i\iclassr2.ado
+f i\iclassr2.hlp
+f l\l1way.ado
+f l\l1way.hlp
+e
+S http://www.stata.com/stb/stb56
+N sbe26_1.pkg
+D 20 Apr 2009
+U 27
+d STB-56 sbe26_1. Update of metainf
+d STB insert by Aurelio Tobias, Universidad Miguel Hernandez
+d Alicante, Spain
+d Support: bledatobias@@ctv.es
+d After installation, see help ^metainf^
+f h\hplot.ado
+f h\hplot.hlp
+f m\metainf.ado
+f m\metainf.hlp
+e
+S http://www.stata.com/stb/stb61
+N sbe19_4.pkg
+D 20 Apr 2009
+U 28
+d STB-61 sbe19_4. Update to metabias to work under version 7
+d STB insert by Thomas J. Steichen, RJRT
+d Support: steicht@@rjrt.com
+d After installation, see help ^metabias^
+f m\metabias.ado
+f m\metabias.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/i
+N imputeitems.pkg
+D 5 May 2009
+U 29
+d 'IMPUTEITEMS': module to impute missing data of binary items
+d
+d imputeitems imputes missing responses to binary items by
+d different ways: Item Mean Substitution (IMS), Person Mean
+d Substitution (PMS), Corrected Item Mean Substiutution (CIM),
+d Interitem Correlation Substitution (ICS), logistic model (LOG)
+d and Worst Case (WORST).
+d
+d KW: Item Response Theory
+d KW: Missing data
+d KW: Imputation
+d
+d Requires: Stata version 9.0
+d
+d Distribution-Date: 20081211
+d
+d Author: Jean-Benoit Hardouin, University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f i\imputeitems.ado
+f i\imputeitems.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/x
+N xsampsi.pkg
+D 16 Jul 2009
+U 30
+d 'XSAMPSI': module to calculate sample size for cross-over trials with continuous measures
+d
+d This program will compute the required sample size for a simple
+d crossover trial, that is AB/BA, or two-period two-treatment
+d cross-over. It will estimate the power for a given sample size,
+d too.
+d
+d Author: Jan Brogger, University of Bergen, Norway
+d Support: email jan.brogger@@med.uib.no
+d
+d Distribution-Date: 20020131
+f x\xsampsi.ado
+f x\xsampsi.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/n
+N nct.pkg
+D 17 Jul 2009
+U 31
+d 'NCT': modules related to the noncentral t distribution
+d
+d nct is a package of programs, all related to the noncentral t
+d distribution. Each one-sided program computes a missing
+d parameter given the other parameters such that P(t<=t'| delta,
+d df) = p. The two-sided programs yield two-sided values from a
+d noncentral t, defined such that P(|t|<=t'| delta, df) = 1 - p.
+d The programs are: nctprob -- Cumulative non-central t
+d probabilities, p, nctinv -- Inverse cumulative non-central t
+d values, t', nctncp -- Noncentrality parameter of the non-central
+d t, delta, nctn -- Sample size for the cumulative non-central
+d t, df + 1, nct2 -- 2-sided non-central t probabilities, p,
+d and nct2inv -- Inverse 2-sided non-central t values, |t'|.
+d
+d Author: Thomas Steichen
+d Support: email steichen@@triad.rr.com
+d
+d Distribution-Date: 20000609
+f n\nct.ado
+f n\nct.hlp
+f n\nct2.ado
+f n\nct2.hlp
+f n\nct2inv.ado
+f n\nct2inv.hlp
+f n\nctinv.ado
+f n\nctinv.hlp
+f n\nctn.ado
+f n\nctn.hlp
+f n\nctncp.ado
+f n\nctncp.hlp
+f n\nctprob.ado
+f n\nctprob.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/t
+N torumm.pkg
+D 20 Jul 2009
+U 32
+d 'TORUMM': module to produce data in RUMM format
+d
+d torumm converts and formats Stata data into 3 files required to
+d run RUMM 2010. RUMM 2010 (Rasch Unidimensional Measurement
+d Models) is program for Rasch analysis. torumm will work with
+d Stata 6 and Stata 7 data.
+d
+d Author: Fred Wolfe
+d Support: email fwolfe@@arthritis-research.org
+d
+d Distribution-Date: 20000708
+f t\torumm.ado
+f t\torumm.hlp
+e
+S http://www.fss.uu.nl/soc/iscore/stata
+N dropvars.pkg
+D 20 Jul 2009
+U 33
+d ^dropvars^. drops all existing variables in a list.
+d ^dropvars varlist^ is similar to ^drop varlist^, but warns if a
+d variable does not exists, rather than aborts.
+d
+d Note that ^capture drop varlist^ either drops all variables or none.
+d
+d ^dropvars varlist^ is equivalent to
+d
+d for var varlist: capture drop X
+d
+d Author: Jeroen Weesie, Dept of Sociology, Utrecht University (NL)
+d Support: email J.Weesie@@fss.uu.nl
+f d\dropvars.ado
+f d\dropvars.hlp
+e
+S http://fmwww.bc.edu/RePEc/bocode/l
+N listutil.pkg
+D 20 Jul 2009
+U 34
+d 'LISTUTIL': modules to manipulate lists of words
+d
+d These functions manipulate lists of words. For details, see the
+d help file.
+d
+d Author: Nicholas J. Cox, University of Durham
+d Support: email N.J.Cox@@durham.ac.uk
+d
+d Distribution-Date: 20010523
+f a\alphlist.ado
+f a\alphlist.hlp
+f b\binolist.ado
+f b\binolist.hlp
+f b\bothlist.ado
+f b\bothlist.hlp
+f c\choplist.ado
+f c\choplist.hlp
+f c\collist.ado
+f c\collist.hlp
+f c\convlist.ado
+f c\convlist.hlp
+f c\cseplist.ado
+f c\cseplist.hlp
+f c\cvarlist.ado
+f c\cvarlist.hlp
+f d\dellist.ado
+f d\dellist.hlp
+f d\difflist.ado
+f d\difflist.hlp
+f e\eqlist.ado
+f e\eqlist.hlp
+f f\fmtlist.ado
+f f\fmtlist.hlp
+f i\inslist.ado
+f i\inslist.hlp
+f j\joinlist.ado
+f j\joinlist.hlp
+f l\lclist.ado
+f l\lclist.hlp
+f m\maplist.ado
+f m\maplist.hlp
+f m\mnthlist.ado
+f m\mnthlist.hlp
+f p\poslist.ado
+f p\poslist.hlp
+f p\postlist.ado
+f p\postlist.hlp
+f p\prelist.ado
+f p\prelist.hlp
+f p\prodlist.ado
+f p\prodlist.hlp
+f r\replist.ado
+f r\replist.hlp
+f r\revlist.ado
+f r\revlist.hlp
+f r\rotlist.ado
+f r\rotlist.hlp
+f s\sellist.ado
+f s\sellist.hlp
+f s\seqlist.ado
+f s\seqlist.hlp
+f s\sortlist.ado
+f s\sortlist.hlp
+f s\sublist.ado
+f s\sublist.hlp
+f s\sumlist.ado
+f s\sumlist.hlp
+f t\takelist.ado
+f t\takelist.hlp
+f t\trnclist.ado
+f t\trnclist.hlp
+f u\uclist.ado
+f u\uclist.hlp
+f u\uniqlist.ado
+f u\uniqlist.hlp
+f v\varflist.ado
+f v\varflist.hlp
+f v\vectlist.ado
+f v\vectlist.hlp
+f w\wclist.ado
+f w\wclist.hlp
+f x\xorlist.ado
+f x\xorlist.hlp
+f l\listutil.hlp
+e
+S http://www.fss.uu.nl/soc/iscore/stata
+N listblck.pkg
+D 20 Jul 2009
+U 35
+d ^listblck^. variant of ^list^ that "wraps variables".
+d ^listblck^ is that wraps variables, not observations. Thus, ^listblck^
+d displays as many variables as fit on the screen (listblck is ^display^
+d ^linesize^ sensitive) for all selected obs, then it displays a second
+d block of variables etc. This is especially useful if the number of
+d observations to be listed is small. See ^listby^ as an application.
+d
+d Author: Jeroen Weesie, Dept of Sociology, Utrecht University (NL)
+d Support: email J.Weesie@@fss.uu.nl
+f l\listblck.ado
+f l\listblck.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/s
+N saswrapper.pkg
+D 22 Nov 2009
+U 37
+d 'SASWRAPPER': module to run a SAS program from within Stata
+d
+d saswrapper runs a SAS program in batch and prints the output in
+d the Stata results window/log file. This usually occurs by
+d specifying a SAS program file after using, but saswrapper can
+d also run SAS code specified by the pre_sas_prog() and/or
+d post_sas_prog() options. By default, saswrapper will save the
+d current data in memory using savasas and make it available in
+d SAS's WORK library. If that is not desired, use the nodata
+d option. The usesas option tells saswrapper to load the last SAS
+d dataset created in the WORK library by the submitted SAS program
+d into Stata using the SAVASTATA SAS macro.
+d
+d KW: SAS
+d KW: Stata
+d
+d Requires: Stata version 8.0
+d
+d Distribution-Date: 20090507
+d
+d Author: Dan Blanchette, Center of Entrepreneurship and Innovation, Duke University's Fuqua School of Business
+d Support: email dan.blanchette@@duke.edu
+d
+f s\saswrapper.ado
+f s\saswrapper.hlp
+f u\usesas.ado
+f u\usesas.hlp
+f s\savasas.ado
+f s\savasas.hlp
+f u\usesasdel.ado
+f s\sasexe.ado
+f a\adoedit.ado
+f a\adoedit.hlp
+f t\tmpdir.ado
+f t\tmpdir.hlp
+f s\shortdir.ado
+f s\shortdir.hlp
+f c\confirmdir.ado
+f c\confirmdir.hlp
+e
+S http://www.stata-journal.com/software/sj4-1
+N st0057.pkg
+D 26 Nov 2009
+U 38
+d SJ4-1 st0057. FIML estimation of an endogenous switching ...
+d FIML estimation of an endogenous switching model for count data
+d by Alfonso Miranda, Economics Department, Warwick University, UK
+d Support: Alfonso.Miranda-Caso-Luengo@@warwick.ac.uk
+d After installation, type help ^espoisson^
+f e\espoisson.ado
+f e\espoisson.hlp
+f e\espoisson_ll.ado
+f e\espoisson_p.ado
+f e\exspoisson.ado
+f e\exspoisson_ll.ado
+f e\exspoisson_p.ado
+f g\ghquad.ado
+f h\hermite.ado
+f x\xcolnames.ado
+e
+S http://fmwww.bc.edu/repec/bocode/e
+N estout.pkg
+D 5 Dec 2009
+U 39
+d 'ESTOUT': module to make regression tables
+d
+d estout produces a table of regression results from one or several
+d models for use with spreadsheets, LaTeX, HTML, or a
+d word-processor table. eststo stores a quick copy of the active
+d estimation results for later tabulation. esttab is a wrapper for
+d estout. It displays a pretty looking publication-style regression
+d table without much typing. estadd adds additional results to the
+d e()-returns for one or several models previously fitted and
+d stored. This package subsumes the previously circulated esto,
+d esta, estadd, and estadd_plus. An earlier version of estout is
+d available as estout1.
+d
+d KW: estimates
+d KW: LaTeX
+d KW: HTML
+d KW: word processor
+d KW: output
+d
+d Requires: Stata version 8.2
+d
+d Distribution-Date: 20091012
+d
+d Author: Ben Jann, ETH Zurich
+d Support: email ben.jann@@soz.gess.ethz.ch
+d
+f _\_eststo.ado
+f _\_eststo.hlp
+f e\estadd.ado
+f e\estadd.hlp
+f e\estout.ado
+f e\estout.hlp
+f e\eststo.ado
+f e\eststo.hlp
+f e\estpost.ado
+f e\estpost.hlp
+f e\esttab.ado
+f e\esttab.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/o
+N outreg2.pkg
+D 5 Dec 2009
+U 40
+d 'OUTREG2': module to arrange regression outputs into an illustrative table
+d
+d outreg2 provides a fast and easy way to produce an illustrative
+d table of regression outputs. The regression outputs are produced
+d piecemeal and are difficult to compare without some type of
+d rearrangement. outreg2 automates this process by concatenating
+d the successive regression ouputs in a vertical format. The
+d resulting table is saved to the disk in ASCII format, which can
+d be read by other programs. outreg2 thus facilitates the
+d convertion of regression outputs to a standard format suitable
+d for inclusion in a scholarly publication. The functionality of
+d outreg2 is based on the earlier package outreg, by John Luke
+d Gallup. Unlike outreg, outreg2 is capable of writing LaTeX-format
+d tables, as well as ASCII, MS Word and MS Excel.
+d
+d KW: regression
+d KW: output
+d KW: tables
+d KW: tab-delimited output
+d KW: LaTeX
+d KW: Word
+d KW: Excel
+d
+d Requires: Stata version 7
+d
+d Distribution-Date: 20091118
+d
+d Author: Roy Wada
+d Support: email roywada@@hotmail.com
+d
+f o\outreg2.ado
+f o\outreg2_prf.ado
+f o\outreg2.hlp
+f s\shellout.ado
+f s\shellout.hlp
+f s\seeout.ado
+f s\seeout.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/r
+N raschpower.pkg
+D 27 Jan 2010
+U 41
+d 'RASCHPOWER': module to estimate power of the Wald test in order to compare the means of the latent trait in two groups of individuals
+d
+d raschpower allows estimating the power of the Wald test comparing
+d the means of two groups of patients in the context of the Rasch
+d model. The estimation is based on the estimation of the variance
+d of the difference of the means based on the Cramer-Rao lower
+d bound.
+d
+d KW: Rasch test
+d KW: power
+d KW: Wald test
+d
+d Requires: Stata version 11
+d
+d Distribution-Date: 20100126
+d
+d Author: Jean-Benoit Hardouin , University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f r\raschpower.ado
+f r\raschpower.hlp
+e
+S http://www.stata-journal.com/production
+N sjlatex.pkg
+D 24 Feb 2010
+U 42
+d sjlatex: LaTeX files for the Stata Journal
+d ^sjlatex^ contains the LaTeX document class and packages for the
+d Stata Journal.
+d
+d The ancillary files should be installed using the ^sjlatex^ command
+d from within Stata.
+d
+d Distribution-Date: 18feb2010
+f s\sjlatex.ado
+f s\sjlatex.hlp
+f s\sjlog_7.ado
+f s\sjlog.ado
+f s\sjlog.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/c
+N checkfor2.pkg
+D 11 Apr 2010
+U 43
+d 'CHECKFOR2': module to check whether a variable exists or not in a dataset
+d
+d checkfor2 is a routine to check for existence of a list of
+d variables within a (usually big) data set. checkfor2 searchs
+d through the data whether the variable exists.
+d
+d KW: data management
+d
+d Requires: Stata version 8
+d
+d Distribution-Date: 20050926
+d
+d Author: Amadou Bassirou Diallo, AFTPM, The World Bank
+d Support: email adiallo5@@worldbank.org
+d
+d Author: Jean-Benoit Hardouin , University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f c\checkfor2.ado
+f c\checkfor2.hlp
+f i\isvar.ado
+f i\isvar.hlp
+e
+S http://www.stata.com/stb/stb46
+N gr33.pkg
+D 6 May 2010
+U 44
+d STB-46 gr33. Violin plots.
+d STB insert by Thomas J. Steichen, RJRT.
+d Support: steicht@@rjrt.com
+d After installation, see help ^violin^.
+f v\violin.ado
+f v\violin.hlp
+e
+S http://www.stata.com/stb/stb47
+N sg103.pkg
+D 31 May 2010
+U 45
+d STB-47 sg103. Within subjects (repeated measures) ANOVA, between subj.
+d STB insert by John R. Gleason, Syracuse University.
+d Support: loeslrg@@ican.net
+d After installation, see help ^wsanova^.
+f w\wsanova.ado
+f w\wsanova.hlp
+e
+S http://www.stata-journal.com/software/sj9-3
+N st0169.pkg
+D 7 Jun 2010
+U 46
+d SJ9-3 st0169. Confirmatory factor analysis
+d Confirmatory factor analysis
+d by Stanislav Kolenikov, University of Missouri, Columbia, USA
+d Support: kolenikovs@@missouri.edu, skolenik@@gmail.com
+d After installation, type help ^confa^
+f c\confa.ado
+f c\confa.sthlp
+f c\confa_lf.ado
+f c\confa_lfm.ado
+f c\confa.mata
+f c\confa_p.ado
+f c\confa_estat.ado
+f c\confa_estat.sthlp
+f b\bollenstine.ado
+f b\bollenstine.sthlp
+f l\lconfa.mlib
+e
+S http://www.stata.com/stb/stb55
+N sbe33.pkg
+D 25 May 2011
+U 47
+d STB-55 sbe33. Comparing several methods of measuring the same quantity
+d STB insert by Paul Seed, GKT School of Medicine, King's London, UK
+d Support: paul.seed@@kcl.ac.uk
+d After installation, see help ^baplot^, help ^sdpair^, help ^bamat^,
+d help ^bagroup^
+f b\bagroup.ado
+f b\bagroup.hlp
+f b\bamat.ado
+f b\bamat.hlp
+f b\baplot.ado
+f b\baplot.hlp
+f n\nicenum.ado
+f s\sdpair.ado
+f s\sdpair.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/l
+N log2html.pkg
+D 11 Oct 2012
+U 49
+d 'LOG2HTML': module to produce HTML log files
+d
+d log2html translates translates Stata's standard SMCL log files to
+d HTML, the language used for web pages. log2html provides greater
+d formatting flexibility than the built-in but undocumented log
+d html, providing preformatted schemes and support for CSS
+d (Cascading Style Sheets). Stata 8 is required. (log2html7 is
+d available for Stata 7.)
+d
+d KW: log
+d KW: web
+d KW: html
+d KW: translate
+d KW: SMCL
+d KW: CSS
+d
+d Requires: Stata version 8.0 (7.0 for log2html7)
+d
+d
+d Author: Christopher F Baum, Boston College
+d Support: email baum@@bc.edu
+d
+d Author: Nicholas J. Cox, Durham University
+d Support: email N.J.Cox@@durham.ac.uk
+d
+d Author: Bill Rising, StataCorp
+d Support: email brising@@stata.com
+d
+d Distribution-Date: 20080731
+f l\log2html.ado
+f l\log2html.hlp
+f l\log2html7.ado
+f l\log2html7.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/l
+N logout.pkg
+D 11 Oct 2012
+U 50
+d 'LOGOUT': module to convert log or ASCII files into various output formats
+d
+d logout provides a fast and easy way to convert log or ASCII files
+d into various output formats compatible with Word, Excel, LaTeX,
+d or Stata datafile. Can be used as a prefix or by itself after a
+d log file has been created. caplog provides a fast and easy way to
+d capture text-based log file, possibly for use with logout or
+d dataout.
+d
+d KW: log file
+d KW: table
+d KW: tab
+d KW: summary
+d KW: output
+d KW: LaTeX
+d KW: Word
+d KW: Excel
+d KW: dataout
+d
+d Requires: Stata version 7.0
+d
+d Distribution-Date: 20091106
+d
+d Author: Roy Wada
+d Support: email roywada@@hotmail.com
+d
+f l\logout.ado
+f l\logout.hlp
+f c\caplog.ado
+f c\caplog.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/g
+N gllamm.pkg
+D 19 Nov 2012
+U 51
+d 'GLLAMM': program to fit generalised linear latent and mixed models
+d
+d gllamm fits generalized linear latent and mixed models. These
+d models include Multilevel generalized linear regression models
+d (extensions of the simple random intercept models that may be
+d fitted in Stata using xtreg, xtlogit, xtpois to include
+d multilevel and random coefficient models), Multilevel factor
+d models and Multilevel structural equation models. The latent
+d variables (or random effects) can be assumed to have a
+d multivariate normal distribution or to be discrete allowing
+d nonparametric maximum likelihood estimation. The common links and
+d families of generalized linear models are available and responses
+d can be of mixed type including continuous, censored, discrete,
+d dichotomous, ordered categorical and unordered categorical. The
+d version of gllamm (gllamm6) described in STB-53, (sg129, p47-57)
+d does not incorporate many of the features outlined above. This is
+d version 2.3.20 of the software (Sep 2011). A manual in PDF form
+d is available from the SSC archive via web browser.
+d
+d KW: multilevel models
+d KW: mixed models
+d KW: random coefficients
+d KW: latent variable models
+d
+d Requires: Stata version 7.0
+d
+d
+d Author: Sophia Rabe-Hesketh, University of California - Berkeley
+d Support: email sophiarh@@berkeley.edu
+d
+d Distribution-Date: 20110911
+d
+f g\gllamm.ado
+f g\gllamm.hlp
+f e\eq_g.hlp
+f g\gllam_ll.ado
+f g\gllapred.ado
+f g\gllapred.hlp
+f g\gllarob.ado
+f g\gllasim.ado
+f g\gllasim.hlp
+f g\gllas_yu.ado
+f r\remcor.ado
+e
+S http://fmwww.bc.edu/repec/bocode/h
+N hotdeck.pkg
+D 30 Jan 2013
+U 52
+d 'HOTDECK': module to impute missing values using the hotdeck method
+d
+d hotdeck replaces missing values for the variable indicated by its
+d argument. It should be used within a multiple imputation
+d sequence since missing values are imputed stochastically rather
+d than deterministically. The nmiss missing values in each stratum
+d of the data described by the `by' option are replaced by values
+d sampled from the nobs observed values in the same stratum. The
+d approximate Bayesian bootstrap method of Rubin and Scheker is
+d used; first a bootstrap sample of nobs observations is sampled
+d with replacement from the observed values, and the nmiss missing
+d values are sampled at random (again with replacement) from this
+d bootstrap sample. If a file is specified in a using clause, the
+d modified file is written to disk and the existing data in memory
+d are unchanged. Otherwise the data in memory are modified. This is
+d version 1.65 of the software, requiring Stata v9. hotdeck6 may be
+d used in earlier versions of Stata.
+d
+d Author: Adrian Mander, MRC Biostatistics Unit
+d Support: email Adrian.Mander@@mrc-hnr.cam.ac.uk
+d
+d Author: David Clayton
+d Support: email david.clayton@@mrc-bsu.cam.ac.uk
+d
+d Distribution-Date: 20070902
+f h\hotdeck.ado
+f h\hotdeck.hlp
+f h\hotdeck6.ado
+f h\hotdeck6.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/f
+N fitstat_ers.pkg
+D 6 May 2013
+U 53
+d 'FITSTAT_ERS': module to compute goodness of fit statistics for Rasch model
+d
+d fitstat_ers computes outfit and infit statistics for the
+d conditional maximum likelihood (cml) Rasch model, using formulas
+d outlined in the Linacre and Wright (1994). These fit statistics
+d differ from those computed by the âraschtest-, which are
+d normalized to be approximately normal random variates. These
+d statistics are not normalized.
+d
+d KW: Rasch model
+d KW: goodness of fit
+d
+d Requires: Stata version 9 and gammasym (q.v.) To output tables of statistics, xml_tab.ado and/or outtable.ado are required.
+d
+d Distribution-Date: 20111222
+d
+d Author: Christian Gregory, Economic Research Service, USDA
+d Support: email cgregory@@ers.usda.gov
+d
+f f\fitstat_ers.ado
+f f\fitstat_ers.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/x
+N xml_tab.pkg
+D 6 May 2013
+U 54
+d 'XML_TAB': module to save results in Excel XML format
+d
+d xml_tab saves Stata output directly into XML file that could be
+d opened with Microsoft Excel or OpenOffice Calc. The program is
+d relatively flexible and produces print-ready tables in Excel or
+d Calc. xml_tab allows users to apply different formats to the
+d elements of the output table and essentially do everything MS
+d Excel or OO Calc can do in terms of formatting from within Stata. d
+d KW: XML
+d KW: results
+d KW: output
+d KW: Excel
+d
+d Requires: Stata version 8 and MS Excel (EN) 2002 for Windows, MS Excel 2004 for Mac, or OpenOffice Calc
+d
+d Distribution-Date: 20080625
+d
+d Author: Michael Lokshin, World Bank
+d Support: email Mlokshin@@worldbank.org
+d
+d Author: Zurab Sajaia, World Bank
+d Support: email
+d
+f x\xml_tab.ado
+f x\xml_tab.hlp
+e
+S http://fmwww.bc.edu/repec/bocode/g
+N gengroup.pkg
+D 6 May 2013
+U 55
+d 'GENGROUP': module to produce groups of individuals
+d
+d gengroup creates groups of individuals by using the values of an
+d ordinal variable. The module creates groups of individuals by
+d recoding several adjacent values of the ordinal variable, until
+d obtaining groups with more than individuals than the number
+d defined in the minsize option.
+d
+d KW: data management
+d KW: groups
+d KW: ordinal
+d
+d Requires: Stata version 7.0
+d
+d Distribution-Date: 20101208
+d
+d Author: Jean-Benoit Hardouin, University of Nantes, France
+d Support: email jean-benoit.hardouin@@univ-nantes.fr
+d
+f g\gengroup.ado
+f g\gengroup.hlp
+e
+S http://fmwww.bc.edu/RePEc/bocode/b
+N batplot.pkg
+D 18 Sep 2013
+U 56
+d 'BATPLOT': module to produce Bland-Altman plots accounting for trend
+d
+d The normal Bland-Altman plot is between the difference of paired
+d variables versus their average. This version uses a regression
+d between the difference and the average and then alters the
+d limits of agreement accordingly. This is particularly useful
+d when the two variables might be measured on different scales and
+d hence a straight conversion factor would recalibrate the two
+d variables.
+d
+d KW: plot
+d KW: Bland-Altman
+d KW: difference
+d KW: paired variables
+d
+d Requires: Stata version 9.2
+d
+d Distribution-Date: 20120617
+d
+d Author: Adrian Mander
+d Support: email Adrian.Mander@@mrc-hnr.cam.ac.uk
+d
+f b\batplot.ado
+f b\batplot.hlp
+e
+S http://www.indiana.edu/~jslsoc/stata
+N spost9_ado.pkg
+D 18 Oct 2013
+U 57
+d spost9_ado | Stata 9-13 commands for the post-estimation interpretation
+d Distribution-date: 05Aug2013
+d of regression models. Use package spostado.pkg for Stata 8.
+d Based on Long & Freese - Regression Models for Categorical Dependent
+d Variables Using Stata. Second Edition.
+d Support www.indiana.edu/~jslsoc/spost.htm
+d Scott Long & Jeremy Freese (spostsup@@indiana.edu)
+f _\_get_mlogit_bv.ado
+f _\_get_mlogit_bvecv.ado
+f _\_peabbv.ado
+f _\_pebase.ado
+f _\_pebase.hlp
+f _\_pecats.ado
+f _\_pecats.hlp
+f _\_peciboot.ado
+f _\_peciboot.hlp
+f _\_pecidelta.ado
+f _\_pecidelta.hlp
+f _\_peciml.ado
+f _\_pecmdcheck.ado
+f _\_pecollect.ado
+f _\_pecollect.hlp
+f _\_pedum.ado
+f _\_pedum.hlp
+f _\_peife.ado
+f _\_peife.hlp
+f _\_pemarg.ado
+f _\_pemarg.hlp
+f _\_penocon.ado
+f _\_penocon.hlp
+f _\_pepred.ado
+f _\_pepred.hlp
+f _\_perhs.ado
+f _\_perhs.hlp
+f _\_pesum.ado
+f _\_pesum.hlp
+f _\_petrap.ado
+f _\_petrap.hlp
+f _\_peunvec.ado
+f _\_peunvec.hlp
+f _\_pexstring.ado
+f a\asprvalue.ado
+f a\asprvalue.hlp
+f b\brant.ado
+f b\brant.hlp
+f c\case2alt.ado
+f c\case2alt.hlp
+f c\countfit.ado
+f c\countfit.hlp
+f f\fitstat.ado
+f f\fitstat.hlp
+f l\leastlikely.ado
+f l\leastlikely.hlp
+f l\listcoef.ado
+f l\listcoef.hlp
+f m\misschk.ado
+f m\misschk.sthlp
+f m\mlogplot.ado
+f m\mlogplot.hlp
+f m\mlogtest.ado
+f m\mlogtest.sthlp
+f m\mlogview.ado
+f m\mlogview.hlp
+f m\mvtab1.ado
+f m\mvtab1.hlp
+f n\nmlab.ado
+f n\nmlab.hlp
+f p\praccum.ado
+f p\praccum.hlp
+f p\prchange.ado
+f p\prchange.hlp
+f p\prcounts.ado
+f p\prcounts.hlp
+f p\prdc.ado
+f p\prdc.hlp
+f p\prgen.ado
+f p\prgen.hlp
+f p\prtab.ado
+f p\prtab.hlp
+f p\prvalue.ado
+f p\prvalue.hlp
+f p\prwhich.ado
+f s\spex.ado
+f s\spex.hlp
+f s\spost.hlp
+f s\spost_footer.ihlp
+f s\spostupdate.ado
+f v\vardesc.ado
+f v\vardesc.hlp
+f x\xpost.ado
+e
diff --git a/Modules/ado/plus/c/caplog.ado b/Modules/ado/plus/c/caplog.ado
new file mode 100644
index 0000000..2087f10
--- /dev/null
+++ b/Modules/ado/plus/c/caplog.ado
@@ -0,0 +1,235 @@
+
+*! version 1.0.2 13oct2009 caplog by roywada@hotmail.com
+*! captures a log file, possibly for use with logout or dataout
+
+program define caplog
+version 6
+
+local logfile : log
+
+version 7
+
+* invisible to Stata 7
+local Version7 ""
+cap local Version7 `c(stata_version)'
+
+if "`Version7'"=="" {
+ * it is version 7
+ local bind ""
+ *noi di in yel "limited functions under Stata 7"
+}
+else if `Version7'>=8.2 {
+ version 8.2
+ local bind "bind"
+}
+
+*qui log query
+*if `"`r(status)'"'=="on" {
+* qui log close
+* local filename `"`r(filename)'"'
+*}
+
+if `"`logfile'"'~="" {
+ di ""
+ qui log close
+ local filename `"`logfile'"'
+}
+
+* embbed to avoid log being open
+_caplog `0'
+
+cap log close
+
+*** c_locals coming back
+* clickables
+if "`tempfile'"~="tempfile" {
+ if "`smcl'"=="" {
+ local cl_text `"{browse `"`using1'"'}"'
+ noi di as txt `"`cl_text'"'
+ }
+ else {
+ local cl_text `"{stata `"view `using1'"':`using1'}"'
+ noi di as txt `"`cl_text'"'
+ }
+}
+
+cap log close
+
+*if `"`filename'"'~="" {
+* log using `"`filename'"', append
+*}
+
+end
+
+
+********************************************************************************************
+
+
+program define _caplog
+version 7
+
+local Version7 ""
+cap local Version7 `c(stata_version)'
+
+if "`Version7'"=="" {
+ * it is version 7
+ local bind ""
+ *noi di in yel "limited functions under Stata 7"
+}
+else if `Version7'>=8.2 {
+ version 8.2
+ local bind "bind"
+}
+
+* encase the colon in file name in quotes, avoiding string function length limits
+
+local behind `"`0'"'
+local 0 ""
+gettoken front behind: behind, parse(" ,")
+local 0 ""
+local done 0
+while `"`front'"'~="" & `done'==0 {
+ if `"`front'"'=="using" {
+
+ gettoken rest behind: behind, parse(" ,")
+ * strip off quotes
+ gettoken first second: rest, parse(" ")
+ cap local rest: list clean local(rest)
+
+ * take off colon at the end
+ local goldfish ""
+ if index(`"`rest'"',":")~=0 {
+ local end=substr(`"`rest'"',length(`"`rest'"'),length(`"`rest'"'))
+ if "`end'"==":" {
+ local rest=substr(`"`rest'"',1,`=length(`"`rest'"')-1')
+ local goldfish " : "
+ }
+ }
+
+ * colon reattached with a space at the end
+ * .txt attached here, SMCL TO BE FIXED LATER
+ local rabbit `"""'
+ if index(`"`rest'"', ".")==0 {
+ local using `"`rabbit'`rest'.txt`rabbit'`goldfish'"'
+ }
+ else {
+ local using `"`rabbit'`rest'`rabbit'`goldfish'"'
+ }
+ local 0 `"`0' using `using' `behind'"'
+ local done 1
+ }
+ else {
+ local 0 `"`0' `front'"'
+ gettoken front behind: behind, parse(" ,")
+ }
+}
+
+
+gettoken first second : 0, parse(":") `bind' match(par) quotes
+local 0 `"`first'"'
+while `"`first'"'~=":" & `"`first'"'~="" {
+ gettoken first second : second, parse(":") `bind' match(par) quotes
+}
+if `"`0'"'==":" {
+ * colon only when shorthand combined with prefix
+ local 0
+}
+else {
+ local _0 `"`0'"'
+}
+
+*** shorthand syntax if [using] is missing
+
+syntax using/ [, replace append tempfile text smcl subspace]
+
+if "`smcl'"=="smcl" {
+ if index(`"`using'"', ".txt")~=0 {
+ local temp=substr(`"`using'"',1,length(`"`using'"')-4)
+ local using `"`temp'.smcl"'
+ }
+}
+
+if "`text'"~="" & "`smcl'"~="" {
+ di "cannot choose both {opt text} and {opt smcl}"
+ exit 198
+}
+
+if "`text'"=="" & "`smcl'"=="" {
+ local text "text"
+}
+
+
+cap confirm file `"`using'"'
+if !_rc & "`replace'"~="replace" & "`append'"~="append" {
+ * it exists
+ noi di in red `"`using' exists; specify {opt replace} or {opt append}"'
+ exit 198
+}
+
+* goes with `second'
+if `"`second'"'~="" {
+ local _colon ":"
+}
+
+qui {
+ if "`subspace'"=="subspace" {
+ * fix the gaps in the value labels
+ ds8
+ foreach var in `r(varlist)'{
+ local temp : var label `var'
+ local temp = subinstr(`"`temp'"'," ","_",.)
+ label var `var' `"`temp'"'
+ }
+ }
+}
+
+ * regular stuff
+ if `"`using'"'~="" {
+ * prefix use using file
+ qui log using `"`using'"', `replace' `append' `text' `smcl'
+ `second'
+ }
+ else {
+ * prefix use temp file
+ qui log using `"`using'"', `replace' `append' `text' `smcl'
+ `second'
+ }
+
+* clickables
+c_local smcl "`smcl'"
+c_local using1 `"`using'"'
+c_local tempfile `"`tempfile'"'
+
+end
+
+
+********************************************************************************************
+
+
+*** ripped from outreg2 Mar 2009
+program define ds8
+ * get you the list of variable like -ds- does for version 8
+ version 7.0
+ qui ds
+ if "`r(varlist)'"=="" {
+ local dsVarlist ""
+ foreach var of varlist _all {
+ local dsVarlist "`dsVarlist' `var'"
+ }
+ c_local dsVarlist `dsVarlist'
+ }
+ else {
+ c_local dsVarlist `r(varlist)'
+ }
+end
+
+
+
+
+/*
+* version 1.0.1 May2009 caplog by roywada@hotmail.com
+smcl accepted
+version control fixed
+
+1.0.2 close the log file at the end to avoid the possibility of it being left open
+
diff --git a/Modules/ado/plus/c/caplog.hlp b/Modules/ado/plus/c/caplog.hlp
new file mode 100644
index 0000000..00a70e0
--- /dev/null
+++ b/Modules/ado/plus/c/caplog.hlp
@@ -0,0 +1,64 @@
+{smcl}
+{* 13oct2009}{...}
+{cmd:help caplog}
+
+{hline}
+
+{title:Title}
+
+{p2colset 5 16 22 2}{...}
+{p2col :{hi: caplog} {hline 2}}captures a ASCII log file (for use with {cmd:{help logout}}){p_end}
+
+{marker s_Syntax}
+{title:Syntax}
+
+{p 4 4 6}
+{cmdab:caplog} using filename [, {it:options}] : command
+
+{marker s_Description}
+{title:Description}
+
+{p 4 4 6}
+{cmd:caplog} provides a fast and easy way to capture text-based log file, possibly for use with
+{cmd:{help logout}}. The default is text log files.
+
+
+{title:Command}
+
+{p 4 12 6}Any command accepted, i.e. { help estimation commands}, tabulation, summary, descrition, etc.
+
+
+{marker s_Options}
+{title:Options}
+
+{dlgtab:Main}
+
+{p 4 12 6}{opt replace} Replace pre-exiting log files.{p_end}
+
+{p 4 12 6}{opt append} Append. {p_end}
+
+{p 4 12 6}{opt smcl} Save smcl file instead of text file. {p_end}
+
+
+{marker s_0}
+{title:Examples}
+
+
+{p 4 4 6}{cmd:* table}{p_end}
+{p 4 4 6}{stata sysuse auto, clear}{p_end}
+{p 4 4 6}{stata `"caplog using mystuff.txt, replace: table trunk rep78 , c(n mpg mean mpg sd mpg median mpg)"'}{p_end}
+{p 4 4 6}{stata `"caplog using mystuff.txt, append: table trunk rep78 , c(n mpg mean mpg sd mpg median mpg)"'}{p_end}
+
+
+{title:Remarks}
+
+{p 4 12 6}PREVIOUSLY OPENED LOG FILES WILL BE CLOSED BY CAPLOG.{p_end}
+{p 4 12 6}version 7: do not include colon characters (:) in the file path. Use -cd- instead.{p_end}
+
+
+{title:Author}
+
+{p 4 4 6}Roy Wada{p_end}
+{p 4 4 6}roywada@hotmail.com{p_end}
+
+
diff --git a/Modules/ado/plus/c/case2alt.ado b/Modules/ado/plus/c/case2alt.ado
new file mode 100644
index 0000000..ef418ce
--- /dev/null
+++ b/Modules/ado/plus/c/case2alt.ado
@@ -0,0 +1,167 @@
+*! 1.0.1 - allow either y() or choice(); yrank() or rank()
+* 1.0.0 - revise option names: case->casevar; id->case
+* 0.2.4 - small text formatting error
+* 0.2.3 - change _optnum to altnum and add as option
+* 0.2.2 - allow id() to specify new variable instead of using _id - 15Jul2005
+* 0.2.1 - change specification of csv from varlist to case() - 11Jul2005
+
+program define case2alt
+
+ version 9
+
+ syntax , [y(varname numeric) YRank(name) case(name) ///
+ Generate(name) REplace CASEVars(namelist) Alt(namelist) noNames altnum(name) ///
+ Choice(name) Rank(name)] // allow choice() and rank() to sub for y() and yrank()
+
+ ** CHANGE 9/8/05: allow choice() instead of y() and allow rank() instead of yrank()
+ if "`choice'" != "" {
+ local y "`choice'"
+ local choice ""
+ }
+
+ if "`rank'" != "" {
+ local yrank "`rank'"
+ local rank ""
+ }
+
+
+ * either y() or yrank() must be specified
+ if "`y'" == "" & "`yrank'" == "" {
+ di as err "option y() or yrank() must be specified"
+ exit 198
+ }
+
+ * figure out if rankdata is being specified
+ local rankdata "yes"
+ if "`y'" != "" {
+ local rankdata "no"
+ }
+
+ if "`rankdata'" == "no" & "`generate'" == "" & "`replace'" == "" {
+ di as txt "(note: " as res "choice " as txt "used for outcome since no variable specified by gen())"
+ confirm new variable choice
+ local generate "choice"
+ }
+ local choice "`generate'"
+
+ if "`case'" == "" {
+ di as txt "(note: variable " as res "_id" as txt " used since case() not specified)"
+ confirm new variable _id
+ gen _id = _n
+ local case "_id"
+ }
+
+ if "`altnum'" == "" {
+ di as txt "(note: variable " as res "_altnum" as txt " used since altnum() not specified)"
+ confirm new variable _altnum
+ local altnum "_altnum"
+ }
+
+ capture confirm variable `case'
+ if _rc != 0 {
+ gen `case' = _n
+ }
+
+
+ if "`rankdata'" == "no" {
+ _pecats `y'
+
+ local catval = r(catvals)
+ local catnms = r(catnms)
+ local numcats = r(numcats)
+
+ forvalues i = 1(1)`numcats' {
+ local y`i' : word `i' of `catval'
+ local ynm`i' : word `i' of `catnms'
+ confirm integer number `y`i''
+ gen _ytemp`y`i'' = 1
+ }
+
+ local ytemp "_ytemp"
+ }
+
+ if "`rankdata'" == "yes" {
+ capture label drop `altnum'
+ foreach rvar of varlist `yrank'* {
+ local rvarnum = subinstr("`rvar'", "`yrank'", "", 1)
+ local rvarnumchk = real("`rvarnum'")
+ if "`rvarnum'" == "`rvarnumchk'" {
+ local rvarlabel : variable label `rvar'
+ label define `altnum' `rvarnum' "`rvarlabel'", modify
+ }
+ }
+ }
+
+ qui reshape long `ytemp' `yrank' `alt', i(`case') j(`altnum')
+
+ capture drop _ytemp
+
+ if "`rankdata'" == "no" {
+
+ tempvar ychosen
+ gen `ychosen' = `y'
+
+ if "`replace'" == "replace" {
+ drop `y'
+ local choice "`y'"
+ }
+
+ gen `choice' = (`altnum' == `ychosen') if `altnum' < .
+
+ }
+
+ if "`rankdata'" == "yes" {
+ label define `altnum', modify
+ label values `altnum' `altnum'
+ _pecats `altnum'
+
+ local catval = r(catvals)
+ local catnms = r(catnms)
+ local numcats = r(numcats)
+
+ forvalues i = 1(1)`numcats' {
+ local y`i' : word `i' of `catval'
+ local ynm`i' : word `i' of `catnms'
+ confirm integer number `y`i''
+ }
+
+ * if generate option specified, rename stub to that
+ if "`generate'" != "" {
+ rename `yrank' `generate'
+ local yrank "`generate'"
+ }
+
+ }
+
+ forvalues i = 1(1)`numcats' {
+ local name = "y`y`i''"
+ if "`names'" != "nonames" & "`ynm`i''" != "`y`i''" {
+ local name "`ynm`i''"
+ }
+ qui gen ytemp`y`i'' = (`altnum' == `y`i'') if `altnum' < .
+ label variable ytemp`y`i'' "`ynm`i''"
+ if "`casevars'" != "" {
+ foreach var of varlist `casevars' {
+ qui gen `name'X`var' = `var' * ytemp`y`i''
+ }
+ }
+ local ylist "`ylist' `name'*"
+ clonevar `name' = ytemp`y`i''
+ drop ytemp`y`i''
+ }
+
+ * output
+
+ if "`rankdata'" == "no" {
+ di _n as txt "choice indicated by:" as res " `choice'"
+ }
+ if "`rankdata'" == "yes" {
+ di _n as txt "ranks indicated by:" as res " `yrank'"
+ }
+ di as txt "case identifier:" as res " `case'"
+ di as txt "case-specific interactions:" as res "`ylist'"
+ if "`alt'" != "" {
+ di as txt "alternative-specific variables:" as res " `alt'"
+ }
+
+end
diff --git a/Modules/ado/plus/c/case2alt.hlp b/Modules/ado/plus/c/case2alt.hlp
new file mode 100644
index 0000000..9d4cc14
--- /dev/null
+++ b/Modules/ado/plus/c/case2alt.hlp
@@ -0,0 +1,121 @@
+{smcl}
+{* 05Dec2005jf}
+{hline}
+help for {hi:case2alt}{right:03Nov2005}
+{hline}
+
+{p 4 4 2}
+{title:Convert data from one observation per case to one observation per alternative per case}
+
+{p 4 12 2}{cmd:case2alt} {cmd:,}
+{{cmdab:choice(}{it:varname}{cmd:)} | {cmdab:rank(}{it:stubname}{cmd:)}}
+[{cmdab:a:lt(}{it:stubnames}{cmd:)}
+{cmdab:casev:ars(}{it:varlist}{cmd:)}
+{cmdab:case(}{it:varname}{cmd:)}
+{cmdab:g:enerate(}{it:newvar}{cmd:)}
+{cmdab:rep:lace}
+{cmdab:altnum(}{it:varname}{cmd:)}
+{cmdab:non:ames}]
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:case2alt} is intended to be used to configure data for the estimation of estimation
+of regression models for alternative-specific data, such as {helpb clogit},
+{helpb rologit} or {helpb asmprobit}. {cmd:case2alt} presumes that you have data
+where each observation corresponds to an individual case and that you want to convert
+the data to the form in which each observation corresponds to an alternative for a specific case.
+
+{p 4 4 2}
+Imagine that you have data with an outcome that has four alternatives, with values 1, 2, 3 and 8.
+{cmd:case2alt} will reshape the data so that there are n*4 observations. If you specify an
+identifying variable with the {cmd:casevars()} option, this variable will continue to identify
+unique cases; otherwise, new variable _id will identify cases.
+
+{p 4 4 2}
+A new variable, called either _altnum or the name specified in {cmd:altnum()},
+will identify the alternatives within a case. Additionally, however, {cmd:case2alt}
+will create dummy variables y{it:value} that also identify alternatives.
+In our example the new dummy variables y1, y2, y3 and y8 will be created.
+Interactions will also be created with these dummies and any variables
+specified in {cmd:case()}. For the variable educ, {cmd:case2alt} will create
+variables y1_educ, y2_educ, y3_educ, and y8_educ.
+
+{p 4 4 2}
+If we have simple choice variable, then {cmd:case2alt} will create an outcome
+variable based on {cmd:y()} that contains 1 in the observation corresponding to
+the selected alternative and 0 for other alternatives. We can specify the name of
+this new outcome variable using the {cmd:gen()} option, or we can have it be the
+same as {opt y()} using the {cmd:replace} option, or (by default) we
+can have it be named choice.
+
+{p 4 4 2}
+After using {cmd:case2alt}, we would be able to estimate models like {helpb clogit} by typing, e.g.,:
+
+{p 4 4 2}
+{cmd:. clogit choice y1* y2* y3*, group(_id)}
+
+{p 4 4 2}
+Alternative-specific variables are specified using the {cmd:alt()} option.
+The contents of {cmd:alt()} should be {it:stubnames}, corresponding to a series
+of variables that contain the alternative-specific values.
+Specifying {cmd:alt(time)}, in our example, would imply that there are
+variables time1, time2, time3 and time8 in our case-level data.
+
+{p 4 4 2}
+Case-specific variables are specified using the {cmd:casevars()} option,
+where the contents should be a {varlist}. Neither the outcome nor id variable
+should be included in {cmd:casevars()}.
+
+{p 4 4 2}
+If we have ranked data, we can specify the ranked outcome with the
+{cmd:rank()} outcome. The content of rank should again be a stubname.
+Specifying {cmd:rank(}rank{cmd:)} in our example would assume there are
+variables rank1, rank2, rank3, rank8 that contain the relevant information
+on the ranks of each alternative.
+
+{title:Options}
+
+{p 4 8 2}{opth choice(varname)} or {opth rank(stubname)} is required. {varname} is the
+variable that indicates the value of the selected alternative.
+In the case of ranked outcome, {it:stubname} with {opt rank()} will contain
+the stub for the names of variables that contain information about ranks of alternatives.
+
+{p 4 8 2}{opth case(varname)} indicates the variable, either existing or to be
+created, that identifies individual cases.
+If {varname} is unspecified, a new variable named _id will be created.
+
+{p 4 8 2}{cmd:alt(}{it:stubnames}{cmd:)} contains the {it:stubnames} for
+alternative-specific variables. This requires that variables {it:stubname}# exist
+for each value of an alternative.
+
+{p 4 8 2}{opth casevars(varlist)} contains the names of the case-specific variables
+(not including the id or outcome variable).
+
+{p 4 8 2}{opth gen:erate(newvar)} and {opt replace} are used to name the variable that
+contain 1 for the selected alternative and 0 for non-selected alternatives.
+The variable will be named {newvar} if {newvar} is specified; the name of
+the variable specified in {cmd: y()} if {opt replace} is specified; and will be named {it:choice} otherwise.
+In the case of ranked data, the ranks will be contained in variable specified as the
+stub in {opt yrank()} and {opt gen:erate()} or {opt replace} will be ignored.
+
+{p 4 8 2}{opth altnum(varname)} indicates the name of the new variable used to indicate
+the alternatives. _altnum will be used if altnum() is not specified.
+
+{p 4 8 2}{opt non:ames} indicates that the case-specific interactions should be named
+y# instead of using the value labels of the outcome variable.
+
+{title:Example}
+
+{p 4 4 2}{cmd:. use "http://www.stata-press.com/data/lfr/nomocc2.dta", clear}{break}
+{cmd:. mlogit occ white ed exper}{break}
+{cmd:. case2alt, choice(ed) casevars(white ed exper) replace nonames}{break}
+{cmd:. clogit occ y1* y2* y3* y4*, group(_id)}{break}
+
+{p 4 4 2}{cmd:. case2alt, rank(rank92) casevars(hntest) alt(rank04) case(id)}
+
+{title:Authors}
+
+ Jeremy Freese and J. Scott Long
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@indiana.edu
diff --git a/Modules/ado/plus/c/cfa1.ado b/Modules/ado/plus/c/cfa1.ado
new file mode 100644
index 0000000..4c24afa
--- /dev/null
+++ b/Modules/ado/plus/c/cfa1.ado
@@ -0,0 +1,679 @@
+*! Confirmatory factor analysis with a single factor: v.2.2
+*! Stas Kolenikov, skolenik-gmail-com
+
+program define cfa1, eclass
+ version 9.1
+
+ if replay() {
+ if ("`e(cmd)'" != "cfa1") error 301
+ Replay `0'
+ }
+
+ else Estimate `0'
+end
+
+program Estimate `0', eclass
+
+ syntax varlist(numeric min=3) [if] [in] [aw pw / ] ///
+ , [unitvar FREE POSvar FROM(str) CONSTRaint(numlist) LEVel(int $S_level) ///
+ ROBust VCE(string) CLUster(passthru) SVY SEArch(passthru) * ]
+ * syntax: cfa1
+ * untivar is for the identification condition of the unit variance of the latent variable
+
+ unab varlist : `varlist'
+ tokenize `varlist'
+ local q: word count `varlist'
+ marksample touse
+ preserve
+ qui keep if `touse'
+ * weights!
+ global CFA1N = _N
+
+/*
+ * we'll estimate the means instead
+ qui foreach x of varlist `varlist' {
+ sum `x', meanonly
+ replace `x' = `x'-r(mean)
+ * deviations from the mean
+ }
+*/
+
+ if "`weight'" != "" {
+ local mywgt [`weight'=`exp']
+ }
+
+ if "`robust'`cluster'`svy'`weight'"~="" {
+ local needed 1
+ }
+ else {
+ local needed 0
+ }
+
+ Parse `varlist' , `unitvar'
+ local toml `r(toml)'
+ if "`from'" == "" {
+ local from `r(tostart)', copy
+ }
+
+ * identification
+ constraint free
+ global CFA1constr `r(free)'
+ if "`unitvar'" ~= "" {
+ * identification by unit variance
+ constraint $CFA1constr [phi]_cons = 1
+ }
+ else if "`free'"=="" {
+ * identification by the first variable
+ constraint $CFA1constr [`1']_cons = 1
+ }
+ else {
+ * identification imposed by user
+ global CFA1constr
+ }
+ local nconstr : word count `constraint'
+
+ global CFA1PV = ("`posvar'" != "")
+
+ if "`posvar'" ~= "" {
+ di as text _n "Fitting the model without restrictions on error variances..."
+ }
+
+ * variance estimation
+ local vce = trim("`vce'")
+ if "`vce'" == "boot" local vce bootstrap
+ if "`vce'" == "sbentler" {
+ global CFA1SBV = 1
+ local vce
+ }
+ else {
+ if index("robustoimopg","`vce'") {
+ local vce vce(`vce')
+ }
+ else {
+ di as err "`vce' estimation is not supported"
+ if "`vce'" == "bootstrap" | "`vce'" == "boot" {
+ di as err "try {help bootstrap} command directly"
+ }
+ exit 198
+ }
+ }
+
+ tempname ilog1 ilog2
+ Tryit ml model lf cfa1_lf `toml' `mywgt', constraint($CFA1constr `constraint') ///
+ init (`from') maximize nooutput `options' `search' ///
+ `svy' `cluster' `robust' `vce'
+/*
+ ml model lf cfa1_lf `toml' `mywgt', ///
+ constraint($CFA1constr `constraint') `svy' `robust' `cluster' ///
+ maximize
+* ml check
+* ml search, rep(5)
+ ml init `from', copy
+ cap noi ml maximize , `options'
+*/
+ mat `ilog1' = e(ilog)
+
+ local nz = 0
+ if $CFA1PV {
+ * determine if refitting the model is needed
+ tempname ll_unr
+ scalar `ll_unr' = e(ll)
+ forvalues i=1/`q' {
+ if [``i''_v]_cons <0 {
+ constraint free
+ local ccc = `r(free)'
+ const define `ccc' [``i''_v]_cons = 0
+ local zerolist `zerolist' `ccc'
+ local ++nz
+ }
+ }
+ local zerolist = trim("`zerolist'")
+ global CFA1constr $CFA1constr `zerolist'
+ if "`zerolist'" ~= "" {
+ di as text _n "Fitting the model with some error variances set to zero..."
+ Tryit ml model lf cfa1_lf `toml' `mywgt' , constraint($CFA1constr `constraint') ///
+ init (`from') maximize nooutput `options' `search' ///
+ `svy' `robust' `cluster' `vce'
+ mat `ilog2' = e(ilog)
+
+ }
+
+ * adjust degrees of freedom!
+ }
+
+
+ * we better have this before Satorra-Bentler
+ if "`unitvar'" ~= "" {
+ ereturn local normalized Latent Variance
+ }
+ else if "`free'"=="" {
+ ereturn local normalized `1'
+ }
+
+
+ * work out Satorra-Bentler estimates
+ if "$CFA1SBV"!="" {
+ * repost Satorra-Bentler covariance matrix
+ tempname SBVar SBV Delta Gamma
+ cap SatorraBentler
+ if _rc {
+ di as err "Satorra-Bentler standard errors are not supported for this circumstance; revert to vce(oim)"
+ global CFA1SBV
+ }
+ else {
+ mat `SBVar' = r(SBVar)
+ mat `Delta' = r(Delta)
+ mat `Gamma' = r(Gamma)
+ mat `SBV' = r(SBV)
+ ereturn repost V = `SBVar'
+ ereturn matrix SBGamma = `Gamma', copy
+ ereturn matrix SBDelta = `Delta', copy
+ ereturn matrix SBV = `SBV', copy
+ ereturn local vce SatorraBentler
+ }
+ }
+
+
+
+ * get the covariance matrix and the number of observations!
+ ***********************************************************
+ tempname lambda vars phi S Sindep Sigma trind eb
+
+ qui mat accum `S' = `varlist', dev nocons
+ mat `S' = `S' / $CFA1N
+
+ * implied matrix
+ mat `eb' = e(b)
+ mat `lambda' = `eb'[1,1..`q']
+ mat `vars' = `eb'[1,`q'+1..2*`q']
+ scalar `phi' = `eb'[1,3*`q'+1]
+ mat `Sigma' = `lambda''*`phi'*`lambda' + diag(`vars')
+ mat `Sindep' = diag(vecdiag(`S'))
+
+ * test against independence
+ mat `trind' = trace( syminv(`Sindep') * `S' )
+ local trind = `trind'[1,1]
+ ereturn scalar ll_indep = -0.5 * `q' * $CFA1N * ln(2*_pi) - 0.5 * $CFA1N * ln(det(`Sindep')) - 0.5 * $CFA1N * `trind'
+ ereturn scalar lr_indep = 2*(e(ll)-e(ll_indep))
+ ereturn scalar df_indep = `q'-`nz'-`nconstr'
+ ereturn scalar p_indep = chi2tail(e(df_indep),e(lr_indep))
+
+ * goodness of fit test
+ ereturn scalar ll_u = -0.5 * `q' * $CFA1N * ln(2*_pi) - 0.5 * $CFA1N * ln(det(`S')) - 0.5 * `q' * $CFA1N
+ ereturn scalar lr_u = -2*(e(ll)-e(ll_u))
+ ereturn scalar df_u = `q'*(`q'+1)*.5 - (2*`q' - `nz' - `nconstr')
+ * wrong if there are any extra constraints in -constraint- command!!!
+ ereturn scalar p_u = chi2tail(e(df_u),e(lr_u))
+ ereturn matrix ilog1 `ilog1'
+ cap ereturn matrix ilog2 `ilog2'
+
+ * Satorra-Bentler corrections
+ if "$CFA1SBV"!="" {
+ * compute the corrected tests, too
+ * Satorra-Bentler 1994
+ tempname U trUG2 Tdf
+ mat `U' = `SBV' - `SBV'*`Delta'*syminv(`Delta''*`SBV'*`Delta')*`Delta''*`SBV'
+ ereturn matrix SBU = `U'
+ mat `U' = trace( e(SBU)*`Gamma' )
+ ereturn scalar SBc = `U'[1,1]/e(df_u)
+ ereturn scalar Tscaled = e(lr_u)/e(SBc)
+ ereturn scalar p_Tscaled = chi2tail( e(df_u), e(Tscaled) )
+
+ mat `trUG2' = trace( e(SBU)*`Gamma'*e(SBU)*`Gamma')
+ ereturn scalar SBd = `U'[1,1]*`U'[1,1]/`trUG2'[1,1]
+ ereturn scalar Tadj = ( e(SBd)/`U'[1,1]) * e(lr_u)
+ ereturn scalar p_Tadj = chi2tail( e(SBd), e(Tadj) )
+
+ * Yuan-Bentler 1997
+ * weights!
+ ereturn scalar T2 = e(lr_u)/(1+e(lr_u)/e(N) )
+ ereturn scalar p_T2 = chi2tail( e(df_u), e(T2) )
+ }
+
+ if "`posvar'" ~= "" {
+ ereturn scalar lr_zerov = 2*(`ll_unr' - e(ll))
+ ereturn scalar df_zerov = `nz'
+ local replay_opt posvar llu(`ll_unr')
+ }
+ ereturn local cmd cfa1
+
+ Replay , `replay_opt' level(`level')
+ Finish
+ restore
+ ereturn repost, esample(`touse')
+
+end
+
+program define Tryit
+
+ cap noi `0'
+ local rc=_rc
+ if `rc' {
+ Finish
+ exit `rc'
+ }
+
+end
+
+program define Finish
+
+ * finishing off
+ constraint drop $CFA1constr
+ global CFA1S
+ global CFA1N
+ global CFA1PV
+ global CFA1theta
+ global CFA1arg
+ global CFA1data
+ global CFA1constr
+ global CFA1vars
+ global CFA1SBV
+
+end
+
+program define Replay
+
+ syntax, [posvar llu(str) level(passthru)]
+
+ di _n as text "Log likelihood = " as res e(ll) _col(59) as text "Number of obs = " as res e(N)
+ di as text "{hline 13}{c TT}{hline 64}"
+ di as text " {c |} Coef. Std. Err. z P>|z| [$S_level% Conf. Interval]"
+ di as text "{hline 13}{c +}{hline 64}"
+
+ tempname vce
+ mat `vce' = e(V)
+ local q = colsof(`vce')
+ local q = (`q'-1)/3
+ local a : colfullnames(`vce')
+ tokenize `a'
+
+ di as text "Lambda{col 14}{c |}"
+ forvalues i = 1/`q' {
+ gettoken v`i' : `i' , parse(":")
+ _diparm `v`i'' , label("`v`i''") prob `level'
+ }
+ di as text "Var[error]{col 14}{c |}"
+ forvalues i = 1/`q' {
+ _diparm `v`i''_v , label("`v`i''") prob `level'
+ }
+ di as text "Means{col 14}{c |}"
+ forvalues i = 1/`q' {
+ _diparm `v`i''_m , label("`v`i''") prob `level'
+ }
+ di as text "Var[latent]{col 14}{c |}"
+ _diparm phi , label("phi1") prob
+
+ di as text "{hline 13}{c +}{hline 64}"
+ di as text "R2{col 14}{c |}"
+ forvalues i = 1/`q' {
+ di as text %12s "`v`i''" "{col 14}{c |}{col 20}" ///
+ as res %6.4f (_b[`v`i'':_cons]^2*_b[phi:_cons]) / ///
+ (_b[`v`i'':_cons]^2*_b[phi:_cons] + _b[`v`i''_v:_cons])
+ }
+
+
+ di as text "{hline 13}{c BT}{hline 64}"
+
+ if e(df_u)>0 {
+ di as text _n "Goodness of fit test: LR = " as res %6.3f e(lr_u) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > LR] = " as res %6.4f e(p_u)
+ }
+ else {
+ di as text "No degrees of freedom to perform the goodness of fit test"
+ }
+ di as text "Test vs independence: LR = " as res %6.3f e(lr_indep) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_indep) as text ") > LR] = " as res %6.4f e(p_indep)
+
+ if "`e(vce)'" == "SatorraBentler" & e(df_u)>0 {
+ * need to report all those corrected statistics
+
+ di as text _n "Satorra-Bentler Tbar" _col(26) "= " as res %6.3f e(Tscaled) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > Tbar] = " as res %6.4f e(p_Tscaled)
+
+ di as text "Satorra-Bentler Tbarbar" _col(26) "= " as res %6.3f e(Tadj) ///
+ as text _col(40) "; Prob[chi2(" as res %4.1f e(SBd) as text ") > Tbarbar] = " as res %6.4f e(p_Tadj)
+
+ di as text "Yuan-Bentler T2" _col(26) "= " as res %6.3f e(T2) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > T2] = " as res %6.4f e(p_T2)
+ }
+
+ if "`posvar'" ~= "" {
+ * just estimated?
+ if "`llu'" == "" {
+ di as err "cannot specify -posvar- option, need to refit the whole model"
+ }
+ else {
+ if e(df_zerov)>0 {
+ di as text "Likelihood ratio against negative variances: LR = " as res %6.3f e(lr_zerov)
+ di as text "Conservative Prob[chi2(" as res %2.0f e(df_zerov) as text ") > LR] = " ///
+ as res %6.4f chi2tail(e(df_zerov),e(lr_zerov))
+ }
+ else {
+ di as text "All variances are non-negative, no need to test against zero variances"
+ }
+ }
+ }
+
+end
+
+program define Parse , rclass
+ * takes the list of variables and returns the appropriate ml model statement
+ syntax varlist , [unitvar]
+
+ global CFA1arg
+ global CFA1theta
+ global CFA1vars
+ local q : word count `varlist'
+
+ * lambdas
+ forvalues i = 1/`q' {
+ local toml `toml' (``i'': ``i'' = )
+ local tostart `tostart' 1
+ global CFA1arg $CFA1arg g_``i''
+ global CFA1theta $CFA1theta l_`i'
+ global CFA1vars $CFA1vars ``i''
+ }
+
+ * variances
+ forvalues i = 1/`q' {
+ local toml `toml' (``i''_v: )
+ local tostart `tostart' 1
+ global CFA1arg $CFA1arg g_``i''_v
+ global CFA1theta $CFA1theta v_`i'
+ }
+
+ * means
+ forvalues i = 1/`q' {
+ local toml `toml' (``i''_m: )
+ qui sum ``i'', mean
+ local mean = r(mean)
+ local tostart `tostart' `mean'
+ global CFA1arg $CFA1arg g_``i''_m
+ global CFA1theta $CFA1theta m_`i'
+ }
+
+ * variance of the factor
+ local toml `toml' (phi: )
+ local tostart `tostart' 1
+ global CFA1arg $CFA1arg g_Phi
+ global CFA1theta $CFA1theta phi
+
+ * done!
+ return local toml `toml'
+ return local tostart `tostart'
+
+end
+
+
+**************************** Satorra-Bentler covariance matrix code
+
+program SatorraBentler, rclass
+ version 9.1
+ syntax [, noisily]
+ * assume the maximization completed, the results are in memory as -ereturn data-
+ * we shall just return the resulting matrix
+
+ if "`e(normalized)'" == "" {
+ di as err "cannot compute Satorra-Bentler variance estimator with arbitrary identification... yet"
+ exit 198
+ }
+
+ * assume sample is restricted to e(sample)
+ * preserve
+ * keep if e(sample)
+
+ * get the variable names
+ tempname VV bb
+ mat `VV' = e(V)
+ local q = rowsof(`VV')
+ local p = (`q'-1)/3
+ local eqlist : coleq `VV'
+ tokenize `eqlist'
+ forvalues k=1/`p' {
+ local varlist `varlist' ``k''
+ }
+
+ * compute the implied covariance matrix
+ tempname Lambda Theta phi Sigma
+ mat `bb' = e(b)
+ mat `Lambda' = `bb'[1,1..`p']
+ mat `Theta' = `bb'[1,`p'+1..2*`p']
+ scalar `phi' = `bb'[1,`q']
+ mat `Sigma' = `Lambda''*`phi'*`Lambda' + diag(`Theta')
+
+ * compute the empirical cov matrix
+ tempname SampleCov
+ qui mat accum `SampleCov' = `varlist' , nocons dev
+ * weights!!!
+ mat `SampleCov' = `SampleCov' / (r(N)-1)
+
+ * compute the matrix Gamma
+ `noisily' di as text "Computing the Gamma matrix of fourth moments..."
+ tempname Gamma
+ SBGamma `varlist'
+ mat `Gamma' = r(Gamma)
+ return add
+
+ * compute the duplication matrix
+ * Dupl `p'
+ * let's call it from within SBV!
+
+ * compute the V matrix
+ `noisily' di as text "Computing the V matrix..."
+ SBV `SampleCov' `noisily'
+ tempname V
+ mat `V' = r(SBV)
+ return add
+
+ * compute the Delta matrix
+ `noisily' di as text "Computing the Delta matrix..."
+ tempname Delta
+ mata : SBDelta("`bb'","`Delta'")
+
+ *** put the pieces together now
+
+ tempname DeltaId
+
+ * enact the constraints!
+ SBconstr `bb'
+ mat `DeltaId' = `Delta' * diag( r(Fixed) )
+
+ * those should be in there, but it never hurts to fix!
+ if "`e(normalized)'" == "Latent Variance" {
+ * make the last column null
+ mat `DeltaId' = ( `DeltaId'[1...,1...3*`p'] , J(rowsof(`Delta'), 1, 0) )
+ }
+ else if "`e(normalized)'" ~= "" {
+ * normalization by first variable
+ local idvar `e(normalized)'
+ if "`idvar'" ~= "`1'" {
+ di as err "cannot figure out the identification variable"
+ exit 198
+ }
+ mat `DeltaId' = ( J(rowsof(`Delta'), 1, 0) , `DeltaId'[1...,2...] )
+ }
+ local dcnames : colfullnames `bb'
+ local drnames : rownames `Gamma'
+ mat colnames `DeltaId' = `dcnames'
+ mat rownames `DeltaId' = `drnames'
+ return matrix Delta = `DeltaId', copy
+
+ tempname VVV
+ mat `VVV' = ( `DeltaId'' * `V' * `DeltaId' )
+ mat `VVV' = syminv(`VVV')
+ mat `VVV' = `VVV' * ( `DeltaId'' * `V' * `Gamma' * `V' * `DeltaId' ) * `VVV'
+
+ * add the covariance matrix for the means, which is just Sigma/_N
+ * weights!
+ tempname CovM
+ mat `CovM' = ( J(2*`p',colsof(`bb'),0) \ J(`p',2*`p',0) , `Sigma', J(`p',1,0) \ J(1, colsof(`bb'), 0) )
+
+ mat `VVV' = (`VVV' + `CovM')/_N
+ return matrix SBVar = `VVV'
+
+end
+* of satorrabentler
+
+program define SBGamma, rclass
+ syntax varlist
+ unab varlist : `varlist'
+ tokenize `varlist'
+
+ local p: word count `varlist'
+
+ forvalues k=1/`p' {
+ * make up the deviations
+ * weights!!!
+ qui sum ``k'', meanonly
+ tempvar d`k'
+ qui g double `d`k'' = ``k'' - r(mean)
+ local dlist `dlist' `d`k''
+ }
+
+ local pstar = `p'*(`p'+1)/2
+ forvalues k=1/`pstar' {
+ tempvar b`k'
+ qui g double `b`k'' = .
+ local blist `blist' `b`k''
+ }
+
+
+ * convert into vech (z_i-bar z)(z_i-bar z)'
+ mata : SBvechZZtoB("`dlist'","`blist'")
+
+ * blist now should contain the moments around the sample means
+ * we need to get their covariance matrix
+
+ tempname Gamma
+ qui mat accum `Gamma' = `blist', dev nocons
+ * weights!
+ mat `Gamma' = `Gamma'/(_N-1)
+ mata : Gamma = st_matrix( "`Gamma'" )
+
+ * make nice row and column names
+ forvalues i=1/`p' {
+ forvalues j=`i'/`p' {
+ local namelist `namelist' ``i''_X_``j''
+ }
+ }
+ mat colnames `Gamma' = `namelist'
+ mat rownames `Gamma' = `namelist'
+
+ return matrix Gamma = `Gamma'
+
+end
+* of computing Gamma
+
+program define SBV, rclass
+ args A noisily
+ tempname D Ainv V
+ local p = rowsof(`A')
+ `noisily' di as text "Computing the duplication matrix..."
+ mata : Dupl(`p',"`D'")
+ mat `Ainv' = syminv(`A')
+ mat `V' = .5*`D''* (`Ainv' # `Ainv') * `D'
+ return matrix SBV = `V'
+end
+* of computing V
+
+ * need to figure out whether a constraint has the form parameter = value,
+ * and to nullify the corresponding column
+program define SBconstr, rclass
+ args bb
+ tempname Iq
+ mat `Iq' = J(1,colsof(`bb'),1)
+ tokenize $CFA1constr
+ while "`1'" ~= "" {
+ constraint get `1'
+ local constr `r(contents)'
+ gettoken param value : constr, parse("=")
+ * is the RHS indeed a number?
+ local value = substr("`value'",2,.)
+ confirm number `value'
+ * parse the square brackets and turn them into colon
+ * replace the opening brackets with nothing, and closing brackets, with :
+ local param = subinstr("`param'","["," ",1)
+ local param = subinstr("`param'","]",":",1)
+ local param = trim("`param'")
+ local coln = colnumb(`bb',"`param'" )
+ mat `Iq'[1,`coln']=0
+
+ mac shift
+ }
+ return matrix Fixed = `Iq'
+end
+
+
+cap mata : mata drop SBvechZZtoB()
+cap mata : mata drop Dupl()
+cap mata : mata drop SBDelta()
+
+mata:
+void SBvechZZtoB(string dlist, string blist) {
+ // view the deviation variables
+ st_view(data=.,.,tokens(dlist))
+ // view the moment variables
+ // blist=st_local("blist")
+ st_view(moments=.,.,tokens(blist))
+ // vectorize!
+ for(i=1; i<=rows(data); i++) {
+ B = data[i,.]'*data[i,.]
+ moments[i,.] = vech(B)'
+ }
+}
+
+void Dupl(scalar p, string Dname) {
+ pstar = p*(p+1)/2
+ Ipstar = I(pstar)
+ D = J(p*p,0,.)
+ for(k=1;k<=pstar;k++) {
+ D = (D, vec(invvech(Ipstar[.,k])))
+ }
+ st_matrix(Dname,D)
+}
+
+void SBDelta(string bbname, string DeltaName) {
+ bb = st_matrix(bbname)
+ p = (cols(bb)-1)/3
+ Lambda = bb[1,1..p]
+ Theta = bb[1,p+1..2*p]
+ phi = bb[1,cols(bb)]
+ Delta = J(0,cols(bb),.)
+ for(i=1;i<=p;i++) {
+ for(j=i;j<=p;j++) {
+ DeltaRow = J(1,cols(Delta),0)
+ for(k=1;k<=p;k++) {
+ // derivative wrt lambda_k
+ DeltaRow[k] = (k==i)*Lambda[j]*phi + (j==k)*Lambda[i]*phi
+ // derivative wrt sigma^2_k
+ DeltaRow[p+k] = (i==k)*(j==k)
+ }
+ DeltaRow[cols(Delta)] = Lambda[i]*Lambda[j]
+ Delta = Delta \ DeltaRow
+ }
+ }
+ st_matrix(DeltaName,Delta)
+}
+
+end
+* of mata piece
+
+***************************** end of Satorra-Bentler covariance matrix code
+
+exit
+
+History:
+ v.1.0 -- May 19, 2004: basic operation, method d0
+ v.1.1 -- May 19, 2004: identification by -constraint-
+ common -cfa1_ll-
+ from()
+ v.1.2 -- May 21, 2004: method -lf-, robust
+ constraint free
+ v.1.3 -- unknown
+ v.1.4 -- Feb 15, 2005: pweights, arbitrary constraints
+ v.2.0 -- Feb 28, 2006: update to version 9 using Mata
+ v.2.1 -- Apr 11, 2006: whatever
+ v.2.2 -- Apr 13, 2006: Satorra-Bentler standard errors and test corrections
+ -vce- option
+ Apr 14, 2006: degrees of freedom corrected for # constraints
+ July 5, 2006: minor issue with -from(, copy)-
diff --git a/Modules/ado/plus/c/cfa1.hlp b/Modules/ado/plus/c/cfa1.hlp
new file mode 100644
index 0000000..efe8ec3
--- /dev/null
+++ b/Modules/ado/plus/c/cfa1.hlp
@@ -0,0 +1,159 @@
+{smcl}
+{.-}
+help for {cmd:cfa1} {right:author: {browse "http://stas.kolenikov.name/":Stas Kolenikov}}
+{.-}
+
+{title:Confirmatory factor analysis with a single factor}
+
+{p 8 27}
+{cmd:cfa1}
+{it:varlist}
+[{cmd:if} {it:exp}] [{cmd:in} {it:range}]
+[{cmd:aw|pw =} {it:weight}]
+[{cmd:,}
+ {cmd:unitvar}
+ {cmd:free}
+ {cmdab:pos:var}
+ {cmdab:constr:aint(}{it:numlist}{cmd:)}
+ {cmdab:lev:el(}{it:#}{cmd:)}
+ {cmdab:rob:ust}
+ {cmd:vce(robust|oim|opg|sbentler}{cmd:)}
+ {cmd:cluster(}{it:varname}{cmd:)}
+ {cmd:svy}
+ {cmdab:sea:rch(}{it:searchspec}{cmd:)}
+ {cmd:from(}{it:initspecs}{cmd:)}
+ {it:ml options}
+]
+
+{title:Description}
+
+{p}{cmd:cfa1} estimates simple confirmatory factor
+analysis model with a single factor. In this model,
+each of the variables is assumed to be an indicator
+of an underlying unobserved factor with a linear
+dependence between them:
+
+{center:{it:y_i = m_i + l_i xi + delta_i}}
+
+{p}where {it:y_i} is the {it:i}-th variable
+in the {it:varlist}, {it:m_i} is its mean,
+{it:l_i} is the latent variable loading,
+{it:xi} is the latent variable/factor,
+and {it:delta_i} is the measurement error.
+
+{p}The model is estimated by the maximum likelihood
+procedure.
+
+{p}As with all latent variable models, a number
+of identifying assumptions need to be made about
+the latent variable {it:xi}. It is assumed
+to have mean zero, and its scale is determined
+by the first variable in the {it:varlist}
+(i.e., l_1 is set to equal 1). Alternatively,
+identification can be achieved by setting the
+variance of the latent variable to 1 (with option
+{it:unitvar}). More sophisticated identification
+conditions can be achieved by specifying option
+{it:free} and then providing the necessary
+{it:constraint}.
+
+
+{title:Options}
+
+{ul:Identification:}
+
+{p 0 4}{cmd:unitvar} specifies identification by setting
+ the variance of the latent variable to 1.
+
+{p 0 4}{cmd:free} requests to relax all identifying constraints.
+ In this case, the user is responsible for provision
+ of such constraints; otherwise, the estimation process
+ won't converge.
+
+{p 0 4}{cmdab:pos:var} specifies that if one or more of the
+ measurement error variances were estimated to be
+ negative (known as Heywood cases), the model
+ needs to be automatically re-estimated by setting
+ those variances to zero. The likelihood ratio test
+ is then reported comparing the models with and without
+ constraints. If there is only one offending estimate,
+ the proper distribution to refer this likelihood
+ ratio to is a mixture of chi-squares; see
+ {help j_chibar:chi-bar test}. A conservative
+ test is provided by a reference to the chi-square
+ distribution with the largest degrees of freedom.
+ The p-value is then overstated.
+
+{p 0 4}{cmdab:constr:aint(}{it:numlist}{cmd:)} can be used
+ to supply additional constraints. The degrees of freedom
+ of the model may be wrong, then.
+
+{p 0 4}{cmdab:lev:el(}{it:#}{cmd:)} -- see
+ {help estimation_options##level():estimation options}
+
+{ul:Standard error estimation:}
+
+{p 0 4}{cmd:vce(oim|opg|robust|sbentler}
+ specifies the way to estimate the standard errors.
+ See {help vce_option}. {cmd:vce(sbentler)} is an
+ additional Satorra-Bentler estimator popular in
+ structural equation modeling literature that relaxes
+ the assumption of multivariate normality while
+ keeping the assumption of proper structural specification.
+
+{p 0 4}{cmd:robust} is a synonum for {cmd:vce(robust)}.
+
+{p 0 4}{cmd:cluster(}{it:varname}{cmd:)}
+
+{p 0 4}{cmd:svy} instructs {cmd:cfa1} to respect the complex
+ survey design, if one is specified.
+
+{ul:Maximization options: see {help maximize}}
+
+{title:Returned values}
+
+{p}Beside the standard {help estcom:estimation results}, {cmd:cfa1}
+also performs the overall goodness of fit test with results
+saved in {cmd:e(lr_u)}, {cmd:e(df_u)} and {cmd:e(p_u)}
+for the test statistic, its goodness of fit, and the resulting
+p-value. A test vs. the model with the independent data
+is provided with the {help ereturn} results with {cmd:indep}
+suffix. Here, under the null hypothesis,
+the covariance matrix is assumed diagonal.
+
+{p}When {cmd:sbentler} is specified, Satorra-Bentler
+standard errors are computed and posted as {cmd:e(V)},
+with intermediate matrices saved in {cmd:e(SBU)},
+{cmd:e(SBV)}, {cmd:e(SBGamma)} and {cmd:e(SBDelta)}.
+Also, a number of corrected overall fit test statistics
+is reported and saved: T-scaled ({cmd:ereturn} results
+with {cmd:Tscaled} suffix) and T-adjusted
+({cmd:ereturn} resuls with {cmd:Tadj} suffix;
+also, {cmd:e(SBc)} and {cmd:e(SBd)} are the
+scaling constants, with the latter also
+being the approximate degrees of freedom
+of the chi-square test)
+from Satorra and Bentler (1994), and T-double
+bar from Yuan and Bentler (1997)
+(with {cmd:T2} suffix).
+
+
+{title:References}
+
+{p 0 4}{bind:}Satorra, A. and Bentler, P. M. (1994)
+ Corrections to test statistics and standard errors in covariance structure analysis,
+ in: {it:Latent variables analysis}, SAGE.
+
+{p 0 4}{bind:}
+ Yuan, K. H., and Bentler, P. M. (1997)
+ Mean and Covariance Structure Analysis: Theoretical and Practical Improvements.
+ {it:JASA}, {bf:92} (438), pp. 767--774.
+
+
+{title:Also see}
+
+{p 0 21}{bind:}Online: help for {help factor}
+
+{title:Contact}
+
+Stas Kolenikov, kolenikovs {it:at} missouri.edu
diff --git a/Modules/ado/plus/c/cfa1_lf.ado b/Modules/ado/plus/c/cfa1_lf.ado
new file mode 100644
index 0000000..72671c7
--- /dev/null
+++ b/Modules/ado/plus/c/cfa1_lf.ado
@@ -0,0 +1,69 @@
+*! Log likelihood for cfa1: linear form; v.2.1
+program define cfa1_lf
+
+ args lnf $CFA1theta
+ * $CFA1theta contains all the names needed:
+ * $CFA1theta == l_1 ... l_q v_1 ... v_q m_1 ... m_q phi
+
+ gettoken lnf allthenames : 0
+
+ tempvar lnl
+ qui g double `lnl' = .
+
+ nobreak mata: CFA1_NormalLKHDr( "`allthenames'", "$CFA1vars", "`lnl'")
+
+ qui replace `lnf' = `lnl'
+
+end
+
+*! NormalLKHDr: normal likelihood with normal deviates in variables
+*! v.2.1 Stas Kolenikov skolenik@gmail.com
+cap mata: mata drop CFA1_NormalLKHDr()
+mata:
+void CFA1_NormalLKHDr(
+ string parnames, // the parameter names
+ string varnames, // the variables
+ string loglkhd // where the stuff is to be returned
+ ) {
+
+ // declarations
+ real matrix data, lnl, parms // views of the data
+ real matrix lambda, means, vars, phi // parameters
+ real matrix Sigma, WorkSigma, InvWorkSigma, SS // the covariance matrices and temp matrix
+ real scalar p, n // dimension, no. obs
+
+ // get the data in
+ st_view(data=., ., tokens(varnames) )
+ st_view(lnl=., ., tokens(loglkhd) )
+ st_view(parms=., 1, tokens(parnames) )
+
+ n=rows(data)
+ p=cols(data)
+
+ // get the parameters in
+ lambda= parms[1,1..p]
+ vars = parms[1,p+1..2*p]
+ means = parms[1,2*p+1..3*p]
+ phi = parms[1,3*p+1]
+
+ Sigma = lambda'*lambda*phi + diag(vars)
+
+ SS = cholesky(Sigma)
+ InvWorkSigma = solvelower(SS,I(rows(SS)))
+ InvWorkSigma = solveupper(SS',InvWorkSigma)
+ ldetWS = 2*ln(dettriangular(SS))
+
+ for( i=1; i<=n; i++ ) {
+ lnl[i,1] = -.5*(data[i,.]-means)*InvWorkSigma*(data[i,.]-means)' - .5*ldetWS - .5*p*ln(2*pi())
+ }
+
+}
+
+end
+
+
+exit
+
+History:
+v.2.0 March 10, 2006 -- re-written for Stata 9 and Mata
+v.2.1 March 10, 2006 -- everything is moved to Mata
diff --git a/Modules/ado/plus/c/checkfor2.ado b/Modules/ado/plus/c/checkfor2.ado
new file mode 100644
index 0000000..088165c
--- /dev/null
+++ b/Modules/ado/plus/c/checkfor2.ado
@@ -0,0 +1,169 @@
+*!Data management utility: check for existence of variables in a dataset.
+*!Version 1.1 by Amadou B. DIALLO.
+*!This version 1.2 . Updated by Amadou B. DIALLO and Jean-Benoit HARDOUIN.
+*!Authors: Amadou Bassirou DIALLO (Poverty Division, World Bank) and Jean-Benoit HARDOUIN (Regional Health Observatory of Orléans).
+
+program checkfor2 , rclass
+version 8
+syntax anything [if] [in] [, noList Tolerance(real 0) TAble noSUm GENMiss(namelist min=1 max=1) MISsing(string)]
+
+marksample touse
+tempname rat
+local av
+local unav
+local manymissings
+local avnum
+
+quietly count if `touse'
+local tot = r(N)
+
+qui isvar `anything'
+local badlist `r(badlist)'
+local varlist `r(varlist)'
+
+di _n
+if "`table'"!="" {
+ if "`badlist'"!="" {
+ di _col(4) in green "{hline 39}"
+ di _col(4)in green "Unavailable variables: "
+ foreach i of local badlist {
+ di _col(4) in ye "`i'"
+ }
+ di _col(4) in green "{hline 39}"
+ di
+ }
+ di _col(4) in green "{hline 39}"
+ display _col(4) in gr "Existing" _col(15) in gr "Rate of"
+ display _col(4) in gr "Variable" _col(14) "missings" _col(26) "Type" _col(34) "Available"
+ di _col(4) in green "{hline 39}"
+}
+
+tokenize `varlist'
+local nbvar : word count `varlist'
+
+forvalues i=1/`nbvar' {
+ capture assert missing(``i'') if `touse'
+ local ty: type ``i''
+ local tty = substr("`ty'", 1, 3)
+ if !_rc {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is empty in the database." in ye " ``i''" in gr " is not added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" _col(15) in ye "100.00%" _col(26) "`ty'"
+ }
+ local manymissings `manymissings' ``i''
+ }
+ else {
+ if "`table'"=="" {
+ display in ye "``i''" in gr " exists and is not empty."
+ }
+ *Consider type
+ if "`tty'" == "str" {
+ qui count if (``i'' == ""|``i''=="`missing'") & `touse'
+ local num = r(N)
+ scalar `rat' = (`num'/`tot')*100
+ }
+ else {
+ local avnum `avnum' ``i''
+ capture confirm number `missing'
+ if _rc!=0 {
+ quietly count if ``i'' >= . & `touse'
+ }
+ else {
+ quietly count if (``i'' >= .|``i''==`missing') & `touse'
+ }
+ local num = r(N)
+ scalar `rat' = (`num'/`tot')*100
+ }
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has " in ye r(N) in gr " missings."
+ display in gr "Ratio number of missings of" in ye " ``i''" in gr " to total number of observations: " in ye %6.2f `rat' "%"
+ }
+
+ if `rat' <= `tolerance' {
+ local av `av' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " is added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" in ye _col(15) %6.2f `rat' "%" _col(26) "`ty'" _col(34) "X"
+ }
+ }
+ else {
+ local manymissings `manymissings' ``i''
+ if "`table'"=="" {
+ display in ye "``i''" in gr " has too many missings, compared to the tolerance level."
+ display in ye "``i''" in gr " is not added to the available list."
+ }
+ else {
+ display _col(4) in gr "`=abbrev("``i''",8)'" _col(15) in ye %6.2f `rat' "%" _col(26) "`ty'"
+ }
+ }
+ }
+ if "`table'"=="" {
+ di
+ }
+}
+
+if "`table'"!="" {
+ di _col(4) in green "{hline 39}"
+}
+
+return local available `av'
+return local unavailable `badlist'
+return local manymissings `manymissings'
+
+if "`avnum'" ~= ""&"`sum'"=="" {
+ display _newline
+ display in ye _col(14) "Unweighted summary statistics for available variables:" _n
+ capture confirm number `missing'
+ if _rc!=0 {
+ summarize `avnum' if `touse'
+ }
+ else {
+ foreach i of local avnum {
+ summarize `i' if `touse'&`i'!=`missing'
+ }
+ }
+}
+
+if "`list'"== "" {
+ display _newline
+ display in ye _d(97) "_"
+ display _newline
+ if "`badlist'"~="" {
+ display in gr "Unavailable variables: " in ye _col(45) "`badlist'" _n
+ }
+ if "`av'"~="" {
+ display in gr "Available variables: " in ye _col(45) "`av'" _n
+ }
+ if "`manymissings'"~="" {
+ display in gr "Available variables but with too missings: " in ye _col(45) "`manymissings'" _n
+ }
+ display in ye _d(97) "_"
+}
+
+if "`genmiss'" !="" {
+ capture confirm variable `genmiss'
+ if _rc!=0 {
+ qui gen `genmiss' = 0
+ local nbav : word count `av'
+ tokenize `av'
+ forvalues i=1/`nbav' {
+ local ty: type ``i''
+ local tty = substr("`ty'", 1, 3)
+ if "`tty'" == "str" {
+ qui replace `genmiss'=`genmiss'+1 if ``i''=="."
+ }
+ else {
+ qui replace `genmiss'=`genmiss'+1 if ``i''>=.
+ }
+ }
+ }
+ else {
+ di in green "The variable" in ye " `genmiss' " in green "already exists".
+ }
+}
+
+end
diff --git a/Modules/ado/plus/c/checkfor2.hlp b/Modules/ado/plus/c/checkfor2.hlp
new file mode 100644
index 0000000..9a6104e
--- /dev/null
+++ b/Modules/ado/plus/c/checkfor2.hlp
@@ -0,0 +1,88 @@
+{smcl}
+{hline}
+help for {cmd:checkfor2} {right:Amadou B. DIALLO}
+ {right:Jean-Benoit HARDOUIN}
+{hline}
+
+{title:Module to check whether a variable exists or not in a dataset.}
+
+{p 4 8 2}{cmd:checkfor2} {it:anything} [{cmd:,}
+ {cmdab:t:olerance}({it:#}) {cmdab:ta:ble} {cmdab:nol:ist} {cmdab:nosu:m}
+ {cmdab:genm:iss}({it:newvarname}) {cmdab:mis:sing}({it:string})]
+
+{title:Description}
+
+{p 4 4 2}{cmd:checkfor2} is a data management routine to check for existence of variables
+within a (usually big) data set.
+
+{p 4 4 2}{cmd:checkfor2} searchs through the data whether each variable exists.
+The variables are clustered between unavailable variables, available variables with
+a little amount of missing values and available variables with too many missing values.
+
+{p 4 4 2}{cmd:isvar} must be installed ({stata ssc install isvar:ssc install isvar}).
+
+{title:Options}
+
+{p 4 4 2}{it:anything} is composed of variable names or lists of variables,
+
+{p 4 4 2}{cmd:tolerance} is the tolerance level (in percentage) to consider a variable as available, with default 0,
+
+{p 4 4 2}{cmd:nolist} avoids displaying availability status at the end of the process,
+
+{p 4 4 2}{cmd:nosum} avoids displaying summary statistics of available variables,
+
+{p 4 4 2}{cmd:table} displays the results in a table (instead as text),
+
+{p 4 4 2}{cmd:genmiss} creates a new variable containing the number of missing values among the available variables,
+
+{p 4 4 2}{cmd:missing} defines a specific value or string considered as a missing value.
+
+
+{title:Saved results}
+
+{p 4 4 2} {cmd:r(unavailable)} names of unavailable variables.{p_end}
+
+{p 4 4 2} {cmd:r(available)} names of available variables with a small amount of missing values.{p_end}
+
+{p 4 4 2} {cmd:r(manymissings)} names of variables present but with too missings.{p_end}
+
+{title:Examples}
+
+{p 4 4 2}{cmd:. use mydata, clear }{p_end}
+
+{p 4 4 2}{cmd:. checkfor2 x y z , mis(99) genmiss(countmiss) }{p_end}
+
+{p 4 4 2}{cmd:. su `r(available)' }{p_end}
+
+{p 4 4 2}{cmd:. tab countmiss }{p_end}
+
+{p 4 4 2}{cmd:. u bigdataset in 1/100, clear // Big data set}{p_end}
+
+{p 4 4 2}{cmd:. checkfor2 v1 v2 v3 xx yy , nosum tol(5) tab}{p_end}
+
+{p 4 4 2}{cmd:. use `r(available)' using bigdataset, clear }{p_end}
+
+{title:Remarks}
+
+{p 4 4 2}{cmd:checkfor2} and its primary version ({cmd:checkfor}) have been primarily written for comparable surveys such as the Demography and
+Health Surveys (DHS) or the Multiple Indicator Cluster Surveys (MICS). But this could easily applied
+to any other survey.
+
+{title:Authors}
+
+{p 4 4 2}Amadou Bassirou DIALLO.
+Poverty and Health Division, PREM, The World Bank.{p_end}
+{p 4 4 2}Email: {browse "mailto:adiallo5@worldbank.org":adiallo5@worldbank.org}
+
+{p 4 4 2}Jean-Benoit HARDOUIN.
+Regional Health Observatory of Orléans, France.{p_end}
+{p 4 4 2}Email: {browse "mailto:jean-benoit.hardouin@orscentre.org":jean-benoit.hardouin@orscentre.org}
+
+{title:Aknowledgements}
+
+{p 4 4 2}We would like to thank Christophe Rockmore and also Nick Cox
+and Kit Baum for their comments.
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help checkfor}, {help isvar}, {help nmissing}, {help npresent}, {help missing} and {help dropmiss} if installed.{p_end}
diff --git a/Modules/ado/plus/c/choplist.ado b/Modules/ado/plus/c/choplist.ado
new file mode 100644
index 0000000..1cd6ff9
--- /dev/null
+++ b/Modules/ado/plus/c/choplist.ado
@@ -0,0 +1,140 @@
+program def choplist, rclass
+*! NJC 1.4.0 13 December 2000
+* NJC 1.3.0 29 June 2000
+* NJC 1.2.0 7 June 2000
+* NJC 1.1.0 22 Dec 1999
+* NJC 1.0.0 20 Dec 1999 after discussion with Kit Baum
+ version 6.0
+ gettoken list 0 : 0, parse(",")
+ if "`list'" == "" | "`list'" == "," {
+ di in r "nothing in list"
+ exit 198
+ }
+ syntax , [ Pos(str) Value(str asis) Length(str) Char(int 0) /*
+ */ Noisily Global(str) ]
+
+ if "`global'" != "" {
+ tokenize `global'
+ args global1 global2 global3
+ if "`global3'" != "" {
+ di in r "global( ) must contain at most 2 names"
+ exit 198
+ }
+ if (length("`global1'") > 8) | (length("`global2'") > 8) {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+ }
+
+ local nopts = /*
+ */ ("`pos'" != "") + (`"`value'"' != "") + /*
+ */ ("`length'" != "") + (`char' != 0)
+ if `nopts' != 1 {
+ di in r "must specify pos( ), value( ), length( ) or char( )"
+ exit 198
+ }
+
+ * as string <= contains quote
+ local asstr = index(`"`value'"', `"""')
+
+ tokenize `list'
+ local n : word count `list'
+
+ if "`length'" != "" | `char' != 0 {
+ local i = 1
+ while `i' <= `n' {
+ local len = length("``i''")
+ if `len' > 80 {
+ di in r "cannot handle word length > 80"
+ exit 498
+ }
+ local i = `i' + 1
+ }
+ }
+
+ local i = 1
+ if "`pos'" != "" {
+ local negsign = index("`pos'", "-")
+ if `negsign' {
+ local pos1 = substr("`pos'",1,`negsign' - 1)
+ local pos2 = substr("`pos'",`negsign', .)
+ local pos2 = `n' + 1 + `pos2'
+ local pos "`pos1'`pos2'"
+ capture confirm integer number `pos'
+ if _rc == 0 { local pos ">= `pos'" }
+ }
+ else {
+ capture confirm integer number `pos'
+ if _rc == 0 { local pos "<= `pos'" }
+ }
+ while `i' <= `n' {
+ if `i' `pos' { local list1 "`list1' ``i''" }
+ else local list2 "`list2' ``i''"
+ local i = `i' + 1
+ }
+ }
+ else if "`value'" != "" {
+ capture confirm number `value'
+ if _rc == 0 { local value "<= `value'" }
+ if `asstr' {
+ while `i' <= `n' {
+ if "``i''" `value' {
+ local list1 `"`list1' ``i''"'
+ }
+ else local list2 `"`list2' ``i''"'
+ local i = `i' + 1
+ }
+ }
+ else {
+ while `i' <= `n' {
+ if ``i'' `value' {
+ local list1 "`list1' ``i''"
+ }
+ else local list2 "`list2' ``i''"
+ local i = `i' + 1
+ }
+ }
+ }
+ else if "`length'" != "" {
+ capture confirm number `length'
+ if _rc == 0 { local length "<= `length'" }
+ while `i' <= `n' {
+ if length("``i''") `length' {
+ local list1 "`list1' ``i''"
+ }
+ else local list2 "`list2' ``i''"
+ local i = `i' + 1
+ }
+ }
+ else {
+ if `char' >= 0 {
+ while `i' <= `n' {
+ local one = substr("``i''",1,`char')
+ local two = substr("``i''",`char'+1,.)
+ local list1 "`list1' `one'"
+ local list2 "`list2' `two'"
+ local i = `i' + 1
+ }
+ }
+ else if `char' < 0 {
+ while `i' <= `n' {
+ local one = substr("``i''",`char',.)
+ local ltwo = length("``i''") + `char'
+ local two = substr("``i''",1,`ltwo')
+ local list1 "`list1' `one'"
+ local list2 "`list2' `two'"
+ local i = `i' + 1
+ }
+ }
+ }
+
+ if "`noisily'" != "" {
+ di in g "list 1: " in y `"`list1'"'
+ di in g "list 2: " in y `"`list2'"'
+ }
+ if "`global1'" != "" { global `global1' `"`list1'"' }
+ if "`global2'" != "" { global `global2' `"`list2'"' }
+ return local list1 `"`list1'"'
+ return local list2 `"`list2'"'
+end
+
diff --git a/Modules/ado/plus/c/choplist.hlp b/Modules/ado/plus/c/choplist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/c/choplist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/c/cmdchk.ado b/Modules/ado/plus/c/cmdchk.ado
new file mode 100644
index 0000000..56c0776
--- /dev/null
+++ b/Modules/ado/plus/c/cmdchk.ado
@@ -0,0 +1,66 @@
+*! version 1.0.4 PR 30sep2005
+* Based on private version 6.1.4 of frac_chk, PR 25aug2004
+program define cmdchk, sclass
+ version 7
+ local cmd `1'
+ mac shift
+ local cmds `*'
+ sret clear
+ if substr("`cmd'",1,3)=="reg" {
+ local cmd regress
+ }
+ if "`cmds'"=="" {
+ tokenize clogit cnreg cox ereg fit glm logistic logit poisson probit /*
+ */ qreg regress rreg weibull xtgee streg stcox stpm stpmrs /*
+ */ ologit oprobit mlogit nbreg
+ }
+ else tokenize `cmds'
+ sret local bad 0
+ local done 0
+ while "`1'"!="" & !`done' {
+ if "`1'"=="`cmd'" {
+ local done 1
+ }
+ mac shift
+ }
+ if !`done' {
+ sret local bad 1
+ *exit
+ }
+ /*
+ dist=0 (normal), 1 (binomial), 2 (poisson), 3 (cox), 4 (glm),
+ 5 (xtgee), 6 (ereg/weibull), 7 (stcox, streg, stpm, stpmrs).
+ */
+ if "`cmd'"=="logit" | "`cmd'"=="probit" /*
+ */ |"`cmd'"=="clogit"| "`cmd'"=="logistic" /*
+ */ |"`cmd'"=="mlogit"| "`cmd'"=="ologit" | "`cmd'"=="oprobit" {
+ sret local dist 1
+ }
+ else if "`cmd'"=="poisson" {
+ sret local dist 2
+ }
+ else if "`cmd'"=="cox" {
+ sret local dist 3
+ }
+ else if "`cmd'"=="glm" {
+ sret local dist 4
+ }
+ else if "`cmd'"=="xtgee" {
+ sret local dist 5
+ }
+ else if "`cmd'"=="cnreg" | "`cmd'"=="ereg" | "`cmd'"=="weibull" | "`cmd'"=="nbreg" {
+ sret local dist 6
+ }
+ else if "`cmd'"=="stcox" | "`cmd'"=="streg" | "`cmd'"=="stpm" | "`cmd'"=="stpmrs" {
+ sret local dist 7
+ }
+ else if substr("`cmd'",1,2)=="st" {
+ sret local dist 7
+ }
+ else sret local dist 0
+
+ sret local isglm = (`s(dist)'==4)
+ sret local isqreg = ("`cmd'"=="qreg")
+ sret local isxtgee= (`s(dist)'==5)
+ sret local isnorm = ("`cmd'"=="regress"|"`cmd'"=="fit"|"`cmd'"=="rreg")
+end
diff --git a/Modules/ado/plus/c/collist.ado b/Modules/ado/plus/c/collist.ado
new file mode 100644
index 0000000..8e216e8
--- /dev/null
+++ b/Modules/ado/plus/c/collist.ado
@@ -0,0 +1,33 @@
+program def collist
+*! NJC 1.0.0 22 Dec 1999
+ version 6
+ gettoken list 0 : 0, parse(",")
+ if "`list'" == "" | "`list'" == "," {
+ di in r "nothing in list"
+ exit 198
+ }
+ syntax [ , Format(str) NUmber ]
+
+ tokenize `list'
+
+ if "`number'" != "" {
+ local n : word count `list'
+ local ndigits = length("`n'")
+ local number = 0
+ }
+
+ * asstr >0 string format
+ * asstr 0 numeric format
+ * asstr -1 default
+ local asstr = cond("`format'" != "",index("`format'", "s"), -1)
+
+ while "`1'" != "" {
+ if "`number'" != "" {
+ local number = `number' + 1
+ local num : di %`ndigits'.0f `number' ". "
+ }
+ if `asstr' { di in g "`num'" `format' in y `"`1'"' }
+ else di in g "`num'" `format' in y `1'
+ mac shift
+ }
+end
diff --git a/Modules/ado/plus/c/collist.hlp b/Modules/ado/plus/c/collist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/c/collist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/c/concord.ado b/Modules/ado/plus/c/concord.ado
new file mode 100644
index 0000000..39e0f3b
--- /dev/null
+++ b/Modules/ado/plus/c/concord.ado
@@ -0,0 +1,433 @@
+*! 3.0.7 9aug2007 TJS & NJC fixed Stata 10 bug by adding missing -version-
+* 3.0.6 14may2006 TJS & NJC fixed Stata 9 bug with -by()-
+// 3.0.5 22aug2005 Stata 8 - fixed legend(off)
+// 3.0.4 27jan2005 TJS & NJC rewrite for Stata 8 + more for graphs
+// 3.0.3 6oct2004 TJS & NJC rewrite for Stata 8
+// 3.0.2 6oct2004 TJS & NJC rewrite for Stata 8
+// 3.0.1 4oct2004 TJS & NJC rewrite for Stata 8 + fixes + noref
+// 3.0.0 27jul2004 TJS & NJC rewrite for Stata 8
+// 3.0.0 19jul2004 TJS & NJC rewrite for Stata 8
+// 2.2.9 14jan2003 TJS & NJC handling of [ ] within connect()
+// 2.2.8 2jan2003 TJS & NJC handling of [ ] within symbol()
+// 2.2.7 30jan2002 TJS & NJC rho_se corrected (SJ2-2: st0015)
+// 2.2.6 10dec2001 TJS & NJC bug fixes (labels, diag line)
+// 2.2.5 23apr2001 TJS & NJC sortpreserve
+// 2.2.4 24jan2001 TJS & NJC l1title for loa
+// 2.2.3 8sep2000 TJS & NJC bug fixes & mods (STB-58: sg84.3)
+// 2.2.0 16dec1999 TJS & NJC version 6 changes (STB-54: sg84.2)
+// 2.1.6 18jun1998 TJS & NJC STB-45 sg84.1
+// 2.0.2 6mar1998 TJS & NJC STB-43 sg84
+//
+// syntax: concord vary varx [fw] [if] [in] [,
+// BY(varname) Summary LEvel(real `c(level)')
+// CCC(str) LOA(str) QNORMD(str) ]
+
+program concord, rclass sortpreserve
+// Syntax help
+ if "`1'" == "" {
+ di "{p}{txt}Syntax is: {inp:concord} " ///
+ "{it:vary varx} [{it:weight}] " ///
+ "[{inp:if} {it:exp}] [{inp:in} {it:range}] " ///
+ "[, {inp:by(}{it:byvar}{inp:)} " ///
+ "{inp:summary level(}{it:#}{inp:)} " ///
+ "{inp:ccc}[{inp:(noref} {it:ccc_options}{inp:)}] " ///
+ "{inp:loa}[{inp:(noref regline} {it:loa_options}{inp:)}] " ///
+ "{inp:qnormd}[{inp:(}{it:qnormd_options}{inp:)}] {p_end}"
+ exit 0
+ }
+
+// Setup
+ version 8
+ syntax varlist(numeric min=2 max=2) ///
+ [fw] ///
+ [if] [in] ///
+ [ , BY(varname) ///
+ Summary ///
+ LEvel(real `c(level)') ///
+ ccc(str asis) ///
+ CCC2 ///
+ loa(str asis) ///
+ LOA2 ///
+ qnormd(str asis) ///
+ QNORMD2 * ]
+
+ marksample touse
+ qui count if `touse'
+ if r(N) == 0 error 2000
+
+ tokenize `varlist'
+
+// Set temporary names
+ tempvar d d2 db dll dul m byg kk bylabel
+ tempname dsd zv k xb yb sx2 sy2 r rp sxy p u sep z zp
+ tempname t set ll ul llt ult rdm Fdm zt ztp sd1 sd2 sl
+
+// Set up wgt
+ if "`weight'" != "" local wgt "[`weight'`exp']"
+
+// Generate CI z-value and label from Level()
+ if `level' < 1 local level = `level' * 100
+ scalar `zv' = -1 * invnorm((1 - `level' / 100) / 2)
+ local rl = `level'
+ local level : di %7.0g `level'
+ local level = ltrim("`level'")
+
+// Generate BY groups
+ qui {
+ bysort `touse' `by' : gen byte `byg' = _n == 1 if `touse'
+ if "`by'" != "" gen `kk' = _n if `byg' == 1
+ replace `byg' = sum(`byg')
+ local byn = `byg'[_N]
+
+// Generate `by' labels -- if required
+ if "`by'" != "" {
+ capture decode `by', gen(`bylabel')
+ if _rc != 0 {
+ local type : type `by'
+ gen `type' `bylabel' = `by'
+ }
+ }
+ }
+
+// Print title
+ di
+ di as txt "Concordance correlation coefficient (Lin, 1989, 2000):"
+
+// Do calculations
+ forval j = 1/`byn' { /* start of loop for each `by' group */
+ di
+ if "`by'" != "" {
+ sort `kk'
+ di as txt "{hline}"
+ di as txt "-> `by' = " `bylabel'[`j'] _n
+ local byl : di "`by' = " `bylabel'[`j']
+ }
+
+// LOA (Bland & Altman) calculations
+ qui {
+ gen `d' = `1' - `2'
+ gen `d2' = `d'^2
+ su `d' if `byg' == `j' `wgt'
+ gen `db' = r(mean)
+ scalar `dsd' = r(sd)
+ gen `dll' = `db' - `zv' * `dsd'
+ gen `dul' = `db' + `zv' * `dsd'
+ gen `m' = (`1' + `2') / 2
+ }
+
+// Concordance calculations
+ qui su `1' if `byg' == `j' `wgt'
+ scalar `k' = r(N)
+ scalar `yb' = r(mean)
+ scalar `sy2' = r(Var) * (`k' - 1) / `k'
+ scalar `sd1' = r(sd)
+
+ qui su `2' if `byg' == `j' `wgt'
+ scalar `xb' = r(mean)
+ scalar `sx2' = r(Var) * (`k' - 1) / `k'
+ scalar `sd2' = r(sd)
+
+ qui corr `1' `2' if `byg' == `j' `wgt'
+ scalar `r' = r(rho)
+ scalar `sl' = sign(`r') * `sd1' / `sd2'
+
+ scalar `rp' = min(tprob(r(N) - 2, r(rho) * sqrt(r(N) - 2) ///
+ / sqrt(1 - r(rho)^2)) ,1)
+ scalar `sxy' = `r' * sqrt(`sx2' * `sy2')
+ scalar `p' = 2 * `sxy' / (`sx2' + `sy2' + (`yb' - `xb')^2)
+ scalar `u' = (`yb' - `xb') / (`sx2' * `sy2')^.25
+
+// --- variance, test, and CI for asymptotic normal approximation
+ // scalar `sep' = sqrt(((1 - ((`r')^2)) * (`p')^2 * (1 -
+ // ((`p')^2)) / (`r')^2 + (4 * (`p')^3 * (1 - `p') * (`u')^2
+ // / `r') - 2 * (`p')^4 * (`u')^4 / (`r')^2 ) / (`k' - 2))
+// Corrected se: per Lin (March 2000) Biometrics 56:325-5.
+ #delimit ;
+ scalar `sep' = sqrt(((1 - ((`r')^2)) * (`p')^2 * (1 -
+ ((`p')^2)) / (`r')^2 + (2 * (`p')^3 * (1 - `p') * (`u')^2
+ / `r') - .5 * (`p')^4 * (`u')^4 / (`r')^2 ) / (`k' - 2));
+ #delimit cr
+ scalar `z' = `p' / `sep'
+ scalar `zp' = 2 * (1 - normprob(abs(`z')))
+ scalar `ll' = `p' - `zv' * `sep'
+ scalar `ul' = `p' + `zv' * `sep'
+
+// --- statistic, variance, test, and CI for inverse hyperbolic
+// tangent transform to improve asymptotic normality
+ scalar `t' = ln((1 + `p') / (1 - `p')) / 2
+ scalar `set' = `sep' / (1 - ((`p')^2))
+ scalar `zt' = `t' / `set'
+ scalar `ztp' = 2 * (1 - normprob(abs(`zt')))
+ scalar `llt' = `t' - `zv' * `set'
+ scalar `ult' = `t' + `zv' * `set'
+ scalar `llt' = (exp(2 * `llt') - 1) / (exp(2 * `llt') + 1)
+ scalar `ult' = (exp(2 * `ult') - 1) / (exp(2 * `ult') + 1)
+
+// Print output
+ di as txt " rho_c SE(rho_c) Obs [" _c
+ if index("`level'",".") {
+ di as txt %6.1f `level' "% CI ] P CI type"
+ }
+ else di as txt " `level'% CI ] P CI type"
+
+ di as txt "{hline 63}"
+ di as res %6.3f `p' %10.3f `sep' %8.0f `k' %10.3f `ll' _c
+ di as res %7.3f `ul' %9.3f `zp' as txt " asymptotic"
+ di as res _dup(24) " " %10.3f `llt' %7.3f `ult' %9.3f `ztp' _c
+ di as txt " z-transform"
+
+ di _n as txt "Pearson's r =" as res %7.3f `r' _c
+ di as txt " Pr(r = 0) =" as res %6.3f `rp' _c
+ di as txt " C_b = rho_c/r =" as res %7.3f `p' / `r'
+ di as txt "Reduced major axis: Slope = " as res %9.3f `sl' _c
+ di as txt " Intercept = " as res %9.3f `yb'-`xb'*`sl'
+ di _n as txt "Difference = `1' - `2'"
+ di _n as txt " Difference" _c
+ if index("`level'", ".") {
+ di _col(33) as txt %6.1f `level' "% Limits Of Agreement"
+ }
+ else di _col(33) as txt " `level'% Limits Of Agreement"
+ di as txt " Average Std Dev. (Bland & Altman, 1986)"
+ di as txt "{hline 63}"
+ di as res %10.3f `db' %12.3f `dsd' _c
+ di as res " " %11.3f `dll' %11.3f `dul'
+
+ qui corr `d' `m' if `byg' == `j' `wgt'
+ scalar `rdm' = r(rho)
+ di _n as txt "Correlation between difference and mean =" _c
+ local fmt = cond(r(rho) < 0, "%7.3f", "%6.3f")
+ di as res `fmt' r(rho)
+
+ su `d2' if `byg' == `j' `wgt', meanonly
+ local sumd2 = r(sum)
+ qui reg `d' `m' if `byg' == `j' `wgt'
+ scalar `Fdm' = ((`sumd2' - e(rss)) / 2) / (e(rss) / e(df_r))
+ di _n as txt "Bradley-Blackwood F = " ///
+ as res %4.3f `Fdm' ///
+ as txt " (P = " %6.5f ///
+ as res 1 - F(2, e(df_r), `Fdm') ///
+ as txt ")"
+
+ if "`summary'" != "" su `1' `2' if `byg' == `j' `wgt'
+
+// setup local options for passing to graph routines
+ if "`byl'" != "" local byls byl("`byl'")
+ if "`level'" != "" local levs level(`level')
+
+// set more if needed
+ if (`"`loa'`loa2'"' != "" & `"`qnormd'`qnormd2'"' != "") | ///
+ (`"`loa'`loa2'"' != "" & `"`ccc'`ccc2'"' != "") | ///
+ (`"`ccc'`ccc2'"' != "" & `"`qnormd'`qnormd2'"' != "") {
+
+ local moreflag "more"
+ }
+
+// loa graph
+ if `"`loa'`loa2'"' != "" {
+ gphloa `2' `1' `dll' `db' `dul' `d' `m' `byg' ///
+ `wgt', j(`j') byn(`byn') `byls' `levs' `loa' `options'
+
+ `moreflag'
+ }
+
+// qnormd graph
+ if `"`qnormd'`qnormd2'"' != "" {
+ gphqnormd `2' `1' `d' `byg' ///
+ `wgt', j(`j') byn(`byn') `byls' `levs' `qnormd' `options'
+
+ `moreflag'
+ }
+
+// ccc graph
+ if `"`ccc'`ccc2'"' != "" {
+ local sll = `sl'
+ local xbl = `xb'
+ local ybl = `yb'
+ gphccc `1' `2' `byg' `wgt', j(`j') ///
+ xb(`xbl') yb(`ybl') sl(`sll') byn(`byn') `byls' `ccc' `options'
+ }
+
+ if `byn' > 1 {
+ capture drop `d'
+ capture drop `d2'
+ capture drop `db'
+ capture drop `dll'
+ capture drop `dul'
+ capture drop `m'
+ }
+
+ } /* end of loop for each `by' group */
+
+// save globals
+ if `byn' == 1 {
+ return scalar N = `k'
+ return scalar rho_c = `p'
+ return scalar se_rho_c = `sep'
+ return scalar asym_ll = `ll'
+ return scalar asym_ul = `ul'
+ return scalar z_tr_ll = `llt'
+ return scalar z_tr_ul = `ult'
+ return scalar C_b = `p' / `r'
+ return scalar diff = `db'
+ return scalar sd_diff = `dsd'
+ return scalar LOA_ll = `dll'
+ return scalar LOA_ul = `dul'
+ return scalar rdm = `rdm'
+ return scalar Fdm = `Fdm'
+
+// double save globals
+// now undocumented as of 3.0.0
+ global S_1 = `k'
+ global S_2 = `p'
+ global S_3 = `sep'
+ global S_4 = `ll'
+ global S_5 = `ul'
+ global S_6 = `llt'
+ global S_7 = `ult'
+ global S_8 = `p' / `r'
+ global S_9 = `db'
+ global S_10 = `dsd'
+ global S_11 = `dll'
+ global S_12 = `dul'
+ }
+end
+
+program gphloa
+// loa graph
+ version 8
+ syntax varlist(numeric min=2) [fw] ///
+ [ , J(int 1) BYN(int 1) BYL(str) REGline LEvel(real `c(level)') ///
+ plot(str asis) noREF * ]
+
+ tokenize `varlist'
+ args two one dll db dul d m byg
+ if "`weight'" != "" local wgt "[`weight'`exp']"
+
+ if `"`byl'"' != "" local t2title `"t2title(`byl')"'
+
+ local name2 : variable label `2'
+ local name1 : variable label `1'
+ local lnth = length(`"`name2'"') + length(`"`name1'"')
+ if `"`name2'"' == `""' | `lnth' > 50 local name2 "`2'"
+ if `"`name1'"' == `""' | `lnth' > 50 local name1 "`1'"
+
+ qui if "`regline'" != "" {
+ tempvar fit
+ regress `d' `m' if `byg' == `j' `wgt'
+ predict `fit'
+ }
+
+ if "`ref'" == "" {
+ local ord 2 3
+ if "`regline'" != "" local ord 2 3 4
+ local zero yli(0, lstyle(refline)) yscale(range(0)) ylabel(0, add) ///
+ legend(on order(`ord') label(2 observed average agreement) ///
+ label(3 `"`level'% limits of agreement"') label(4 regression line)) ///
+ caption("y=0 is line of perfect average agreement")
+ }
+
+ graph twoway line `dll' `db' `dul' `fit' `m' if `byg' == `j', ///
+ clcolor(red purple red green) sort ///
+ || scatter `d' `m' if `byg' == `j' ///
+ , ms(oh) `t2title' ///
+ yti(`"Difference of `name2' and `name1'"') ///
+ xti(`"Mean of `name2' and `name1'"') ///
+ caption("`level'% Limits Of Agreement") legend(off) `zero' ///
+ `options' ///
+ || `plot'
+
+ if `byn' > 1 more
+end
+
+program gphqnormd, sort
+// normal prob plot
+// note: logic pilfered from qnorm
+ version 8
+ syntax varlist(numeric min=2) [fw] ///
+ [ , J(int 1) BYN(int 1) BYL(str) LEvel(real `c(level)') ///
+ plot(str asis) * ]
+
+ args two one d byg
+ if "`weight'" != "" local wgt "[`weight'`exp']"
+ else local exp 1
+
+ local name2 : variable label `2'
+ local name1 : variable label `1'
+ local lnth = length(`"`name2'"') + length(`"`name1'"')
+ if `"`name2'"' == `""' | `lnth' > 50 local name2 "`2'"
+ if `"`name1'"' == `""' | `lnth' > 50 local name1 "`1'"
+
+ tempvar Z Psubi touse2
+ mark `touse2' if `byg' == `j'
+ qui {
+ gsort -`touse2' `d'
+ gen `Psubi' = sum(`touse2' * `exp')
+ replace `Psubi' = cond(`touse2' == 0, ., `Psubi'/(`Psubi'[_N] + 1))
+ su `d' if `touse2' == 1 `wgt'
+ gen float `Z' = invnorm(`Psubi') * r(sd) + r(mean)
+ label var `Z' "Inverse Normal"
+ local xttl : var label `Z'
+ local yttl `"Difference of `name2' and `name1'"'
+ }
+
+ if `"`byl'"' != "" local t2title `"t2title(`byl')"'
+
+ graph twoway ///
+ (scatter `d' `Z', ///
+ sort ///
+ ytitle(`"`yttl'"') ///
+ xtitle(`"`xttl'"') ///
+ `t2title' ///
+ `options' ///
+ ) ///
+ (function y=x, ///
+ range(`Z') ///
+ n(2) ///
+ clstyle(refline) ///
+ yvarlabel("Reference") ///
+ yvarformat(`fmt') ///
+ ) ///
+ , legend(off) ///
+ || `plot'
+
+ if `byn' > 1 more
+end
+
+program gphccc
+ version 8
+//-----------------------------------------------------
+// ccc graph
+// ----------------------------------------------------
+ syntax varlist(numeric min=2) [fw] [ , J(int 1) XB(real 0) noREF ///
+ YB(real 0) SL(real 0) BYN(int 1) BYL(str) plot(str asis) LEGEND(str) * ]
+
+ tokenize `varlist'
+ tempvar byg rmaxis
+ local byg `3'
+ if "`weight'" != "" local wgt "[`weight'`exp']"
+
+ local yttl : variable label `1'
+ if `"`yttl'"' == "" local yttl "`1'"
+ local xttl : variable label `2'
+ if `"`xttl'"' == "" local xttl "`2'"
+
+ if "`ref'" == "" local lopc || function y = x, ra(`2') clstyle(refline) ///
+ legend(on order(2 "reduced major axis" 3 "line of perfect concordance"))
+
+ if "`legend'" != "" {
+ local legnd "legend(`legend')"
+ }
+
+// Graph concordance plot
+ qui gen `rmaxis' = `sl' * (`2' - `xb') + `yb'
+
+ graph twoway scatter `1' `rmaxis' `2' ///
+ if `byg' == `j' `wgt', ///
+ sort connect(none line) ms(oh none) ///
+ yti(`"`yttl'"') xti(`"`xttl'"') legend(off) `lopc' ///
+ `options' ///
+ || `plot'
+
+ if `byn' > 1 more
+end
+
diff --git a/Modules/ado/plus/c/concord.dlg b/Modules/ado/plus/c/concord.dlg
new file mode 100644
index 0000000..b4b230b
--- /dev/null
+++ b/Modules/ado/plus/c/concord.dlg
@@ -0,0 +1,183 @@
+/* Dialog (Version 3.0.1) by: T. J. Steichen, steichen@triad.rr.com
+
+concord VERSION 3.0.3 6oct2004
+
+ syntax: concord vary varx [fw] [if] [in] [,
+ BY(varname) Summary LEvel(real 95) ccc[(noREF ccc_graph_options)]
+ loa[(noREF REGline loa_graph_options)] qnormd[(qnormd_graph_options}] ]
+
+
+Install in User Statistics menu via:
+ . window menu append item "stUserStatistics" "&concord (Concordance correlation coefficient)" "db concord3"
+ . window menu refresh
+To permanently install, place the commands in your -profile.do- file.
+*/
+
+VERSION 8.0
+
+INCLUDE _std_small
+INCLUDE header
+
+HELP hlp1, view("help concord")
+RESET res1
+
+DIALOG main, label("concord - Concordance correlation coefficient") tabtitle("Main")
+BEGIN
+ TEXT tx_yvar _lft _top 150 ., ///
+ label("Y Variable:")
+ VARNAME vn_yvar @ _ss @ ., ///
+ label("Y Variable")
+ TEXT tx_xvar 180 _top 150 ., ///
+ label("X Variable:")
+ VARNAME vn_xvar @ _ss @ ., ///
+ label("X Variable")
+
+ CHECKBOX cb_by 10 70 50 ., ///
+ label("By:") ///
+ onclickon(main.vn_by.enable) ///
+ onclickoff(main.vn_by.disable)
+ VARNAME vn_by 60 70 270 ., ///
+ label("By Variable") ///
+ option("by")
+
+ CHECKBOX cb_summary 10 100 300 ., ///
+ label("Show Summary") ///
+ option("summary")
+
+ CHECKBOX cb_level 10 130 50 ., ///
+ label("Level:") ///
+ onclickon(main.ed_level.enable) ///
+ onclickoff(main.ed_level.disable)
+ EDIT ed_level 60 @ 40 ., ///
+ label("Level") ///
+ numonly default(global S_level) ///
+ option("level")
+END
+
+INCLUDE ifin
+INCLUDE weights_f
+
+DIALOG graph, tabtitle("Graph")
+BEGIN
+ CHECKBOX cb_ccc 20 10 150 ., ///
+ label("Concordance") ///
+ onclickon(script ccc_on) ///
+ onclickoff(script ccc_off) ///
+ option("ccc")
+ CHECKBOX cb_ccc_ref 40 30 140 ., ///
+ label("No CCC Reference Line")
+ CHECKBOX cb_ccc_opt 40 50 90 ., ///
+ label("CCC Options:") ///
+ onclickon(graph.ed_ccc_opt.enable) ///
+ onclickoff(graph.ed_ccc_opt.disable)
+ EDIT ed_ccc_opt 130 50 200 ., ///
+ label("CCC Opts")
+
+ CHECKBOX cb_loa 20 70 150 ., ///
+ label("Limits of Agreement") ///
+ onclickon(script loa_on) ///
+ onclickoff(script loa_off) ///
+ option("loa")
+ CHECKBOX cb_loa_ref 40 90 140 ., ///
+ label("No LOA Reference Line")
+ CHECKBOX cb_loa_reg 40 110 140 ., ///
+ label("Regression Line")
+ CHECKBOX cb_loa_opt 40 130 90 ., ///
+ label("LOA Options:") ///
+ onclickon(graph.ed_loa_opt.enable) ///
+ onclickoff(graph.ed_loa_opt.disable)
+ EDIT ed_loa_opt 130 130 200 ., ///
+ label("LOA Opts")
+
+ CHECKBOX cb_qnormd 20 150 150 ., ///
+ label("Differences Normal plot") ///
+ onclickon(graph.cb_qnormd_opt.enable) ///
+ onclickoff(graph.cb_qnormd_opt.disable) ///
+ option("qnormd")
+ CHECKBOX cb_qnormd_opt 40 170 90 ., ///
+ label("QND Options:") ///
+ onclickon(graph.ed_qnormd_opt.enable) ///
+ onclickoff(graph.ed_qnormd_opt.disable)
+ EDIT ed_qnormd_opt 130 170 200 ., ///
+ label("QND Opts")
+END
+
+SCRIPT ccc_on
+BEGIN
+ graph.cb_ccc_ref.enable
+ graph.cb_ccc_opt.enable
+END
+
+SCRIPT ccc_off
+BEGIN
+ graph.cb_ccc_ref.disable
+ graph.cb_ccc_opt.disable
+END
+
+SCRIPT loa_on
+BEGIN
+ graph.cb_loa_ref.enable
+ graph.cb_loa_reg.enable
+ graph.cb_loa_opt.enable
+END
+
+SCRIPT loa_off
+BEGIN
+ graph.cb_loa_ref.disable
+ graph.cb_loa_reg.disable
+ graph.cb_loa_opt.disable
+END
+
+PROGRAM command
+BEGIN
+ put "concord "
+ varlist main.vn_yvar main.vn_xvar
+ INCLUDE _weights_pr
+ INCLUDE _ifin_pr
+ beginoptions
+ optionarg main.vn_by
+ option main.cb_summary
+ optionarg main.ed_level
+ if graph.cb_ccc {
+ put "ccc"
+ if graph.cb_ccc_ref | graph.cb_ccc_opt {
+ put "("
+ }
+ if graph.cb_ccc_ref {
+ put "noref "
+ }
+ if graph.cb_ccc_opt {
+ put graph.ed_ccc_opt
+ }
+ if graph.cb_ccc_ref | graph.cb_ccc_opt {
+ put ") "
+ }
+ }
+ if graph.cb_loa {
+ put "loa"
+ if graph.cb_loa_ref | graph.cb_loa_opt | graph.cb_loa_reg {
+ put "("
+ }
+ if graph.cb_loa_ref {
+ put "noref "
+ }
+ if graph.cb_loa_reg {
+ put "regline "
+ }
+ if graph.cb_loa_opt {
+ put graph.ed_loa_opt
+ }
+ if graph.cb_loa_ref | graph.cb_loa_opt | graph.cb_loa_reg {
+ put ") "
+ }
+ }
+ if graph.cb_qnormd {
+ put "qnormd"
+ if graph.cb_qnormd_opt {
+ put "("
+ put graph.ed_qnormd_opt
+ put ") "
+ }
+ }
+ endoptions
+END
diff --git a/Modules/ado/plus/c/concord.hlp b/Modules/ado/plus/c/concord.hlp
new file mode 100644
index 0000000..8d29923
--- /dev/null
+++ b/Modules/ado/plus/c/concord.hlp
@@ -0,0 +1,275 @@
+{smcl}
+{* 6oct2004/23aug2005/14may2006/9aug2007}
+{hline}
+{hi:help concord} {right:(SJ7-3: st0015_4)}
+{hline}
+
+{title:Title}
+
+{p2colset 5 16 18 2}{...}
+{p2col:{hi:concord} {hline 2}}Concordance correlation coefficient and associated measures, tests, and graphs{p_end}
+{p2colreset}{...}
+
+
+{title:Syntax}
+
+{p 8 17 2}
+{cmd:concord}
+{it:vary} {it:varx}
+{ifin}
+{weight}
+[{cmd:,}
+{cmd:by(}{it:byvar}{cmd:)}
+{cmdab:s:ummary}
+{cmdab:le:vel(}{it:#}{cmd:)}
+{cmd:ccc}[{cmd:(noref} {it:ccc_options}{cmd:)}]
+{cmd:loa}[{cmd:(noref} {cmdab:reg:line} {it:loa_options}{cmd:)}]
+{cmd:qnormd}[{cmd:(}{it:qnormd_options}{cmd:)}]]
+
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:concord} computes Lin's (1989, 2000) concordance correlation coefficient
+for agreement on a continuous measure obtained by two persons or methods. (The
+measure was introduced earlier by Krippendorff (1970).) The concordance
+correlation coefficient combines measures of both precision and accuracy to
+determine how far the observed data deviate from the line of perfect
+concordance (i.e., the line at 45 degrees on a square scatter plot). Lin's
+coefficient increases in value as a function of the nearness of the data's
+reduced major axis to the line of perfect concordance (the accuracy of the
+data) and of the tightness of the data about its reduced major axis (the
+precision of the data). The Pearson correlation coefficient, r, the
+bias-correction factor, C_b, and the equation of the reduced major axis are
+reported to show these components. Note that the concordance correlation
+coefficient, rho_c, can be expressed as the product of r, the measure of
+precision, and C_b, the measure of accuracy.
+
+{p 4 4 2}
+{cmd:concord} also provides results for Bland and Altman's
+limits-of-agreement, "loa", procedure (1986). The loa, a data-scale assessment
+of the degree of agreement, is a complementary approach to the
+relationship-scale approach of Lin.
+
+{p 4 4 2}
+Finally, two other results are reported:
+
+{p 8 8 2}
+1. The correlation between difference and mean. In one interpretation
+this is a test statistic for a null hypothesis of equal variances given
+bivariate normality (Pitman 1939; also see Snedecor and Cochran 1989, 192-193).
+Alternatively, it is an exploratory diagnostic.
+A value near zero implies concordance.
+
+{p 8 8 2}
+2. An F test of equality of means and variances. Note that this too
+assumes bivariate normality (Bradley and Blackwood 1989).
+See also Hsu (1940) and Reynolds and Gregoire (1991).
+Nonsignificance implies concordance.
+
+{p 4 4 2}
+The user provides the pairs of measurements for a single property as
+observations in variables {it:vary} and {it:varx}. Frequency weights may be
+specified and used. Missing values (if any) are deleted in a casewise manner.
+
+{p 4 4 2}
+Various associated graphs may be obtained through options.
+See below for explanations of the options {cmd:ccc}, {cmd:loa}, and
+{cmd:qnormd}.
+
+
+{title:Options}
+
+{p 4 8 2}
+{cmd:by(}{it:byvar}{cmd:)} produces separate results for groups of
+observations defined by {it:byvar}.
+
+{p 4 8 2}
+{cmd:summary} requests summary statistics.
+
+{p 4 8 2}
+{cmd:level(}{it:#}{cmd:)} sets the confidence level % for the CI; default is
+{cmd:c(level)}.
+
+{p 4 8 2}
+{cmd:ccc} requests a graphical display of the data and the reduced major axis
+of the data. The reduced major axis or SD line goes through the intersection of
+the means and has slope given by the sign of Pearson's r and the ratio of the
+standard deviations. The SD line serves as a summary of the center of the data.
+
+{p 8 8 2}
+{cmd:ccc()} suboption {cmd:noref} suppresses the reference line of
+perfect concordance, y=x.
+
+{p 8 8 2}
+{cmd:ccc()} may also be specified with other options, which should
+be options of {helpb scatter}. For example, the scheme may be changed by a
+call such as {cmd:ccc(scheme(lean1)}.
+
+{p 4 8 2}
+{cmd:loa} requests a graphical display of the loa, the mean difference, and
+the data presented as paired differences plotted against pair-wise means.
+
+{p 8 8 2}
+{cmd:loa()} suboption {cmd:noref} suppresses the reference line of perfect
+average agreement, y=0.
+
+{p 8 8 2}
+{cmd:loa()} suboption {cmd:regline} adds a regression line to the loa plot
+fitting the paired differences to the pair-wise means.
+
+{p 8 8 2}
+{cmd:loa()} may also be specified with other options, which should normally
+be options of {helpb scatter}. For example,
+the reference line of perfect average agreement was generated as
+{cmd:loa(yline(0, lstyle(refline)) yscale(range(0)) ylabel(0, add))}.
+
+{p 4 8 2}
+{cmd:qnormd} requests a normal plot of differences.
+
+{p 8 8 2}
+{cmd:qnormd()} may also be specified with options, which should
+be options of {helpb scatter}. For example,
+{cmd:qnormd(title(Normal plot of differences))} adds a title to the graph.
+
+
+{title:Comments}
+
+{p 4 4 2}
+Lin (2000) reported typographical errors in his original 1989 paper
+that affected calculation of the standard error of rho_c. These corrections
+were included in {cmd:concord} in version 2.2.7 (January 2002) when the erratum
+was brought to the attention of the program authors by Dr. Benjamin Littenberg.
+We thank Dr. Littenberg.
+
+{p 4 4 2}Kevan Polkinghorne pointed out a problem with {cmd:loa()}.
+Mark Marshall pointed out a problem with {cmd:by()} under Stata 9.
+
+{p 4 4 2}
+Dunn (2004) contains a bibliography on related work.
+Cox (2004) discusses other graphical approaches to this and related
+problems. Cox (2006) discusses concordance correlation and
+other numerical and graphical methods for assessing agreement
+with various scientific examples.
+
+
+{title:Saved results}
+
+{p 4 4 2}
+The following items are returned in {cmd:r()}, if the {cmd:by()} option was
+not used:
+
+{p 8 18}{cmd:r(N)}{space 9}number of observations compared{p_end}
+{p 8 18}{cmd:r(rho_c)}{space 5}concordance correlation coefficient rho_c{p_end}
+{p 8 18}{cmd:r(se_rho_c)}{space 2}standard error of rho_c{p_end}
+{p 8 18}{cmd:r(asym_ll)}{space 3}lower CI limit (asymptotic){p_end}
+{p 8 18}{cmd:r(asym_ul)}{space 3}upper CI limit (asymptotic){p_end}
+{p 8 18}{cmd:r(z_tr_ll)}{space 3}lower CI limit (z-transform){p_end}
+{p 8 18}{cmd:r(z_tr_ul)}{space 3}upper CI limit (z-transform){p_end}
+{p 8 18}{cmd:r(C_b)}{space 7}bias-correction factor C_b{p_end}
+{p 8 18}{cmd:r(diff)}{space 6}mean difference{p_end}
+{p 8 18}{cmd:r(sd_diff)}{space 3}standard deviation of mean difference{p_end}
+{p 8 18}{cmd:r(LOA_ll)}{space 4}lower loa CI limit{p_end}
+{p 8 18}{cmd:r(LOA_ul)}{space 4}upper loa CI limit{p_end}
+{p 8 18}{cmd:r(rdm)}{space 7}correlation between difference and mean{p_end}
+{p 8 18}{cmd:r(Fdm)}{space 7}F from Bradley-Blackwood test{p_end}
+
+
+{title:Examples}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2 [fw=freq]}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2, summary ccc}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2, summary ccc(noref)}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2, level(90) by(grp)}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2, loa(regline noref)}
+
+{p 4 8 2}
+{cmd:. concord rater1 rater2, qnormd(title(Normal plot))}
+
+
+{title:Authors}
+
+{p 4 4 2}
+Thomas J. Steichen, Winston-Salem, NC, USA, steichen@triad.rr.com
+
+{p 4 4 2}
+Nicholas J. Cox, Durham University, UK, n.j.cox@durham.ac.uk
+
+
+{title:References}
+
+{p 4 8 2}
+Bland, J. M., and D. G. Altman. 1986. Statistical methods for assessing
+agreement between two methods of clinical measurement. {it:Lancet} I:
+307{c -}310.
+
+{p 4 8 2}
+Bradley, E. L., and L. G. Blackwood. 1989. Comparing paired data:
+a simultaneous test for means and variances. {it:American Statistician}
+43: 234{c -}235.
+
+{p 4 8 2}
+Cox, N. J. 2004. Graphing agreement and disagreement.
+{it:Stata Journal} 4: 329{c -}349.
+
+{p 4 8 2}
+------. 2006.
+Assessing agreement of measurements and predictions in geomorphology.
+{it:Geomorphology} 76: 332{c -}346.
+
+{p 4 8 2}
+Dunn, G. 2004.
+{it: Statistical Evaluation of Measurement Errors: Design and Analysis of Reliability Studies.}
+London: Arnold.
+
+{p 4 8 2}
+Hsu, C. T. 1940. On samples from a normal bivariate population.
+{it:Annals of Mathematical Statistics} 11: 410{c -}426.
+
+{p 4 8 2}
+Krippendorff, K. 1970. Bivariate agreement coefficients for reliability of data.
+In Borgatta, E.F. and G.W. Bohrnstedt (eds)
+{it:Sociological Methodology}. San Francisco: Jossey-Bass, 139{c -}150.
+[a.k.a. {it:Sociological Methodology} 2: 139{c -}150]
+
+{p 4 8 2}
+Lin, L. I-K. 1989. A concordance correlation coefficient to evaluate
+reproducibility. {it:Biometrics} 45: 255{c -}268.
+
+{p 4 8 2}
+------. 2000. A note on the concordance correlation coefficient.
+{it:Biometrics} 56: 324{c -}325.
+
+{p 4 8 2}
+Pitman, E. J. G. 1939. A note on normal correlation.
+{it:Biometrika} 31: 9{c -}12.
+
+{p 4 8 2}
+Reynolds, M., and T. G. Gregoire. 1991. Comment on Bradley and Blackwood.
+{it:American Statistician} 45: 163{c -}164.
+
+{p 4 8 2}
+Snedecor, G. W., and W. G. Cochran. 1989. {it:Statistical Methods.}
+Ames, IA: Iowa State University Press.
+
+
+{title:Also see}
+
+{p 4 13 2}
+STB: STB-43 sg84; STB-45 sg84.1; STB-54 sg84.2; STB-58 sg84.3
+
+{psee}
+SJ:{space 3}SJ2-2 st0015; SJ4-4 st0015_1; SJ5-3: st0015_2; SJ6-2: st0015_3
+{p_end}
diff --git a/Modules/ado/plus/c/confa.ado b/Modules/ado/plus/c/confa.ado
new file mode 100644
index 0000000..4359119
--- /dev/null
+++ b/Modules/ado/plus/c/confa.ado
@@ -0,0 +1,1090 @@
+*! v.2.0.2 Confirmatory factor analysis, by Stas Kolenikov, skolenik at gmail dot com, 08 Sep 2009
+program define confa, eclass properties( svyr svyb svyj ) sortpreserve
+ version 10.0
+
+ if replay() {
+ if ("`e(cmd)'" != "confa") error 301
+ Replay `0'
+ }
+
+ else {
+ Estimate `0'
+ }
+
+end
+
+program define Estimate, eclass properties( svyr svyb svyj )
+
+ syntax anything [if] [in] [aw pw iw/ ], [ ///
+ UNITvar(str) /// provides the list of factors where unit variance identification is used
+ FREE /// estimate all parameters as free -- the user provides identification through constraints
+ CONSTRaint(numlist) /// see the previous one
+ FROM(str) /// starting values, compliant with -ml init- syntax
+ LEVel(int $S_level) ROBust VCE(string) CLUster(passthru) /// standard errors and inference
+ LOGLEVel(int 1) /// logging level
+ CORRelated(string) /// correlated measurement errors
+ SUBtractone /// subtract one from the sample size in places
+ USENames ///
+ MISSing /// allow for special treatment of missing data
+ SVY * ]
+
+ * preliminary work
+ global CONFA_loglevel = `loglevel'
+
+ cap bothlist a \ b, global( CONFA_t )
+ if _rc==199 {
+ * listutil not installed
+ di as err "listutil not found, trying to install from SSC..."
+ ssc install listutil
+ }
+
+ if "`subtractone'"~="" local subtractone -1
+
+ *** MISSING
+ tempvar touse
+ marksample touse, zeroweight
+ global CONFA_touse `touse'
+ if $CONFA_loglevel > 2 tab $CONFA_touse
+
+ * weights?
+ if "`weight'" ~= "" {
+ global CONFA_wgt [`weight'=`exp']
+ global CONFA_wgti [iw=`exp']
+ }
+
+ * initial values?
+ if "`from'"~="" {
+ if "`from'" == "iv" | "`from'" == "IV" | "`from'" == "ivreg" | "`from'" == "2SLS" {
+ if "`unitvar'" ~= "" {
+ di as err "cannot specify from(`from') and unitvar at the same time"
+ CleanIt
+ exit 198
+ }
+ else global CONFA_init IV
+ }
+ else if "`from'" == "ones" global CONFA_init ones
+ else if "`from'" == "smart" global CONFA_init smart
+ else {
+ gettoken isitmat isitnot : from , parse(",")
+ cap confirm matrix `isitmat'
+ if _rc {
+ di "{err}Warning: matrix `isitmat' not found"
+ * do something sensible instead
+ global CONFA_init smart
+ }
+ else {
+ * do nothing --- let the hell break loose
+ global CONFA_init
+ }
+ }
+ }
+
+ * vce?
+ if "`vce'" ~= "" {
+ gettoken vce1 rest : vce, parse(" ,")
+ CheckVCE , `vce1'
+ local lvce = length("`vce'")
+ if `"`vce'"' != substr("sbentler", 1, max(2, `lvce')) ///
+ & `"`vce'"' != substr("satorrabentler", 1, max(3, `lvce')) {
+ local vceopt vce(`vce')
+ }
+ }
+
+ if $CONFA_loglevel > 2 di as text "Parsing..."
+ cap noi Parse `anything'
+ if _rc {
+ CleanIt
+ exit 198
+ }
+
+ * copy everything down -- -ivreg- cleans -sreturn-
+ local obsvar=s(obsvar)
+ global CONFA_obsvar `obsvar'
+
+ local nobsvar : word count `obsvar'
+ local nfactors = s(nfactors)
+ forvalues k=1/`nfactors' {
+ local indicators`k' = s(indicators`k')
+ local name`k' = s(name`k')
+ local factorlist `factorlist' `name`k''
+ }
+
+ * begin collecting the equations, starting values, bounds, and model structure
+ if $CONFA_loglevel > 2 di as text "Setting the structure up..."
+ Structure, unitvar(`unitvar') correlated(`correlated') `usenames'
+ local nicecorr $CONFA_t
+ * produces a bunch of globals
+
+ * did we need all this starting values business at all?
+ gettoken isitmat isitnot : from , parse(",")
+ cap confirm matrix `isitmat'
+ if ~_rc | strpos("`from'",",") {
+ * the user has provided the starting values
+ global CONFA_start `from'
+ }
+ else {
+ * not a matrix, no comma: use our ugly computations
+ global CONFA_start $CONFA_start, copy
+ }
+* if "$CONFA_bounds" ~= "" global CONFA_bounds bounds($CONFA_bounds)
+
+ if $CONFA_loglevel > 3 di `" ml model lf confa_lf $CONFA_toML $CONFA_wgt, constraint($CONFA_constr `constraint') `svy' `robust' `cluster' init($CONFA_start) bounds($CONFA_bounds) `options' maximize"'
+
+ tempvar misspat touse1
+ global CONFA_miss `misspat'
+ qui gen byte `touse1' = 1-$CONFA_touse
+ if "`missing'" != "" {
+ if $CONFA_loglevel > 1 di "{txt}Working on missing values..."
+ * cycle over the observed variables, create missing indicators
+ forvalues k=1/`nobsvar' {
+ local thisvar : word `k' of `obsvar'
+ tempvar miss`k'
+ qui gen byte `miss`k'' = mi( `thisvar' ) if $CONFA_touse
+ local misslist `misslist' `miss`k''
+ }
+
+ * sort by pattern: relevant observations first
+ * when $CONFA_touse==0 `misslist' will be missing
+ qui {
+ bysort `touse1' `misslist' : gen long $CONFA_miss = (_n==1)
+ replace $CONFA_miss = sum( $CONFA_miss )
+ replace $CONFA_miss = . if mi( $CONFA_touse )
+ }
+ cap assert $CONFA_miss == 1 if $CONFA_touse
+ local anymissing = _rc
+ if !`anymissing' {
+ di "{txt}Option missing specified, but no missing data found"
+ }
+ else {
+ qui tab $CONFA_miss
+ di _n "{txt}Note: {res}" r(r) "{txt} patterns of missing data found"
+ }
+ if $CONFA_loglevel > 3 li $CONFA_miss `misslist'
+ }
+* if "`anymissing'"=="0" | "`missing'" == "" {
+ else {
+ * -missing- option is omitted
+ if $CONFA_loglevel > 1 di "{err}NOT {txt}working on missing values"
+ markout $CONFA_touse `obsvar'
+ qui gen byte $CONFA_miss = 1 if $CONFA_touse
+ if $CONFA_loglevel > 2 {
+ sum `obsvar' if $CONFA_touse
+ tab $CONFA_miss, missing
+ }
+ }
+
+
+ cap noi ml model lf confa_lfm $CONFA_toML $CONFA_wgt if $CONFA_touse, ///
+ constraint($CONFA_constr `constraint') `svy' `robust' `cluster' `vceopt' ///
+ init($CONFA_start) bounds($CONFA_bounds) `options' `missing' ///
+ maximize
+
+ local mlrc = _rc
+ if `mlrc' {
+ CleanIt
+ error `mlrc'
+ }
+
+ * parametric matrices
+ tempname bb
+ mat `bb' = e(b)
+ global CONFA_loglevel -1
+ * to indicate to CONFA_StrucToSigma() that the matrices should be posted to Stata
+ qui mata : CONFA_StrucToSigma(st_matrix("`bb'"))
+ global CONFA_loglevel `loglevel'
+ * now, post all those matrices to ereturn
+
+ mat rownames CONFA_Sigma = `obsvar'
+ mat colnames CONFA_Sigma = `obsvar'
+ mat rownames CONFA_Lambda = `obsvar'
+ mat colnames CONFA_Lambda = `factorlist'
+ mat rownames CONFA_Phi = `factorlist'
+ mat colnames CONFA_Phi = `factorlist'
+ mat colnames CONFA_Theta = `obsvar'
+ mat rownames CONFA_Theta = `obsvar'
+ ereturn matrix Sigma = CONFA_Sigma, copy
+ ereturn matrix Lambda = CONFA_Lambda, copy
+ ereturn matrix Phi = CONFA_Phi, copy
+ ereturn matrix Theta = CONFA_Theta, copy
+
+ if "`missing'"!= "" ereturn local missing missing
+
+ eret local observed `obsvar'
+ eret local factors `factorlist'
+ if "`unitvar'" ~= "" {
+ * need to unwrap the contents of `unitvar'...
+ * or change its defintion from passthru to string
+ if "`unitvar'" == "_all" eret local unitvar `factorlist'
+ else eret local unitvar `unitvar'
+ }
+ forvalues k=1/`nfactors' {
+ eret local factor`k' `name`k'' : `indicators`k''
+ }
+ if "`correlated'"!="" eret local correlated `nicecorr'
+
+ if "`svy'`cluster'`exp'`robust'" == "" & "`vce'"!="robust" & substr("`vce'",1,2)!="cl" & "`missing'"=="" {
+
+ * if the data are not i.i.d., LRT is not applicable
+ * don't know what to do with missing data
+
+ tempname S Sindep trind
+ qui mat accum `S' = `obsvar' $CONFA_wgti if $CONFA_touse, dev nocons
+ mat `S' = `S' / ( e(N) `subtractone' )
+ mat `Sindep' = diag(vecdiag(`S'))
+
+ * degrees of freedom
+ local nconstr = `: word count $CONFA_constr' + `: word count `constraint''
+ local pstar = `nobsvar' * (`nobsvar' + 1) / 2
+ local df_m = rowsof(CONFA_Struc) - `nobsvar' - `nconstr'
+ ereturn scalar pstar = `pstar'
+
+ * test against independence
+ mat `trind' = trace( syminv(`Sindep') * `S' )
+ local trind = `trind'[1,1]
+ ereturn scalar ll_indep = -0.5 * `nobsvar' * e(N) * ln(2*_pi) - 0.5 * e(N) * ln(det(`Sindep')) - 0.5 * e(N) * `trind'
+ ereturn scalar lr_indep = 2*(e(ll)-e(ll_indep))
+ ereturn scalar df_indep = `pstar' - `nobsvar'
+ ereturn scalar p_indep = chi2tail(e(df_indep),e(lr_indep))
+
+ * goodness of fit test
+ ereturn scalar ll_0 = -0.5 * `nobsvar' * e(N) * ln(2*_pi) - 0.5 * e(N) * ln(det(`S')) - 0.5 * `nobsvar' * e(N)
+ ereturn scalar df_u = `pstar' - `df_m'
+ ereturn scalar lr_u = cond(e(df_u)==0,0,-2*(e(ll)-e(ll_0)))
+ ereturn scalar p_u = chi2tail(e(df_u),e(lr_u))
+
+ * make the g.o.f. test the default test
+ ereturn scalar df_m = `df_m'
+ ereturn local chi2type LR
+ ereturn scalar chi2 = e(lr_u)
+ ereturn scalar p = e(p_u)
+
+ * other crap
+ ereturn matrix S = `S'
+
+ if `"`vce'"'==substr("satorrabentler",1,max(3, length("`vce'"))) ///
+ | "`vce'" ==substr("sbentler",1,max(4, length("`vce'"))) {
+ * repost Satorra-Bentler covariance matrix
+ * not defined for complex survey data,
+
+ cap noi SatorraBentler, constraint(`constraint') `missing'
+
+ if _rc {
+ di as err "Satorra-Bentler standard errors are not supported; revert to vce(oim)"
+ }
+ else {
+
+ tempname SBVar SBV Delta Gamma VV U trUG2 Tdf
+ mat `SBVar' = r(SBVar)
+ mat `Delta' = r(Delta)
+ mat `Gamma' = r(Gamma)
+ mat `SBV' = r(SBV)
+ mat `VV' = e(V)
+ mat `SBVar' = ( `VV'[1..`nobsvar',1..`nobsvar'], `VV'[1..`nobsvar',`nobsvar'+1 ...] ///
+ \ `VV'[`nobsvar'+1...,1..`nobsvar'], `SBVar'[`nobsvar'+1...,`nobsvar'+1...] )
+ ereturn repost V = `SBVar'
+ ereturn matrix SBGamma = `Gamma', copy
+ ereturn matrix SBDelta = `Delta', copy
+ ereturn matrix SBV = `SBV', copy
+ ereturn local vce SatorraBentler
+ ereturn local vcetype "Satorra-Bentler"
+
+ * compute the corrected tests, too
+ * only takes care of the covariance structure
+ * Satorra-Bentler 1994
+ mat `U' = `SBV' - `SBV'*`Delta'*syminv(`Delta''*`SBV'*`Delta')*`Delta''*`SBV'
+ ereturn matrix SBU = `U'
+ mat `U' = trace( e(SBU)*e(SBGamma) )
+ ereturn scalar SBc = `U'[1,1]/e(df_u)
+ ereturn scalar Tsc = e(lr_u)/e(SBc) * (e(N) `subtractone' ) / e(N)
+ ereturn scalar p_Tsc = chi2tail( e(df_u), e(Tsc) )
+
+ mat `trUG2' = trace( e(SBU)*`Gamma'*e(SBU)*`Gamma')
+ ereturn scalar SBd = `U'[1,1]*`U'[1,1]/`trUG2'[1,1]
+ ereturn scalar Tadj = ( e(SBd)/`U'[1,1]) * e(lr_u) * (e(N) `subtractone' ) / e(N)
+ ereturn scalar p_Tadj = chi2tail( e(SBd), e(Tadj) )
+
+* saddlepoint approximation comes here!!!
+
+ * Yuan-Bentler 1997
+ ereturn scalar T2 = e(lr_u)/(1+e(lr_u)/e(N) )
+ ereturn scalar p_T2 = chi2tail( e(df_u), e(T2) )
+
+ }
+ }
+ }
+
+ * are we done yet?
+ ereturn matrix CONFA_Struc = CONFA_Struc
+ ereturn local predict confa_p
+ ereturn local estat_cmd confa_estat
+ ereturn local cmd confa
+
+ Replay
+
+ CleanIt
+
+end
+
+program define CleanIt
+ * just in case
+ return clear
+
+ * release the constraints
+ constr drop $CONFA_constr
+
+ * clear the globals
+ if $CONFA_loglevel < 3 {
+ global CONFA_constr
+ global CONFA_init
+ global CONFA_loglevel
+ global CONFA_toML
+ global CONFA_start
+ global CONFA_bounds
+ global CONFA_args
+ global CONFA_constr
+ global CONFA_obsvar
+ global CONFA_t
+ global CONFA_wgt
+ global CONFA_wgti
+ }
+end
+
+program define Parse, sclass
+
+ * number of factors?
+ local input `0'
+
+ mata: st_local("nfactors",strofreal(CONFA_NF(`"`input'"')))
+
+ if `nfactors' == 0 {
+ * something terrible happened
+ di as err "incorrect factor specification"
+ exit 198
+ }
+
+ sreturn local nfactors = `nfactors'
+
+ tokenize `input', parse("()")
+
+ local k = 0
+ while "`1'"~="" {
+ * right now, `1' should contain an opening bracket
+ if "`1'"~="(" {
+ * the first character is not a "("
+ di as err "incorrect factor specification"
+ exit 198
+ }
+ else {
+ * the first character IS a "("
+ mac shift
+ * right now, `1' should contain a factor-type statement
+ local ++k
+ local factor`k' `1'
+ mac shift
+ * right now, `1' should contain a closing bracket
+ if "`1'"~=")" {
+ * the first character is not a ")"
+ di as err "incorrect factor specification"
+ exit 198
+ }
+ else mac shift
+ * it may contain a space, I guess
+ * then -mac shift- it again
+ if trim("`1'")=="" mac shift
+ }
+ }
+ forvalues k=1/`nfactors' {
+ * now, parse each factor statement
+ tokenize `factor`k'', parse(":")
+ sreturn local name`k' `1'
+ * `2' is the colon
+ unab indicators : `3'
+ sreturn local indicators`k' `indicators'
+ local obsvar `obsvar' `indicators'
+ }
+
+ cap uniqlist `obsvar'
+ if _rc == 199 {
+ * uniqlist not found
+ di as err "uniqlist not found, trying to install from SSC..."
+ ssc install listutil
+ uniqlist `obsvar'
+ }
+ local obsvar = r(list)
+
+* mata: st_local("obsvar",CONFA_UL(`"`obsvar'"'))
+
+ sreturn local obsvar `obsvar'
+ sreturn local nobsvar = `: word count `obsvar''
+
+end
+
+program define Structure
+
+ syntax , [unitvar(str) correlated(str) usenames]
+
+ * implement usenames:
+ * the parameters go along with the factor and variable names
+ * rather than matrix indices
+
+ * utilize all the sreturn results
+ if $CONFA_loglevel > 3 sreturn list
+
+ * copy everything down -- -ivreg- cleans -sreturn-
+ local obsvar=s(obsvar)
+ local nobsvar : word count `obsvar'
+ local nfactors = s(nfactors)
+
+ forvalues k=1/`nfactors' {
+ local indicators`k' = s(indicators`k')
+ local name`k' = s(name`k')
+ local factorlist `factorlist' `name`k''
+ }
+
+ if "`unitvar'" == "_all" {
+ local unitvar `factorlist'
+ }
+
+ * set up the labeling system
+ if "`usenames'" != "" {
+ * give the parameters varname labels
+ forvalues k=1/`nobsvar' {
+ local o`k' : word `k' of `obsvar'
+ }
+ forvalues k=1/`nfactors' {
+ local f`k' `name`k''
+ }
+ }
+ else {
+ * give the parameters numberic lables
+ forvalues k=1/`nobsvar' {
+ local o`k' `k'
+ }
+ forvalues k=1/`nfactors' {
+ local f`k' `k'
+ }
+ }
+
+ * returns:
+ * - ML equations
+ * - ML bounds
+ * - the structure matrix
+ * - ML statement for the likelihood evaluator
+
+ * initialize everything
+ local eqno = 0
+ global CONFA_toML
+ global CONFA_start
+ global CONFA_args
+ global CONFA_constr
+ global CONFA_bounds
+ mata : CONFA_Struc = J(0,4,.)
+
+ * process the means first
+ tokenize `obsvar'
+ forvalues j=1/`nobsvar' {
+ * 1. equations to ML
+ local ++eqno
+ global CONFA_toML $CONFA_toML (mean_`o`j'':)
+ * 2. starting values
+ sum ``j'', mean
+ global CONFA_start $CONFA_start `r(mean)'
+ * 3. confa_lf arguments
+ global CONFA_args $CONFA_args mean_`o`j''
+ * 4. CONFA structure
+ mata : CONFA_Struc = CONFA_Struc \ (1, `eqno', `j', 0)
+ }
+
+ * next, process lambda's
+ forvalues k=1/`nfactors' {
+ * determine if unitvar is needed here
+ bothlist `name`k'' \ `unitvar', global(CONFA_t)
+ if "$CONFA_t" ~= "" {
+ * identification by unit variance, no scaling variables
+ local scalevar
+ }
+ else {
+ * identification by the scaling variable: the 1st one on the list
+ local scalevar : word 1 of `indicators`k''
+ }
+ forvalues j=1/`nobsvar' {
+ * determine whether `k'-th factor loads on `j'-th variable
+ if strpos( "`indicators`k''", "``j''") {
+ * 1. equations to ML
+ local ++eqno
+ global CONFA_toML $CONFA_toML (lambda_`o`j''_`f`k'':)
+ * 2. starting values
+ local r2_`j' = 0.5
+ if "``j''" == "`scalevar'" {
+ * the current one is the scaling variable
+ * set up the constraints, initialize to 1
+ global CONFA_start $CONFA_start 1
+ constraint free
+ local nconstr = r(free)
+ constraint `nconstr' [lambda_`o`j''_`f`k'']_cons = 1
+ global CONFA_constr $CONFA_constr `nconstr'
+ }
+ else if "$CONFA_init" == "IV" {
+ * initialize by a simple version of instrumental variables
+ * use the remaining indicators of this factor as instruments
+ dellist `indicators`k'', delete(`scalevar' ``j'')
+ local ivlist = r(list)
+ if "`ivlist'" == "." {
+ di as err "Warning: no instruments available for ``j''"
+ local ivl = 1
+ }
+ else {
+ qui ivreg ``j'' (`scalevar' = `ivlist')
+ local ivl = _b[`scalevar']
+ }
+ global CONFA_start $CONFA_start `ivl'
+ if !mi(e(r2)) local r2_`j' = e(r2)
+ }
+ else if "$CONFA_init" == "ones" {
+ global CONFA_start $CONFA_start 1
+ }
+ else {
+ * no init options
+ global CONFA_start $CONFA_start 0
+ }
+ global CONFA_bounds $CONFA_bounds /lambda_`o`j''_`f`k'' -100 100
+ * 3. confa_lf arguments
+ global CONFA_args $CONFA_args lambda_`o`j''_`f`k''
+ * 4. CONFA structure
+ mata : CONFA_Struc = CONFA_Struc \ (2, `eqno', `j', `k')
+ }
+ }
+ }
+
+ * next, process Phi matrix
+ forvalues k=1/`nfactors' {
+ local scalevar1 : word 1 of `indicators`k''
+
+ foreach kk of numlist `k'/1 {
+ * 1. equations to ML
+ local ++eqno
+ global CONFA_toML $CONFA_toML (phi_`f`kk''_`f`k'':)
+ * 2. starting values
+ if `k' == `kk' {
+ * diagonal entry
+ bothlist `name`k'' \ `unitvar', global(CONFA_t)
+ if "$CONFA_t" ~= "" {
+ * identification by unit variance
+ constraint free
+ local nconstr = r(free)
+ constraint `nconstr' [phi_`f`k''_`f`k'']_cons = 1
+ global CONFA_constr $CONFA_constr `nconstr'
+ local v`k' = 1
+ }
+ else {
+ * identification by the scaling variable
+ if "$CONFA_init" == "smart" | "$CONFA_init" == "IV" {
+ qui sum `scalevar1'
+ local v`k' = r(Var)*0.5
+ }
+ else if "$CONFA_init" == "ones" local v`k' = 1
+ else local v`k' = 0
+ }
+ global CONFA_start $CONFA_start `v`k''
+ global CONFA_bounds $CONFA_bounds /phi_`f`k''_`f`kk'' 0 1000
+ }
+ else {
+ * off-diagonal entry
+ if "$CONFA_init" == "smart" | "$CONFA_init" == "IV" {
+ local scalevar2 : word 1 of `indicators`kk''
+ qui corr `scalevar1' `scalevar2'
+ local v = 0.5*r(rho)*sqrt(`v`k''*`v`kk'')
+ }
+ else if "$CONFA_init" == "ones" local v = 0.5
+ else local v = 0
+ local vv = 1.5*abs(`v') + 0.01
+ global CONFA_start $CONFA_start `v'
+ global CONFA_bounds $CONFA_bounds /phi_`f`kk''_`f`k'' -`vv' `vv'
+ }
+ * 3. confa_lf arguments
+ global CONFA_args $CONFA_args phi_`f`kk''_`f`k''
+ * 4. CONFA structure
+ mata : CONFA_Struc = CONFA_Struc \ (3, `eqno', `kk', `k')
+ }
+
+ }
+
+ * residual variances
+ forvalues j=1/`nobsvar' {
+ * 1. equations to ML
+ local ++eqno
+ global CONFA_toML $CONFA_toML (theta_`o`j'':)
+ * 2. starting values
+ if "$CONFA_init" == "ones" {
+ local v_`j' = 1
+ }
+ else if "$CONFA_init" == "IV" | "$CONFA_init" == "smart" {
+ qui sum ``j''
+ local v_`j' = r(Var)*(1-`r2_`j'')
+ }
+ else local v_`j' = 0.01
+ global CONFA_start $CONFA_start `v_`j''
+ global CONFA_bounds $CONFA_bounds /theta_`o`j'' 0 1000
+ * 3. confa_lf arguments
+ global CONFA_args $CONFA_args theta_`o`j''
+ * 4. CONFA structure
+ mata : CONFA_Struc = CONFA_Struc \ (4, `eqno', `j', 0)
+ }
+
+ * the error correlations
+ while "`correlated'" != "" {
+ gettoken corrpair correlated : correlated , match(m)
+ gettoken corr1 corrpair : corrpair, parse(":")
+ unab corr1 : `corr1'
+ gettoken sc corr2 : corrpair, parse(":")
+ unab corr2 : `corr2'
+
+ * make sure both are present in the list of observed variables
+
+ poslist `obsvar' \ `corr1', global(CONFA_t)
+ local k1 = $CONFA_t
+ if `k1' == 0 {
+ di as err "`corr1' is not among the observed variables"
+ CleanIt
+ exit 198
+ }
+ poslist `obsvar' \ `corr2', global(CONFA_t)
+ local k2 = $CONFA_t
+ if `k2' == 0 {
+ di as err "`corr2' is not among the observed variables"
+ CleanIt
+ exit 198
+ }
+
+ * will be empty @ the first call
+ local nicecorr `nicecorr' (`corr1':`corr2')
+
+ * 1. equations to ML
+ local ++eqno
+ global CONFA_toML $CONFA_toML (theta_`o`k1''_`o`k2'':)
+ * 2. starting values
+ global CONFA_start $CONFA_start 0
+ local vv = sqrt(`v_`k1''*`v_`k2'')
+ global CONFA_bounds $CONFA_bounds /theta_`o`k1''_`o`k2'' -`vv' `vv'
+ * 3. confa_lf arguments
+ global CONFA_args $CONFA_args theta_`o`k1''_`o`k2''
+ * 4. CONFA structure
+ mata : CONFA_Struc = CONFA_Struc \ (5, `eqno', `k1', `k2')
+ }
+ if "`nicecorr'"!="" global CONFA_t `nicecorr'
+
+ if $CONFA_loglevel > 3 {
+ di as text "ML input (" as res `: word count $CONFA_toML' as text "): " as res "$CONFA_toML"
+ di as text "Starting values (" as res `: word count $CONFA_start' as text "): " as res "$CONFA_start"
+ di as text "Likelihood evaluator (" as res `: word count $CONFA_args' as text"): " as res "$CONFA_args"
+ di as text "Constraints (" as res `nfactors' as text "): " as res "$CONFA_constr"
+ di as text "Correlated errors: " as res "`nicecorr'"
+ constraint dir $CONFA_constr
+ mata : CONFA_Struc
+ }
+ mata : st_matrix("CONFA_Struc",CONFA_Struc)
+
+
+end
+
+program define Replay
+
+ syntax, [posvar llu(str) level(passthru)]
+
+ * get the implied matrix
+ tempname bb Sigma
+ mat `bb' = e(b)
+ * mata : st_matrix("Sigma",CONFA_StrucToSigma(st_matrix("`bb'")))
+ mat `Sigma' = e(Sigma)
+ mat CONFA_Struc = e(CONFA_Struc)
+
+ * determine what kind of labeling has been used
+ * RATHER FRAGILE: checking for mean_1 rather than trying to find
+ * whether option usenames was specified
+ cap local whatis = [mean_1]_cons
+ if _rc {
+ * mean_1 not found => labeling by names
+ forvalues k=1/`: word count `e(observed)' ' {
+ local o`k' : word `k' of `e(observed)'
+ }
+ forvalues k=1/`: word count `e(factors)' ' {
+ local f`k' : word `k' of `e(factors)'
+ }
+ }
+ else {
+ * mean_1 was found => labeling by numbers
+ forvalues k=1/`: word count `e(observed)' ' {
+ local o`k' `k'
+ }
+ forvalues k=1/`: word count `e(factors)' ' {
+ local f`k' `k'
+ }
+ }
+
+ * header
+ di _n as text "`e(crittype)' = " as res e(ll) _col(59) as text "Number of obs = " as res e(N)
+ di as text "{hline 13}{c TT}{hline 64}"
+ if "`e(vcetype)'" ~= "" {
+ di as text " {c |} {center 15:`e(vcetype)'}"
+ }
+ di as text " {c |} Coef. Std. Err. z P>|z| [$S_level% Conf. Interval]"
+ di as text "{hline 13}{c +}{hline 64}"
+
+ tokenize `e(observed)'
+ local nobsvar : word count `e(observed)'
+
+ * let's go equation by equation
+ local eqno = 0
+
+ * Means
+ _diparm __lab__, label("Means") eqlabel
+ forvalues j = 1/`nobsvar' {
+ local ++eqno
+ _diparm mean_`o`j'' , label("``j''") prob `level'
+ }
+
+ * Loadings
+ _diparm __lab__, label("Loadings") eqlabel
+ local ++eqno // to point to the next line
+ forvalues k=1/`: word count `e(factors)' ' {
+ _diparm __lab__ , label("`: word `k' of `e(factors)' '")
+ while CONFA_Struc[`eqno',1]<=2 & CONFA_Struc[`eqno',4]==`k' {
+ local j = CONFA_Struc[`eqno',3]
+ _diparm lambda_`o`j''_`f`k'', label("``j''") prob `level'
+ local ++eqno
+ }
+ }
+
+ * Factor covariance
+ _diparm __lab__, label("Factor cov.") eqlabel
+ forvalues k=1/`: word count `e(factors)'' {
+ foreach kk of numlist `k'/1 {
+ _diparm phi_`f`kk''_`f`k'', label("`: word `kk' of `e(factors)''-`: word `k' of `e(factors)''") prob `level'
+ local ++eqno
+ }
+ }
+
+ * Error variances
+ _diparm __lab__, label("Var[error]") eqlabel
+ forvalues j= 1/`nobsvar' {
+ _diparm theta_`o`j'' , label("``j''") prob `level'
+ local ++eqno
+ }
+
+ * Error correlations
+ if `eqno' <= rowsof(CONFA_Struc) & CONFA_Struc[`eqno',1] == 5 {
+ _diparm __lab__, label("Cov[error]") eqlabel
+ while (`eqno' <= rowsof(CONFA_Struc) & CONFA_Struc[`eqno',1] == 5) {
+ local k1 = CONFA_Struc[`eqno',3]
+ local k2 = CONFA_Struc[`eqno',4]
+ _diparm theta_`o`k1''_`o`k2'', label("``k1''-``k2''") prob `level'
+ * range check: what am I supposed to check here? Hm...
+ local ++eqno
+ }
+ }
+
+ if "`e(vcetype)'"~="Robust" & "`e(missing)'"=="" {
+ di as text "{hline 13}{c +}{hline 64}"
+ di as text "R2{col 14}{c |}"
+ forvalues j = 1/`nobsvar' {
+ qui sum ``j'' if e(sample)
+ local r2 = (`Sigma'[`j',`j']-_b[theta_`o`j'':_cons])/r(Var)
+ di as text %12s "``j''" "{col 14}{c |}{col 20}" as res %6.4f `r2'
+ }
+ }
+
+
+ di as text "{hline 13}{c BT}{hline 64}"
+
+ if e(df_u)>0 {
+ di as text _n "Goodness of fit test: LR = " as res %6.3f e(lr_u) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > LR] = " as res %6.4f e(p_u)
+ }
+ else {
+ di as text "No degrees of freedom to perform the goodness of fit test"
+ }
+ di as text "Test vs independence: LR = " as res %6.3f e(lr_indep) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_indep) as text ") > LR] = " as res %6.4f e(p_indep)
+
+ if "`e(vce)'" == "SatorraBentler" & e(df_u)>0 {
+ * need to report all those corrected statistics
+
+ di as text _n "Satorra-Bentler Tsc" _col(26) "= " as res %6.3f e(Tsc) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > Tsc ] = " as res %6.4f e(p_Tsc)
+
+ di as text "Satorra-Bentler Tadj" _col(26) "= " as res %6.3f e(Tadj) ///
+ as text _col(40) "; Prob[chi2(" as res %4.1f e(SBd) as text ") > Tadj] = " as res %6.4f e(p_Tadj)
+
+ di as text "Yuan-Bentler T2" _col(26) "= " as res %6.3f e(T2) ///
+ as text _col(40) "; Prob[chi2(" as res %2.0f e(df_u) as text ") > T2 ] = " as res %6.4f e(p_T2)
+ }
+
+ if "`e(vce)'" == "BollenStine" {
+ * need to report Bollen-Stine measures
+ di as text _n "Bollen-Stine simulated Prob[ LR > " as res %6.4f e(lr_u) as text " ] = " as res %6.4f e(p_u_BS) ///
+ as text _n "Based on " as res e(B_BS) as text " replications. " ///
+ as text "The bootstrap 90% interval: (" as res %6.3f e(T_BS_05) as text "," ///
+ as res %6.3f e(T_BS_95) as text ")"
+
+
+ }
+
+ mat drop CONFA_Struc
+
+end
+
+**************************** Satorra-Bentler covariance matrix code
+
+program SatorraBentler, rclass
+ syntax [, noisily constraint(numlist) missing]
+
+ if "`missing'"!="" {
+ di "{err}cannot specify Satorra-Bentler standard errors with missing data"
+ exit 198
+ }
+
+ * assume the maximization completed, the results are in memory as -ereturn data-
+ * we shall just return the resulting matrix
+
+ * assume sample is restricted to e(sample)
+ * preserve
+ * keep if e(sample)
+
+ * get the variable names
+ tempname VV bb
+ mat `bb' = e(b)
+ mat `VV' = e(V)
+ local p : word count $CONFA_obsvar
+ qui count if $CONFA_touse
+ local NN = r(N)
+
+ * compute the implied covariance matrix
+ tempname Lambda Theta Phi Sigma
+ mata : st_matrix("`Sigma'",CONFA_StrucToSigma(st_matrix("`bb'")))
+
+ * compute the empirical cov matrix
+ tempname SampleCov
+ qui mat accum `SampleCov' = $CONFA_obsvar $CONFA_wgti if $CONFA_touse , nocons dev
+ * divide by sum of weights instead???
+ mat `SampleCov' = `SampleCov' / (`NN'-1)
+
+ * compute the matrix Gamma (fourth moments)
+ if $CONFA_loglevel > 4 {
+ di as text "Computing the Gamma matrix of fourth moments..."
+ }
+ tempname Gamma
+ SBGamma $CONFA_obsvar if $CONFA_touse
+ mat `Gamma' = r(Gamma)
+ return add
+
+ * compute the V matrix, the normal theory weight
+ if $CONFA_loglevel > 4 {
+ di as text "Computing the V matrix..."
+ }
+ SBV `SampleCov' `noisily'
+ if !mi(r(needmatsize)) {
+ di as err "matsize too small; need at least " r(needmatsize)
+ exit 908
+ }
+ tempname V
+ mat `V' = r(SBV)
+ return add
+
+ * compute the Delta matrix
+ if $CONFA_loglevel > 4 {
+ di as text "Computing the Delta matrix..."
+ }
+
+ tempname Delta DeltaId
+ noi mata : SBStrucToDelta("`Delta'")
+
+ *** put the pieces together now
+
+ * enact the constraints!
+ SBconstr `bb', constraint(`constraint')
+
+ * zero out the rows of Delta that correspond to fixed parameters
+ mat `DeltaId' = `Delta' * diag( r(Fixed) )
+
+ local dcnames : colfullnames `bb'
+ local drnames : rownames `Gamma'
+ mat colnames `DeltaId' = `dcnames'
+ mat rownames `DeltaId' = `drnames'
+ return matrix Delta = `DeltaId', copy
+
+ tempname VVV
+ mat `VVV' = ( `DeltaId'' * `V' * `DeltaId' )
+ mat `VVV' = syminv(`VVV')
+ mat `VVV' = `VVV' * ( `DeltaId'' * `V' * `Gamma' * `V' * `DeltaId' ) * `VVV'/`NN'
+
+ * add the covariance matrix for the means, which is just Sigma/_N
+ * weights!
+ * third moments!
+ return matrix SBVar = `VVV'
+
+end
+* of satorrabentler
+
+* Compute Gamma: the fourth moments matrix -- check!
+program define SBGamma, rclass
+ syntax varlist [if] [in]
+ unab varlist : `varlist'
+ tokenize `varlist'
+
+ marksample touse
+
+ local p: word count `varlist'
+
+ forvalues k=1/`p' {
+ * make up the deviations; weights are used in a weird way
+ *** MISSING: change r(mean) to _b[whatever] ?
+ qui sum ``k'' $CONFA_wgti if `touse', meanonly
+ tempvar d`k'
+ qui g double `d`k'' = ``k'' - r(mean) if `touse'
+ local dlist `dlist' `d`k''
+ }
+
+ local pstar = `p'*(`p'+1)/2
+ forvalues k=1/`pstar' {
+ tempvar b`k'
+ qui g double `b`k'' = .
+ local blist `blist' `b`k''
+ }
+
+
+ * convert into vech (z_i-bar z)(z_i-bar z)'
+ mata : SBvechZZtoB("`dlist'","`blist'")
+
+ * blist now should contain the moments around the sample means
+ * we need to get their covariance matrix
+
+ tempname Gamma
+ qui mat accum `Gamma' = `blist' $CONFA_wgti if `touse', dev nocons
+ mat `Gamma' = `Gamma'/(r(N)-1)
+ mata : Gamma = st_matrix( "`Gamma'" )
+
+ * make nice row and column names
+ forvalues i=1/`p' {
+ forvalues j=`i'/`p' {
+ local namelist `namelist' ``i''_X_``j''
+ }
+ }
+ mat colnames `Gamma' = `namelist'
+ mat rownames `Gamma' = `namelist'
+
+ return matrix Gamma = `Gamma'
+
+end
+* of computing Gamma
+
+* compute V = 1/2 D' (Sigma \otimes Sigma) D
+* normal theory weight matrix, see Satorra (1992), eq (24) -- check!
+program define SBV, rclass
+ args A noisily
+ tempname D Ainv V
+ local p = rowsof(`A')
+ if $CONFA_loglevel > 3 di as text "Computing the duplication matrix..."
+ mata : Dupl(`p',"`D'")
+ mat `Ainv' = syminv(`A')
+ cap mat `V' = .5*`D''* (`Ainv' # `Ainv') * `D'
+ if _rc == 908 {
+ * need a larger matrix
+ return scalar needmatsize = rowsof(`A')*rowsof(`A')
+ }
+ else {
+ return matrix SBV = `V'
+ }
+end
+* of computing V
+
+program define SBconstr, rclass
+ * need to figure out whether a constraint has the form [parameter]_cons = value,
+ * and to nullify the corresponding column
+ syntax anything, [constraint(numlist)]
+ local bb `anything'
+ * that's the name of the parameter vector, a copy of e(b)
+ tempname Iq
+ mat `Iq' = J(1,colsof(`bb'),1)
+ tokenize $CONFA_constr `constraint'
+ while "`1'" ~= "" {
+ constraint get `1'
+ local constr `r(contents)'
+ gettoken param value : constr, parse("=")
+ * is the RHS indeed a number?
+ local value = substr("`value'",2,.)
+ confirm number `value'
+ * parse the square brackets and turn them into colon
+ * replace the opening brackets with nothing, and closing brackets, with colon
+ * that way, we will get "parameter:_cons", which is the format of e(b) labels
+ local param = subinstr("`param'","["," ",1)
+ local param = subinstr("`param'","]",":",1)
+ local param = trim("`param'")
+ local coln = colnumb(`bb',"`param'" )
+ mat `Iq'[1,`coln']=0
+
+ mac shift
+ }
+ return matrix Fixed = `Iq'
+end
+
+program define CheckVCE
+ syntax [anything] , [ROBust CLuster oim opg SBentler SATorrabentler BOOTstrap JACKknife]
+ if "`bootstrap'" ~= "" {
+ di "{err}vce(bootstrap) not allowed, but you can run {inp}bootstrap ... : confa ... {err}instead."
+ CleanIt
+ exit 198
+ }
+ if "`jackknife'" ~= "" {
+ di "{err}vce(jackknife) not allowed, but you can run {inp}jackknife ... : confa ... {err}instead."
+ CleanIt
+ exit 198
+ }
+end
+
+exit
+
+if "$SOCST" == "c:\-socialstat" {
+ // at home, run the Mata file
+ do C:\-Mizzou\CONFA\confa.mata
+}
+else {
+ // for public release, add Mata code
+ mata : mata mlib index
+}
+
+Globals used:
+CONFA_init -- initialization type
+CONFA_loglevel -- detail level
+CONFA_toML -- model statement for -ml model-
+CONFA_start -- default starting values
+CONFA_bounds -- ml search bounds
+CONFA_args -- the list of parameters, to appear in -confa_lf-
+CONFA_constr -- the list of constraints
+CONFA_obsvar -- the list of observed variables
+CONFA_wgt -- weight specification
+CONFA_wgti -- iweight
+CONFA_t -- temporary global for -listutil-
+
+Structure matrix:
+CONFA_Struc -- the model structure: (parameter type, equation number, index1, index2)
+
+History:
+v.1.0 -- Jan 09, 2008
+ -- basic formulation without -cluster-, -robust-, -weights-, -svy-
+v.1.1 -- Mar 21, 2008
+ -- Satorra-Bentler?
+v.1.2 -- Sep 16, 2008
+ -- Ken Higbee comments
+v.1.5 -- usenames
+ -- Mata moved to lconfa.mlib
+ -- survey-compatible
+v.1.6 -- listwise deletion for missing data
+ -- what kind of idiot should Stas be to not pay attention to this???
+ -- informative message about matsize in Satorra-Bentler calculations
+v.2.0 -- FIML missing data
+ -- prepared for revision in SJ
+v.2.0.1 -- fixed -if- in Satorra-Bentler calculations
+v.2.0.2 -- fixed reporting of correlations with -unitvar-: confa.ado, confa_estat.ado
+v.2.1 -- someday?
+ -- Bartlett correction: (N - 1 - (2p+4m+5)/6)
+ -- F-statistic in place of chi-square, both normal theory and S-B
diff --git a/Modules/ado/plus/c/confa.mata b/Modules/ado/plus/c/confa.mata
new file mode 100644
index 0000000..ec56fd7
--- /dev/null
+++ b/Modules/ado/plus/c/confa.mata
@@ -0,0 +1,503 @@
+*! Mata definitions for confa package; 3 March 2009; v.2.0
+
+set matalnum on
+
+mata:
+
+mata set matastrict on
+mata clear
+
+//////////////////////////////////////////////
+// needed by confa.ado
+
+real CONFA_NF( string input ) {
+ real scalar nopenpar, nclosepar, ncolon;
+ // opening and closing parentheses
+
+ nopenpar = length(tokens(input, ")" ))
+ nclosepar = length(tokens(input, "(" ))
+ // n*par will be 2*nf
+ ncolon = length(tokens(input, ":" ))
+ // ncolon will be 2*nf + 1
+
+ if ( (nopenpar == nclosepar) & (nopenpar == ncolon-1 ) ) {
+ if (mod(nopenpar,2) == 0) {
+ return( nopenpar/2 )
+ }
+ }
+
+ // if everything was OK, should've exited by now
+ // if something's wrong, return zero
+ return(0)
+}
+
+matrix CONFA_StrucToSigma(real vector parms) {
+ real scalar CONFA_loglevel, nobsvar, nfactors, eqno;
+ real matrix Lambda, Phi, Theta, Sigma, CONFA_Struc;
+
+ // loglevel
+ CONFA_loglevel = strtoreal( st_global("CONFA_loglevel"))
+
+ CONFA_Struc = st_matrix("CONFA_Struc")
+ if (CONFA_loglevel>4) CONFA_Struc
+
+ if (CONFA_loglevel>4) {
+ printf("{txt}Current parameter values:\n")
+ parms
+ }
+
+ // the length should coinicde with the # pars from CONFA_Struc
+ if ( cols(parms) ~= rows(CONFA_Struc) ) {
+ // something's wrong, let's just drop out with an empty matrix
+ if (CONFA_loglevel>4) {
+ printf("{txt}Expected parameters: {res}%3.0f{txt}; received parameters: {res}%3.0f\n",
+ rows(CONFA_Struc),cols(parms))
+ }
+ return(J(0,0,0))
+ }
+
+ // # observed variables: max entry in the number of means
+ nobsvar = colmax( select(CONFA_Struc[,3], !(CONFA_Struc[,1]-J(rows(CONFA_Struc),1,1)) ) )
+ if (CONFA_loglevel>4) printf("{txt}No. of observed variables: {res}%3.0f\n",nobsvar)
+
+ // # observed factors: max entry in the phi indices
+ nfactors = colmax( select(CONFA_Struc[,3], !(CONFA_Struc[,1]-J(rows(CONFA_Struc),1,3)) ) )
+ if (CONFA_loglevel>4) printf("{txt}No. of latent factors: {res}%3.0f\n",nfactors)
+
+ // set up the matrices
+ Lambda = J(nobsvar,nfactors,0)
+ Phi = J(nfactors,nfactors,0)
+ Theta = J(nobsvar,nobsvar,0)
+
+ // fill the stuff in
+ for(eqno=nobsvar+1;eqno<=rows(CONFA_Struc);eqno++) {
+ if (CONFA_Struc[eqno,1] == 2) {
+ // a lambda-type entry
+ Lambda[ CONFA_Struc[eqno,3], CONFA_Struc[eqno,4] ] = parms[eqno]
+ }
+ if (CONFA_Struc[eqno,1] == 3) {
+ // a phi-type entry
+ Phi[ CONFA_Struc[eqno,3], CONFA_Struc[eqno,4] ] = parms[eqno]
+ Phi[ CONFA_Struc[eqno,4], CONFA_Struc[eqno,3] ] = parms[eqno]
+ }
+ if (CONFA_Struc[eqno,1] == 4) {
+ // a theta-type entry
+ Theta[ CONFA_Struc[eqno,3], CONFA_Struc[eqno,3] ] = parms[eqno]
+ }
+ if (CONFA_Struc[eqno,1] == 5) {
+ // a theta-type correlated errors entry
+ Theta[ CONFA_Struc[eqno,3], CONFA_Struc[eqno, 4] ] = parms[eqno]
+ Theta[ CONFA_Struc[eqno,4], CONFA_Struc[eqno, 3] ] = parms[eqno]
+ }
+ }
+ if (CONFA_loglevel > 4) {
+ printf("{txt}Loadings:\n")
+ Lambda
+ printf("{txt}Factor covariances:\n")
+ Phi
+ printf("{txt}Residual variances:\n")
+ Theta
+ }
+ Sigma = Lambda*Phi*Lambda' + Theta
+ if (CONFA_loglevel > 4) {
+ printf("{txt}Implied moments:\n")
+ Sigma
+ }
+
+ if (CONFA_loglevel == -1) {
+ // post matrices to Stata
+ st_matrix("CONFA_Lambda",Lambda)
+ st_matrix("CONFA_Phi",Phi)
+ st_matrix("CONFA_Theta",Theta)
+ st_matrix("CONFA_Sigma",Sigma)
+ }
+
+ // done with model structure, compute and return implied matrix
+ return( Sigma )
+}
+
+// vech covariance matrix, for Satorra-Bentler
+void SBvechZZtoB(string dlist, string blist) {
+ real matrix data, moments, B;
+ real scalar i;
+
+ // view the deviation variables
+ st_view(data=.,.,tokens(dlist))
+ // view the moment variables
+ // blist=st_local("blist")
+ st_view(moments=.,.,tokens(blist))
+ // vectorize!
+ for(i=1; i<=rows(data); i++) {
+ B = data[i,.]'*data[i,.]
+ moments[i,.] = vech(B)'
+ }
+}
+
+// duplication matrix, for Satorra-Bentler
+void Dupl(scalar p, string Dname) {
+ real scalar pstar, k;
+ real matrix Ipstar, D;
+
+ pstar = p*(p+1)/2
+ Ipstar = I(pstar)
+ D = J(p*p,0,.)
+ for(k=1;k<=pstar;k++) {
+ D = (D, vec(invvech(Ipstar[.,k])))
+ }
+ st_matrix(Dname,D)
+}
+
+// Satorra-Bentler Delta matrix
+// Delta = \frac \partial{\partial \theta} vech \Sigma(\theta)
+void SBStrucToDelta(string DeltaName) {
+ real scalar CONFA_loglevel, p, t, varno, facno, i, j, k, fac1, fac2, k1, k2;
+ // log level, # obs vars, # parameters, current var, current factor, cycle indices, temp indices
+ real matrix Lambda, Phi, Theta, Sigma, CONFA_Struc, Delta, DeltaRow;
+ // must be self-explanatory
+ real matrix U, E;
+ // identity matrices of the size #factors and #obs vars
+
+ // loglevel
+
+ CONFA_loglevel = strtoreal( st_global("CONFA_loglevel"))
+
+ // need the CONFA matrices
+ CONFA_Struc = st_matrix("CONFA_Struc")
+ Sigma = st_matrix("CONFA_Sigma")
+ Lambda = st_matrix("CONFA_Lambda")
+ Phi = st_matrix("CONFA_Phi")
+ // Theta = st_matrix("CONFA_Theta")
+
+ if (CONFA_loglevel>4) CONFA_Struc
+
+ // # parameters in the model
+ t = rows(CONFA_Struc)
+
+ // cols(Delta) = t = # pars
+ // rows(Delta) = pstar = p*(p+1)/2 = length( vech( Sigma ) )
+ // but that should be accumulated one by one...
+ Delta = J(0,t,.)
+
+ // sources of u and e vectors
+ p = rows( Sigma )
+ U = I( p )
+ E = I( rows(Phi) )
+
+ for(i=1;i<=p;i++) {
+ for(j=i;j<=p;j++) {
+ if (CONFA_loglevel > 4) printf("{txt}Working with pair ({res}%2.0f{txt},{res}%2.0f{txt})\n",i,j)
+ DeltaRow = J(1,t,0)
+ // parse Struc matrix and see how each parameter affects Cov(X_i,X_j)
+ for(k=1;k<=t;k++) {
+ if (CONFA_Struc[k,1] == 1) {
+ // a mean-type entry
+ // for the moment, assume it does not affect anything
+ }
+ if (CONFA_Struc[k,1] == 2) {
+ // a lambda-type entry
+ // CONFA_Struc[k,.] = (2, equation #, variable #, factor #)
+ varno = CONFA_Struc[k,3]
+ facno = CONFA_Struc[k,4]
+ DeltaRow[1,k] = U[i,.] * U[.,varno] * E[facno,.] * Phi * Lambda' * U[.,j] +
+ U[i,.] * Lambda * Phi * E[.,facno] * U[varno,.] * U[.,j]
+ }
+ if (CONFA_Struc[k,1] == 3) {
+ // a phi-type entry
+ // CONFA_Struc[k,.] = (3, equation #, `factor`kk'', `factor`k'')
+ fac1 = CONFA_Struc[k,3]
+ fac2 = CONFA_Struc[k,4]
+ DeltaRow[1,k] = U[i,.] * Lambda * E[.,fac1] * E[fac2,.] * Lambda' * U[.,j]
+ }
+ if (CONFA_Struc[k,1] == 4) {
+ // a theta-type entry
+ // CONFA_Struc[k,.] = (4, equation #, variable #, 0)
+ varno = CONFA_Struc[k,3]
+ DeltaRow[1,k] = (i==j) & (i==varno)
+ }
+ if (CONFA_Struc[k,1] == 5) {
+ // a theta_{jk}-type entry
+ // CONFA_Struc[k,.] = (5, equation #, variable k1, variable k2)
+ k1 = CONFA_Struc[k,3]
+ k2 = CONFA_Struc[k,4]
+ DeltaRow[1,k] = ((i==k1) & (j==k2) ) | ((i==k2) & (j==k1))
+ }
+ }
+ Delta = Delta \ DeltaRow
+ }
+ }
+
+ st_matrix(DeltaName,Delta)
+}
+
+
+///////////////////////////////////////////
+// needed by confa_p.ado
+
+void CONFA_P_EB(string Fnames, string ObsVarNames, string ToUseName) {
+ real matrix ff, xx;
+ // views
+ real matrix bb, Sigma, Lambda, Theta, Phi;
+ // substantive matrices
+ real scalar p
+
+ // view on the newly generated factors
+ st_view(ff=.,.,tokens(Fnames),ToUseName)
+
+ // view on the observed variables
+ st_view(xx=.,.,tokens(ObsVarNames),ToUseName)
+
+ // get the estimated matrices
+ bb = st_matrix("e(b)")
+ Sigma = st_matrix("e(Sigma)")
+ Theta = st_matrix("e(Theta)")
+ Lambda = st_matrix("e(Lambda)")
+ Phi = st_matrix("e(Phi)")
+
+ // # observed vars
+ p = rows(Sigma)
+
+ // prediction
+ ff[,] = (xx-J(rows(xx),1,1)*bb[1..p]) * invsym(Sigma) * Lambda * Phi
+}
+
+void CONFA_P_MLE(string Fnames, string ObsVarNames, string ToUseName) {
+ real matrix ff, xx;
+ // views
+ real matrix bb, Sigma, Lambda, Theta, Phi, ThetaInv;
+ // substantive matrices
+ real scalar p
+
+ // view on the newly generated factors
+ st_view(ff=.,.,tokens(Fnames),ToUseName)
+
+ // view on the observed variables
+ st_view(xx=.,.,tokens(ObsVarNames),ToUseName)
+
+ // get the estimated matrices
+ bb = st_matrix("e(b)")
+ Sigma = st_matrix("e(Sigma)")
+ Theta = st_matrix("e(Theta)")
+ Lambda = st_matrix("e(Lambda)")
+ Phi = st_matrix("e(Phi)")
+
+ // # observed vars
+ p = rows(Sigma)
+
+ // Theta is the vector of diagonal elements,
+ // so the inverse is easy!
+ ThetaInv = diag( 1:/Theta )
+
+ // prediction
+ ff[,] = (xx-J(rows(xx),1,1)*bb[1..p]) * ThetaInv * Lambda * invsym(Lambda' * ThetaInv * Lambda)
+}
+
+//////////////////////////////////
+// needed by confa_lf.ado
+
+void CONFA_NormalLKHDr( string ParsName, string lnfname) {
+ // ParsName are the parameters
+ // lnfname is the name of the likelihood variable
+ // the observed variables are in $CONFA_obsvar
+
+ real scalar CONFA_loglevel, nobsvar, ldetWS, i;
+ // log level, # obs vars, log determinant, cycle index
+ real matrix Sigma, means, SS, InvWorkSigma;
+ // intermediate computations
+ string scalar obsvar, touse;
+ // list of observed variables
+ real matrix data, lnl, parms;
+ // views
+
+ CONFA_loglevel = strtoreal( st_global("CONFA_loglevel"))
+
+ obsvar = st_global("CONFA_obsvar")
+ nobsvar = length(tokens(obsvar))
+
+ touse = st_global("CONFA_touse")
+
+ st_view(data=., ., tokens(obsvar), touse )
+ st_view(lnl=., ., tokens(lnfname), touse)
+ st_view(parms=., ., tokens(ParsName), touse)
+
+ // using the set up where the means are the first nobsvar entries of the parameter vector,
+ means = parms[1,1..nobsvar]
+
+ Sigma = CONFA_StrucToSigma(parms[1,.])
+
+ if (CONFA_loglevel > 2) {
+ parms[1,.]
+ means
+ Sigma
+ }
+
+// do some equilibration??
+
+ SS = cholesky(Sigma)
+ InvWorkSigma = solvelower(SS,I(rows(SS)))
+ InvWorkSigma = solveupper(SS',InvWorkSigma)
+ ldetWS = 2*ln(dettriangular(SS))
+
+ for( i=1; i<=rows(data); i++ ) {
+ lnl[i,1] = -.5*(data[i,.]-means)*InvWorkSigma*(data[i,.]-means)' - .5*ldetWS - .5*nobsvar*ln(2*pi())
+ }
+
+ if (CONFA_loglevel>2) {
+ sum(lnl)
+ }
+
+}
+
+// normal likelihood with missing data
+void CONFA_NormalLKHDrMiss( string ParsName, string lnfname) {
+ // ParsName are the parameters
+ // lnfname is the name of the likelihood variable
+ // the observed variables are in $CONFA_obsvar
+
+
+ real scalar CONFA_loglevel, nobsvar, thisldetWS, i, j;
+ // log level, # obs vars, log determinant, cycle index
+ real matrix Sigma, means, thisSigma, thisSS, thisInvSigma, thispattern, parms;
+ // intermediate computations
+ string scalar obsvar, misspat, touse;
+ // list of observed variables; the names of the missing patterns and touse tempvars
+ real matrix data, lnl, parmview, pattern, mdata, mlnl, info;
+ // views
+
+ CONFA_loglevel = strtoreal( st_global("CONFA_loglevel"))
+
+ obsvar = st_global("CONFA_obsvar")
+ nobsvar = length(tokens(obsvar))
+
+ misspat = st_global("CONFA_miss")
+ touse = st_global("CONFA_touse")
+
+ st_view(pattern=., ., misspat, touse )
+ st_view(data=., ., tokens(obsvar), touse )
+ st_view(lnl=., ., lnfname, touse )
+
+ // STILL USING THE FIRST OBSERVATIONS TO GET THE PARAMETERS!!!
+ st_view(parmview=., ., tokens(ParsName), touse )
+ parms = parmview[1,1..cols(parmview)]
+
+ if (CONFA_loglevel>2) {
+ obsvar
+ parms
+ }
+
+ // using the set up where the means are the first nobsvar entries of the parameter vector,
+ means = parms[1..nobsvar]
+
+ Sigma = CONFA_StrucToSigma(parms)
+
+ // utilize an existing set up of the missing data patterns
+ // data assumed to be sorted by the patterns of missing data
+
+ info = panelsetup( pattern, 1 )
+
+ for (i=1; i<=rows(info); i++) {
+ panelsubview(mdata=., data, i, info)
+ panelsubview(mlnl=., lnl, i, info)
+ // mdata should contain the portion of the data with the same missing data pattern
+ // mlnl will be conforming to mdata
+
+ // OK, now need to figure out that pattern
+ thispattern = J(1, cols(data), 1) - colmissing( mdata[1,] )
+ if (CONFA_loglevel > 2) {
+ printf("{txt}Pattern #{res}%5.0f{txt} :", i)
+ thispattern
+ };
+
+ // modify the matrices
+
+ thisSigma = select( select( Sigma, thispattern), thispattern' )
+ thisSS = cholesky(thisSigma)
+ thisInvSigma = solvelower(thisSS,I(rows(thisSS)))
+ thisInvSigma = solveupper(thisSS',thisInvSigma)
+ thisldetWS = 2*ln(dettriangular(thisSS))
+
+ if (CONFA_loglevel > 3) {
+ thisSigma
+ thisInvSigma
+ };
+
+ for( j=1; j<=rows(mdata); j++ ) {
+ // this is actually a single line broken by arithmetic operator signs
+ // that's bad style but it works
+ mlnl[j,1] = -.5*(select(data[j,.],thispattern)-select(means,thispattern)) *
+ thisInvSigma *
+ (select(data[j,.],thispattern)-select(means,thispattern))' -
+ .5*thisldetWS - .5*sum(thispattern)*ln(2*pi())
+ }
+
+ if (CONFA_loglevel>3) {
+ mlnl
+ };
+
+ }
+
+
+}
+
+// Bollen-Stine bootstrap rotation
+void CONFA_BSrotate(
+ string SigmaName, // the parameter matrix name
+ string varnames // the variable names
+ ) {
+
+ // declarations
+ real matrix data // views of the data
+ real matrix Sigma, SS, S2, SS2 // the covariance matrices and temp matrices
+ real matrix means // the means -- need modifications for weighted data!!!
+ real scalar n // dimension, no. obs
+
+ // get the data in
+ st_view(data=., ., tokens(varnames) )
+ n=rows(data)
+
+ Sigma = st_matrix(SigmaName)
+
+ // probability weights!!!
+ means = colsum(data)/n
+ SS = (cross(data,data)-n*means'*means)/(n-1)
+
+ S2 = cholesky(Sigma)
+ SS2 = cholesky(SS)
+ SS2 = solveupper(SS2',I(rows(SS)))
+
+ data[,] = data*SS2*S2'
+
+}
+
+
+// build a library
+mata mlib create lconfa, replace
+mata mlib add lconfa *()
+mata mlib index
+
+end
+// of mata
+
+exit
+
+// don't need this:
+
+string scalar CONFA_UL( string input ) {
+
+ string rowvector s;
+ real scalar i,j,n;
+
+ // tokenize input into a string vector
+ s = tokens( input )
+ n = cols( s )
+ for(i=1;i<=n;i++) {
+ // as I go over the elements, compare to the previous ones
+ for(j=1;j1 {
+ * display the factor correlations
+
+ di as text "{hline 13}{c TT}{hline 64}"
+ if "`e(vcetype)'" ~= "" {
+ di as text " {c |} {center 15:`e(vcetype)'}"
+ }
+ di as text " {c |} Coef. Std. Err. z P>|z| [$S_level% Conf. Interval]"
+ di as text "{hline 13}{c +}{hline 64}"
+
+ * parse the factor names
+ local fnames : rownames e(Phi)
+ * parse the unitvar list to be used in -inlist-
+ local unitvarlist = `"""' + subinstr("`e(unitvar)'"," ",`"",""',.) + `"""'
+
+ _diparm __lab__ , label("Factors") eqlabel
+
+ forvalues i=1/`q' {
+ local i1 = `i'+1
+ forvalues j=`i1'/`q' {
+ if inlist("`: word `i' of `fnames''", `unitvarlist') & inlist("`: word `j' of `fnames''", `unitvarlist') {
+ * both factor variances are constrained at 1, display as is
+ _diparm phi_`i'_`j' , prob label("`: word `i' of `fnames''-`: word `j' of `fnames''") `level' `bound'
+ }
+ else if inlist("`: word `i' of `fnames''", `unitvarlist') & !inlist("`: word `j' of `fnames''", `unitvarlist') {
+ * `i' is restricted unit variance, `j' is not
+ _diparm phi_`i'_`j' phi_`j'_`j', ///
+ function( @1/sqrt(@2) ) d( 1/sqrt(@2) -0.5*@1/sqrt(@2*@2*@2) ) ///
+ prob label("`: word `i' of `fnames''-`: word `j' of `fnames''") `level' `bound'
+ }
+ else if !inlist("`: word `i' of `fnames''", `unitvarlist') & inlist("`: word `j' of `fnames''", `unitvarlist') {
+ * `j' is restricted unit variance, `i' is not
+ _diparm phi_`i'_`j' phi_`i'_`i', ///
+ function( @1/sqrt(@2) ) d( 1/sqrt(@2) -0.5*@1/sqrt(@2*@2*@2) ) ///
+ prob label("`: word `i' of `fnames''-`: word `j' of `fnames''") `level' `bound'
+ }
+ else {
+ * display correlation transform
+ _diparm phi_`i'_`j' phi_`i'_`i' phi_`j'_`j', ///
+ function( @1/sqrt(@2*@3) ) d( 1/sqrt(@2*@3) -0.5*@1/sqrt(@2*@2*@2*@3) -0.5*@1/sqrt(@2*@3*@3*@3) ) ///
+ prob label("`: word `i' of `fnames''-`: word `j' of `fnames''") `level' `bound'
+ }
+ }
+ }
+
+ }
+
+
+ if "`e(correlated)'" ~= "" {
+
+ if `q' < 2 {
+ * need to display the header
+
+ di as text "{hline 13}{c TT}{hline 64}"
+ if "`e(vcetype)'" ~= "" {
+ di as text " {c |} {center 15:`e(vcetype)'}"
+ }
+ di as text " {c |} Coef. Std. Err. z P>|z| [$S_level% Conf. Interval]"
+ di as text "{hline 13}{c +}{hline 64}"
+ }
+
+ * print out correlated measurement errors
+ _diparm __lab__ , label("Errors") eqlabel
+ local correlated `e(correlated)'
+ local obsvar `e(observed)'
+ while "`correlated'" != "" {
+ gettoken corrpair correlated : correlated , match(m)
+ gettoken corr1 corrpair : corrpair, parse(":")
+ unab corr1 : `corr1'
+ gettoken sc corr2 : corrpair, parse(":")
+ unab corr2 : `corr2'
+
+ poslist `obsvar' \ `corr1', global(CFA_temp)
+ local k1 = $CFA_temp
+ poslist `obsvar' \ `corr2', global(CFA_temp)
+ local k2 = $CFA_temp
+
+ _diparm theta_`k1'_`k2' theta_`k1' theta_`k2', ///
+ function( @1/sqrt(@2*@3) ) d( 1/sqrt(@2*@3) -0.5*@1/sqrt(@2*@2*@2*@3) -0.5*@1/sqrt(@2*@3*@3*@3) ) ///
+ prob label("`corr1'-`corr2'") `level' `bound'
+
+ }
+
+ }
+ else if `q'<2 {
+ di as text _n "Nothing to display" _n
+ }
+
+ di as text "{hline 13}{c BT}{hline 64}"
+
+ global CFA_temp
+
+end
+
+program FitIndices, rclass
+
+ syntax , [all tli rmsea rmsr aic bic]
+
+ di _n "{txt} Fit indices" _n
+ return add
+
+ * all, by default
+ if "`*'" == "" local all 1
+
+ * the fundamentals
+ local p = `: word count `e(obsvar)''
+
+ if "`rmsea'`all'"~="" {
+ return scalar RMSEA = sqrt( max( (e(lr_u)-e(df_u))/(e(N)-1), 0 )/e(df_u) )
+ tempname ll lu
+ scalar `ll' = cond(chi2(e(df_u),e(lr_u))>0.95,npnchi2(e(df_u),e(lr_u),0.95),0)
+ scalar `lu' = cond(chi2(e(df_u),e(lr_u))>0.05,npnchi2(e(df_u),e(lr_u),0.05),0)
+ return scalar RMSEA05 = sqrt( `ll'/( (e(N)-1)*e(df_u) ) )
+ return scalar RMSEA95 = sqrt( `lu'/( (e(N)-1)*e(df_u) ) )
+ di "{txt}RMSEA {col 8}= {res}" %6.4f return(RMSEA) _c
+ di "{txt}, 90% CI{col 8}= ({res}" %6.4f return(RMSEA05) "{txt}, {res}" %6.4f return(RMSEA95) "{txt})"
+ }
+
+ if "`rmsr'`all'"~="" {
+ cap mat li e(S)
+ if _rc {
+ * no matrix posted
+ return scalar RMSR = .
+ }
+ else {
+ tempname res
+ mata : st_numscalar("`res'",norm(vech(st_matrix("e(Sigma)") - st_matrix("e(S)"))) )
+ return scalar RMSR = `res'/sqrt(e(pstar) )
+ }
+ di "{txt}RMSR {col 8}= {res}" %6.4f return(RMSR)
+ }
+
+ if "`tli'`all'"~="" {
+ return scalar TLI = (e(lr_indep)/e(df_indep)-e(lr_u)/e(df_u))/(e(lr_indep)/e(df_indep)-1)
+ di "{txt}TLI {col 8}= {res}" %6.4f return(TLI)
+ }
+
+ if "`cfi'`all'"~="" {
+ return scalar CFI = 1 - max( e(lr_u)-e(df_u),0 )/max( e(lr_u)-e(df_u), e(lr_indep)-e(df_indep),0 )
+ di "{txt}CFI {col 8}= {res}" %6.4f return(CFI)
+ }
+
+ if "`aic'`all'"~="" {
+ if "`e(wexp)'" == "" & "`e(vcetype)'"~="Robust" return scalar AIC = -2*e(ll) + 2*e(df_m)
+ else return scalar AIC = .
+ di "{txt}AIC {col 8}= {res}" %8.3f return(AIC)
+ }
+
+ if "`bic'`all'"~="" {
+ if "`e(wexp)'" == "" & "`e(vcetype)'"~="Robust" return scalar BIC = -2*e(ll) + e(df_m)*ln( e(N) )
+ else return scalar BIC = .
+ di "{txt}BIC {col 8}= {res}" %8.3f return(BIC)
+ }
+
+end
+
+exit
+
+Version history:
+1.0.0 9 Jan 2008 -- Correlate
+ FitIndices
+1.0.1 12 Sep 2008 -- AIC, BIC
+1.0.2 Oct 2008 -- bound for Correlate CI
+ correlated measurement errors
+ CI for RMSEA
diff --git a/Modules/ado/plus/c/confa_estat.sthlp b/Modules/ado/plus/c/confa_estat.sthlp
new file mode 100644
index 0000000..090cd9b
--- /dev/null
+++ b/Modules/ado/plus/c/confa_estat.sthlp
@@ -0,0 +1,205 @@
+{smcl}
+{* *! version 1.1.13 04jun2007}{...}
+{cmd:help confa postestimation}{right: ({browse "http://www.stata-journal.com/article.html?article=st0169":SJ9-3: st0169})}
+{hline}
+
+{title:Title}
+
+{p2colset 5 29 31 2}{...}
+{p2col :{hi:confa postestimation} {hline 2}}Postestimation tools for confa{p_end}
+{p2colreset}{...}
+
+
+{title:Description}
+
+{pstd}The following commands are available after {helpb confa}:{p_end}
+
+{synoptset 17}{...}
+{p2coldent :command}description{p_end}
+{synoptline}
+{synopt :{helpb confa_estat##fit:estat fitindices}}fit indices{p_end}
+{synopt :{helpb confa_estat##ic:estat aic}}AIC{p_end}
+{synopt :{helpb confa_estat##ic:estat bic}}BIC{p_end}
+{synopt :{helpb confa_estat##corr:estat correlate}}correlations of factors and measurement errors{p_end}
+{synopt :{helpb confa_estat##predict:predict}}factor scores{p_end}
+{synopt :{helpb bollenstine}}Bollen-Stine bootstrap{p_end}
+{synoptline}
+{p2colreset}{...}
+
+
+{marker fit}{...}
+{title:The estat fitindices command}
+
+ {title:Syntax}
+
+{p 8 15 2}
+{cmd:estat} {cmdab:fit:indices}
+[{cmd:,} {it:options}]
+
+{p2colset 9 27 29 2}{...}
+{p2col:{it:options}}fit index{p_end}
+{p2line}
+{p2col :{opt aic}}Akaike information criterion{p_end}
+{p2col :{opt bic}}Schwarz Bayesian information criterion{p_end}
+{p2col :{opt cfi}}comparative fit index{p_end}
+{p2col :{opt rmsea}}root mean squared error of approximation{p_end}
+{p2col :{opt rmsr}}root mean squared residual{p_end}
+{p2col :{opt tli}}Tucker-Lewis index{p_end}
+{p2col :{opt _all}}all the above indices, the default{p_end}
+{p2line}
+{p2colreset}{...}
+
+ {title:Description}
+
+{pmore}{opt estat }{cmd:fitindices} computes, prints, and saves into
+{cmd:r()} results several traditional fit indices.
+
+ {title:Options}
+
+{phang2}
+{opt aic} requests the Akaike information criterion (AIC).
+
+{phang2}
+{opt bic} requests the Schwarz Bayesian information criterion (BIC).
+
+{phang2}
+{opt cfi} requests the CFI (Bentler 1990b).
+
+{phang2}
+{opt rmsea} requests the RMSEA (Browne and Cudeck 1993).
+
+{phang2}
+{opt rmsr} requests the RMSR.
+
+{phang2}
+{opt tli} requests the TLI (Tucker and Lewis 1973).
+
+{phang2}
+{opt _all} requests all the above indices. This is the default
+behavior if no option is specified.
+
+
+{marker ic}{...}
+{title:The estat aic and estat bic commands}
+
+ {title:Syntax}
+
+{p 8 15 2}
+{cmd:estat} {cmd:aic}
+
+{p 8 15 2}
+{cmd:estat} {cmd:aic}
+
+ {title:Description}
+
+{pmore}{cmd:estat aic} and {cmd:estat bic} compute the Akaike and Schwarz
+Bayesian information criteria, respectively.
+
+
+{title:The estat correlate command}
+
+ {title:Syntax}
+
+{p 8 15 2}
+{cmd:estat} {cmdab:corr:elate}
+[{cmd:,}
+{opt level(#)}
+{opt bound}]
+
+ {title:Description}
+
+{marker corr}{...}
+{pmore}{opt estat} {cmd:correlate} transforms the covariance parameters into
+correlations for factor covariances and measurement-error covariances. The
+delta method standard errors are given; for correlations close to plus or
+minus 1, the confidence intervals may extend beyond the range of admissible
+values.{p_end}
+
+ {title:Options}
+
+{phang2}{opt level(#)} changes the confidence level for confidence-interval
+reporting.{p_end}
+
+{phang2}{cmd:bound} provides an alternative confidence interval based on
+Fisher's z transform of the correlation coefficient. It guarantees
+that the end points of the interval are in the (-1,1) range, provided the
+estimate itself is in this range.
+
+
+{marker predict}{...}
+{title:The predict command}
+
+ {title:Syntax}
+
+{p 8 19 2}
+{cmd:predict} {dtype} {it:{help newvarlist}} {ifin} [{cmd:,} {it:scoring_method}]
+
+{p2colset 9 27 29 2}{...}
+{p2col:{it:scoring_method}}factor scoring method{p_end}
+{p2line}
+{p2col:{cmdab:reg:ression}}regression, or empirical Bayes, score{p_end}
+{p2col:{cmdab:emp:iricalbayes}}alias for {cmd:regression}{p_end}
+{p2col:{cmdab:eb:ayes}}alias for {cmd:regression}{p_end}
+{p2col:{opt mle}}MLE, or Bartlett score{p_end}
+{p2col:{cmdab:bart:lett}}alias for {cmd:mle}{p_end}
+{p2line}
+{p2colreset}{...}
+
+ {title:Description}
+
+{pmore} {cmd:predict} can be used to create factor scores following {cmd:confa}.
+The number of variables in {it:newvarlist} must be the same as the number of
+factors in the model specification; all factors are predicted at once by the
+relevant matrix formula.
+
+ {title:Options}
+
+{phang2}
+{opt regression}, {opt empiricalbayes}, or {opt ebayes}
+requests regression, or empirical Bayes, factor scoring procedure.
+
+{phang2}
+{opt mle} or {opt bartlett} requests Bartlett scoring procedure.
+
+
+{title:Example}
+
+{phang}{cmd:. use hs-cfa}{p_end}
+{phang}{cmd:. confa (vis: x1 x2 x3) (text: x4 x5 x6) (math: x7 x8 x9), from(iv) corr(x7:x8)}{p_end}
+{phang}{cmd:. estat fit}{p_end}
+{phang}{cmd:. estat corr}{p_end}
+{phang}{cmd:. estat corr, bound}{p_end}
+{phang}{cmd:. predict fa1-fa3, reg}{p_end}
+{phang}{cmd:. predict fb1-fb3, bart}{p_end}
+
+
+{title:References}
+
+{phang}
+Bentler, P. M. 1990. Comparative fit indexes in structural models.
+{it:Psychological Bulletin} 107: 238-246.
+
+{phang}
+Browne, M. W., and R. Cudeck. 1993. Alternative ways of assessing model fit.
+In {it:Testing Structural Equation Models}, ed. K. A. Bollen and J. S. Long,
+136-162. Newbury Park, CA: Sage.
+
+{phang}
+Tucker, L. R., and C. Lewis. 1973. A reliability coefficient for maximum likelihood factor analysis. {it:Psychometrika} 38: 1-10.
+
+
+{title:Author}
+
+{pstd}Stanislav Kolenikov{p_end}
+{pstd}Department of Statistics{p_end}
+{pstd}University of Missouri{p_end}
+{pstd}Columbia, MO{p_end}
+{pstd}kolenikovs@missouri.edu{p_end}
+
+
+{title:Also see}
+
+{psee}
+Article: {it:Stata Journal}, volume 9, number 3: {browse "http://www.stata-journal.com/article.html?article=st0169":st0169}
+
+{psee}Online: {helpb confa}, {helpb bollenstine}{p_end}
diff --git a/Modules/ado/plus/c/confa_lf.ado b/Modules/ado/plus/c/confa_lf.ado
new file mode 100644
index 0000000..9b968c3
--- /dev/null
+++ b/Modules/ado/plus/c/confa_lf.ado
@@ -0,0 +1,20 @@
+*! Log likelihood for confa: linear form; part of confa suite; 16 Oct 2008
+program define confa_lf
+
+ args lnf $CONFA_args
+ * $CONFA_args contains the names of the equations, but
+ * we need the variable names
+ gettoken lnf allthenames : 0
+
+ tempvar lnl
+ qui g double `lnl' = .
+
+ mata: CONFA_NormalLKHDr( "`allthenames'", "`lnl'")
+
+ qui replace `lnf' = `lnl'
+
+ if $CONFA_loglevel > 3 li `lnl'
+
+end
+
+exit
diff --git a/Modules/ado/plus/c/confa_lfm.ado b/Modules/ado/plus/c/confa_lfm.ado
new file mode 100644
index 0000000..0dfabfb
--- /dev/null
+++ b/Modules/ado/plus/c/confa_lfm.ado
@@ -0,0 +1,20 @@
+*! Log likelihood for confa: linear form; part of confa suite; 23 Apr 2009
+program define confa_lfm
+
+ args lnf $CONFA_args
+ * $CONFA_args contains the names of the equations, but
+ * we need the variable names
+ gettoken lnf allthenames : 0
+
+ tempvar lnl
+ qui g double `lnl' = .
+
+ mata: CONFA_NormalLKHDrMiss( "`allthenames'", "`lnl'")
+
+ qui replace `lnf' = `lnl'
+
+ if $CONFA_loglevel > 3 li `lnl'
+
+end
+
+exit
diff --git a/Modules/ado/plus/c/confa_p.ado b/Modules/ado/plus/c/confa_p.ado
new file mode 100644
index 0000000..99e2a71
--- /dev/null
+++ b/Modules/ado/plus/c/confa_p.ado
@@ -0,0 +1,89 @@
+*! v.1.0 -- prediction commands for confa suite; 16 Oct 2008
+program define confa_p
+ version 10
+
+* set trace on
+
+* di as inp "`0'"
+
+ syntax anything [if] [in], [EBayes EMPiricalbayes REGression MLE BARTlett SCores]
+
+* fork to equation scores or factor scores
+
+ if "`scores'"!="" EqScores `0'
+ else if "`ebayes'`empiricalbayes'`regression'`mle'`bartlett'" != "" FScores `0'
+ else {
+ di as err "cannot figure those options out"
+ exit 198
+ }
+
+end
+
+program define EqScores
+
+ * implicitly used by _robust and svy
+ * typical request: predict stub*, scores
+ * stub* is not parsed well by newvarlist, have to use anything
+ syntax anything [if] [in], scores
+ marksample touse, novarlist
+ ml score `anything' if `touse'
+end
+
+program define FScores
+
+ * user requested factor predictions
+
+ syntax newvarlist [if] [in], [EBayes EMPiricalbayes REGression MLE BARTlett]
+
+ marksample touse, novarlist
+
+ if "`ebayes'`empiricalbayes'`regression'`mle'`bartlett'" == "" | ///
+ ( ("`ebayes'`empiricalbayes'`regression'"~="" ) & ("`mle'`bartlett'"~="" ) ) {
+
+ di as err "One and only one factor scoring option must be specified"
+ exit 198
+ }
+ else {
+
+ local nfactors = rowsof( e(Phi) )
+
+ if "`: word count `varlist''" ~= "`nfactors'" {
+ di as err "Must specify as many new variables as there were factors in confa model"
+ exit 198
+ }
+
+ * generate new variables
+ forvalues k=1/`nfactors' {
+ tempname f`k'
+ qui gen double `f`k'' = .
+ local flist `flist' `f`k''
+ }
+
+ if "`ebayes'`empiricalbayes'`regression`" ~= "" {
+ * Empirical Bayes:
+ mata : CONFA_P_EB("`flist'", "`e(observed)'", "`touse'")
+ }
+
+ if "`mle'`bartlett'" ~= "" {
+ * MLE/Bartlett scoring:
+ mata : CONFA_P_MLE("`flist'", "`e(observed)'", "`touse'")
+ }
+
+ nobreak {
+ forvalues k=1/`nfactors' {
+ local type : word `k' of `typlist'
+ local name : word `k' of `varlist'
+ qui gen `type' `name' = `f`k'' if `touse'
+ label var `name' `"`e(factor`k')', `ebayes'`empiricalbayes'`regression'`mle'`bartlett' method"'
+ }
+ }
+
+ }
+
+
+end
+
+exit
+
+History:
+v.1.0 -- June 12, 2008: Empirical Bayes and MLE scoring
diff --git a/Modules/ado/plus/c/confirmdir.ado b/Modules/ado/plus/c/confirmdir.ado
new file mode 100644
index 0000000..b0088cd
--- /dev/null
+++ b/Modules/ado/plus/c/confirmdir.ado
@@ -0,0 +1,18 @@
+*! comfirmdir Version 1.1 dan.blanchette@duke.edu 22Jan2009
+*! Center of Entrepreneurship and Innovation Duke University's Fuqua School of Business
+* confirmdir Version 1.1 dan_blanchette@unc.edu 17Jan2008
+* research computing, unc-ch
+* - made it handle long directory names
+** confirmdir Version 1.0 dan_blanchette@unc.edu 05Oct2003
+** the carolina population center, unc-ch
+
+program define confirmdir, rclass
+ version 8
+
+ local cwd `"`c(pwd)'"'
+ quietly capture cd `"`1'"'
+ local confirmdir=_rc
+ quietly cd `"`cwd'"'
+ return local confirmdir `"`confirmdir'"'
+
+end
diff --git a/Modules/ado/plus/c/confirmdir.hlp b/Modules/ado/plus/c/confirmdir.hlp
new file mode 100644
index 0000000..78c2c98
--- /dev/null
+++ b/Modules/ado/plus/c/confirmdir.hlp
@@ -0,0 +1,54 @@
+{smcl}
+{* 17Jan2008}{...}
+{* 28Oct2004}{...}
+{* 19Nov2003}{...}
+{hline}
+help for {hi:confirmdir} {right:manual: {hi:[R] none}}
+{right:dialog: {hi: none} }
+{hline}
+
+
+{title:Confirms if directory exists}
+
+{p 8 17 2}
+{cmd:confirmdir} {it:full direcotory name}
+{p_end}
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:confirmdir} is designed for programmers who want to know if a directory exists.
+This is just like {cmd:confirm} command when used to confirm a file. If Stata allowed their
+{cmd:confirm} command to also have the "dir" option, this program would not have been
+written. Stata's {cmd:confirm file} will confirm a directory in UNIX/Linux but not in Windows.
+{cmd:confirmdir} works in all operating systems.{p_end}
+
+{title:Examples}
+
+{p 4 8 2}{cmd:. confirmdir "c:\My Favorite Directory\Where I Keep Stuff\"}{p_end}
+
+{p 4 8 2}{cmd:. confirmdir /projects/ethiopia/survey2002/data/}{p_end}
+
+
+{title:Saved Results}
+
+{p 4 8 2}The {cmd:confirmdir} command saves in {cmd:r()}:{p_end}
+
+{synoptset 20 tabbed}{...}
+{p2col 5 20 24 2: Macros}{p_end}
+{synopt:{cmd:r(confirmdir)}}return code returned by the {help cd:cd} command.{p_end}
+
+
+{title:Author}
+
+{p 4 4 2}
+Dan Blanchette {break}
+Center of Entrepreneurship and Innovation {break}
+Duke University's Fuqua School of Business {break}
+Dan.Blanchette@Duke.edu{p_end}
+
+
+{title:Also see}
+
+{p 4 13 2}On-line: {help confirm:confirm} {help cd:cd}, {help tmpdir:tmpdir} (if installed){p_end}
+
diff --git a/Modules/ado/plus/c/convlist.ado b/Modules/ado/plus/c/convlist.ado
new file mode 100644
index 0000000..9d59d11
--- /dev/null
+++ b/Modules/ado/plus/c/convlist.ado
@@ -0,0 +1,62 @@
+program def convlist, rclass
+*! NJC 1.0.0 9 April 2001
+ version 6.0
+ gettoken lists 0 : 0, parse(",")
+ if "`lists'" == "" | "`lists'" == "," {
+ di in r "no lists specified"
+ exit 198
+ }
+
+ tokenize "`lists'", parse("\")
+ if "`4'" != "" | "`2'" != "\" {
+ di in r "incorrect syntax"
+ exit 198
+ }
+ numlist "`1'"
+ local list1 `r(numlist)'
+ local n1 : word count `list1'
+ numlist "`3'"
+ local list2 `r(numlist)'
+ local n2 : word count `list2'
+
+ syntax [ , Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ local n3 = `n1' + `n2' - 1
+ local k = 1
+ while `k' <= `n3' {
+ tempname c`k'
+ scalar `c`k'' = 0
+ local k = `k' + 1
+ }
+
+ tokenize `list1'
+
+ local i = 1
+ while `i' <= `n1' {
+ local j = 1
+ while `j' <= `n2' {
+ local b`j' : word `j' of `list2'
+ local k = `i' + `j' - 1
+ scalar `c`k'' = `c`k'' + (``i'' * `b`j'')
+ local j = `j' + 1
+ }
+ local i = `i' + 1
+ }
+
+ local k = 1
+ while `k' <= `n3' {
+ local this = `c`k''
+ local newlist "`newlist'`this' "
+ local k = `k' + 1
+ }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
+
diff --git a/Modules/ado/plus/c/convlist.hlp b/Modules/ado/plus/c/convlist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/c/convlist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/c/countfit.ado b/Modules/ado/plus/c/countfit.ado
new file mode 100644
index 0000000..4e1103b
--- /dev/null
+++ b/Modules/ado/plus/c/countfit.ado
@@ -0,0 +1,877 @@
+*! version 0.8.1 - 2009-07-31
+* work around S11 bug in estimates table
+
+* To do:
+* 1) add weights
+* 2) use returns rather than scalars
+
+// compare count models
+
+capture program drop countfit
+program define countfit, rclass
+ version 9.0
+
+ * 2009-07-31
+ local vwidth = 32 // causes error in Stata 11
+ local vwidth = 30
+
+ syntax varlist [if] [in] ///
+ , [Generate(string) replace ///
+ INFlate(string) /// inflation variables
+ MAXcount(integer 9) ///
+ NOGraph /// suppress graph of differences in predicted probabilities
+ NODifferences /// suppress table of differences in predicted probabilities
+ NOEstimates /// suppress table of estimated parameters
+ NOFit /// suppress table of fit statistics
+ Prm Nbreg ZIP ZINb ///
+ nodash ///
+ NOConstant ///
+ NOPRTable ///
+ note(string) /// note for graph
+ GRAPHexport(string) /// options passed to graph export
+ NOIsily ///
+ ]
+
+// trap weights
+
+ if "`e(wtype)'"!="" {
+ di in r "-countfix- does not work with weights."
+ exit
+ }
+
+// define variable lists
+
+ * inflate is same as rhs if not specified
+ if "`inflate'"=="" {
+ ** better way to do this?
+ local nvars : word count `varlist'
+ foreach i of numlist 2(1)`nvars' {
+ local var : word `i' of `varlist'
+ local inflate "`inflate' `var'"
+ }
+ }
+
+// set up printing
+
+ local f83 "%8.3f"
+ local f93 "%9.3f"
+ local f93l "%-9.3f"
+ local f103 "%10.3f"
+ local dash ""
+ if "`nodash'"=="" {
+ local dash ///
+ "--------------------------------------------------------------------------"
+ }
+
+// construct information on models being assessed
+
+ * defalult name is CF for variables created
+ if "`generate'"=="" local set "CF"
+ local set "`generate'" // label for sets of models
+ local modellist "" // list of types of models estimated
+ local mdlnmlist "" // like modellist but begin with generate prefix _
+ local pltsym "" // symbols used in the plot
+ local plty "" // y variables to plot
+ local pltx "" // x variables to plot
+ local mdlnum = 1 // number associated with each model
+
+ * set up information for all models specified
+ if "`prm'"=="prm" {
+ local mdlnmlist "`mdlnmlist' `set'PRM"
+ local modellist "PRM "
+ local pltx "`set'PRMval"
+ local plty "`set'PRMdif "
+ local pltsym "Th "
+ local pltleg1 "`set'PRM"
+ local mdlnum = `mdlnum' + 1
+ }
+ if "`nbreg'"=="nbreg" {
+ local mdlnmlist "`mdlnmlist' `set'NBRM"
+ local modellist "`modellist'NBRM "
+ local pltx "`set'NBRMval"
+ local plty "`plty' `set'NBRMdif "
+ local pltsym "`pltsym' Sh "
+ local pltleg`mdlnum' "`set'NBRM"
+ local mdlnum = `mdlnum' + 1
+ }
+ if "`zip'"=="zip" {
+ local mdlnmlist "`mdlnmlist' `set'ZIP"
+ local modellist "`modellist'ZIP "
+ local pltx "`set'ZIPval"
+ local plty "`plty' `set'ZIPdif "
+ local pltsym "`pltsym' T "
+ local pltleg`mdlnum' "`set'ZIP"
+ local mdlnum = `mdlnum' + 1
+ }
+ if "`zinb'"=="zinb" {
+ local mdlnmlist "`mdlnmlist' `set'ZINB"
+ local modellist "`modellist'ZINB "
+ local pltx "`set'ZINBval"
+ local plty "`plty' `set'ZINBdif "
+ local pltsym "`pltsym' S "
+ local pltleg`mdlnum' "`set'ZINB"
+ local mdlnum = `mdlnum' + 1
+ }
+ * if none, then all
+ if "`prm'"=="" & "`nbreg'"=="" & "`zip'"=="" & "`zinb'"=="" {
+ local pltx "`set'PRMval"
+ local plty "`set'PRMdif `set'NBRMdif `set'ZIPdif `set'ZINBdif"
+ local pltsym "Th Sh T S"
+ local pltleg1 "`set'PRM"
+ local pltleg2 "`set'NBRM"
+ local pltleg3 "`set'ZIP"
+ local pltleg4 "`set'ZINB"
+ local mdlnmlist "`set'PRM `set'NBRM `set'ZIP `set'ZINB"
+ local modellist "PRM NBRM ZIP ZINB"
+ local prm "prm"
+ local nbreg "nbreg"
+ local zip "zip"
+ local zinb "zinb"
+ * drop? local alphaopt "drop(lnalpha:_cons)"
+ }
+
+// estimate models
+
+ * 2009-07-31
+ _count_estimate `varlist' `if' `in' [`fweight' `pweight' `iweight'], ///
+ max(`maxcount') gen(`generate') `replace' inflate(`inflate') ///
+ `prm' `nbreg' `zip' `zinb' `noconstant' `noisily'
+
+// table of estimates
+
+
+ if "`noestimates'"=="" {
+ estimates table `mdlnmlist', eform ///
+ b(%9.3f) t(%7.2f) label varwidth(`vwidth') ///
+ stats(alpha N ll bic aic)
+ }
+
+// summary table of mean observed - predicted probabilities
+
+ local c1 = 10
+ local c2 = 25
+ local c3 = 31
+ local c4 = 47
+
+ if "`nodifferences'"=="" {
+
+ di in g "Comparison of Mean Observed and Predicted Count"
+ di
+ di in g " " _col(`c1') " Maximum" ///
+ _col(`c2') " At" ///
+ _col(`c3') " Mean"
+ di in g "Model" _col(`c1') " Difference" ///
+ _col(`c2') "Value" ///
+ _col(`c3') " |Diff|"
+ di in g "---------------------------------------------"
+ }
+
+ * loop through models and compute differences
+ foreach m in `modellist' {
+
+ local modelnm "`set'`m'"
+
+ * stats on difference
+ qui sum `modelnm'dif
+ local toplot "`toplot' `modelnm'dif"
+ local `m'difsd = r(sd) // sd of obs-pred
+ local `m'difmin = r(min) // min
+ local `m'difmax = r(max) // max
+
+ * stats on mean absolute difference
+ capture drop `modelnm'difabs
+ qui gen `modelnm'absdif = abs(`modelnm'dif)
+ qui sum `modelnm'absdif
+ local `m'absdifmax = r(max) // max
+ scalar absdifsd`m' = r(sd) // sd
+ scalar absdifmn`m' = r(mean) // mean
+ * find values for largest difference
+ tempname difval
+ qui gen `difval' = (`modelnm'absdif>``m'absdifmax'-.00001)*_n ///
+ if `modelnm'absdif!=.
+ qui sum `difval'
+ local `m'absdifmaxval = r(max) - 1
+
+ * sign of deviation
+ tempname maxdif // 0.8.0
+ if ``m'absdifmax' == abs(``m'difmin') {
+ *local maxdif = ``m'difmin' // 0.8.0
+ scalar `maxdif' = ``m'difmin'
+ }
+ if ``m'absdifmax' == abs(``m'difmax') {
+ *local maxdif = ``m'difmax' // 0.8.0
+ scalar `maxdif' = ``m'difmax'
+ }
+
+ if "`nodifferences'"=="" {
+ * print summary of differences from predictions
+ di in y "`modelnm'" _col(`c1') in y `f83' `maxdif' ///
+ _col(`c2') `f83' " ``m'absdifmaxval'" ///
+ _col(`c3') `f83' absdifmn`m'
+ }
+
+ } // loop through models
+
+// TABLES OF OBSERVED AND PREDICTED COUNTS
+
+ if "`noprtable'" == "" {
+
+ foreach t in `mdlnmlist' {
+
+ qui {
+ sum `t'absdif
+ local max = r(N) - 1 // largest count
+ tempname sumde sumpe sumob sumpr // 0.8.0
+ scalar `sumde' = r(sum) // sum of abs dif
+ sum `t'pearson
+ scalar `sumpe' = r(sum) // sum of pearson dif
+ sum `t'obeq
+ scalar `sumob' = r(sum) // sum of pr observed
+ sum `t'preq
+ scalar `sumpr' = r(sum) // sum of pr predicted
+ } // qui
+ local c1 = 7
+ local c2 = 19
+ local c3 = 30
+ local c4 = 40
+ local c5 = 50
+ di
+ di in y "`t'" in g ": Predicted and actual probabilities"
+ di
+ di in g "Count" _col(`c1') " Actual" ///
+ _col(`c2') "Predicted" ///
+ _col(`c3') " |Diff|" ///
+ _col(`c4') " Pearson"
+
+ local dash ""
+ if "`nodash'"=="" {
+ local dash ///
+ "------------------------------------------------"
+ }
+
+ di in g "`dash'"
+
+ foreach c of numlist 0(1)`max' {
+ local i = `c' + 1
+ tempname ob pr de pe // 0.8.0
+ scalar `ob' = `t'obeq[`i']
+ scalar `pr' = `t'preq[`i']
+ scalar `de' = abs(`t'dif[`i'])
+ scalar `pe' = `t'pearson[`i']
+
+ di in y "`c'" ///
+ _col(`c1') `f83' `ob' ///
+ _col(`c2') `f83' `pr' ///
+ _col(`c3') `f83' `de' ///
+ _col(`c4') `f83' `pe'
+
+ } // loop through counts
+
+ di in g "`dash'"
+ di in y "Sum" ///
+ _col(`c1') `f83' `sumob' ///
+ _col(`c2') `f83' `sumpr' ///
+ _col(`c3') `f83' `sumde' ///
+ _col(`c4') `f83' `sumpe'
+
+ } // loop through modellist
+
+ } // print table of predictions
+
+// PLOT DIFFERENCES
+
+ if "`nograph'"=="" {
+
+ twoway (connected `plty' `pltx', ///
+ msymbol(`pltsym') ///
+ clpat(tight_dot tight_dot tight_dot tight_dot ) ///
+ ytitle("Observed-Predicted") ///
+ subtitle("Note: positive deviations show underpredictions.", ///
+ pos(11) size(small)) ///
+ ylabel(-.10(.05).10, grid gmax gmin) ///
+ xlabel(0(1)`maxcount') ///
+ note(`note') ///
+ ysize(3.5) xsize(4.5) ///
+ legend(order(1 "`pltleg1'" 2 "`pltleg2'" ///
+ 3 "`pltleg3'" 4 "`pltleg4'")) ///
+ )
+
+ * export graph
+ if "`graphexport'" != "" {
+ qui graph export `graphexport'
+ }
+
+ }
+
+// COMPARE FIT STATISTICS
+
+ if "`nofit'"=="" {
+
+ local dash ""
+ if "`nodash'"=="" {
+ local dash ///
+ "-------------------------------------------------------------------------"
+ }
+ local c1 = 16
+ local c2 = 32
+ local c3 = 48
+ local c4 = 56
+ local c5 = 62
+
+ di _n in g "Tests and Fit Statistics"
+ di
+ tempname aicd // 0.8.0
+
+ * base PRM
+ if "`prm'"!="" {
+ local mdl1 "`set'PRM"
+ local mdl1type "PRM"
+ di in y "`mdl1'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl1' ///
+ _col(`c2') in g "AIC=" in y `f103' aic`mdl1' ///
+ _col(`c3') in g "Prefer" ///
+ _col(`c4') in g "Over" ///
+ _col(`c5') in g "Evidence"
+
+ * prm vs nbreg
+ if "`nbreg'"!="" {
+ local mdl2 "`set'NBRM"
+ local mdl2type "NBRM"
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di "`dash'"
+ * bic
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ * lr test
+ local lrfav "`mdl1type'"
+ local lrnofav "`mdl2type'"
+ if lrnb_prmp < .05 {
+ local lrfav "`mdl2type'"
+ local lrnofav "`mdl1type'"
+ }
+ di _col(`c1') in g "LRX2=" in y `f93' lrnb_prm ///
+ _col(`c2') in g "prob=" in y `f93' lrnb_prmp in g ///
+ _col(`c3') in y "`lrfav'" ///
+ _col(`c4') in y "`lrnofav'" ///
+ _col(`c5') in y "p=" `f93l' lrnb_prmp
+ } // no nbreg vs prm
+
+ * prm vs zip
+ if "`zip'"!="" {
+ local mdl2 "`set'ZIP"
+ local mdl2type "ZIP"
+ * bic
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di in g "`dash'"
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ tempname aicd // 0.8.0
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ * vuong test
+ local vufav "`mdl1type'"
+ local vunofav "`mdl2type'"
+ if vu`mdl2'>0 {
+ local vufav "`mdl2type'"
+ local vunofav "`mdl1type'"
+ }
+ di _col(`c1') in g "Vuong=" in y `f83' vu`mdl2' ///
+ _col(`c2') in g "prob=" in y `f93' vu`mdl2'p in g ///
+ _col(`c3') in y "`vufav'" ///
+ _col(`c4') in y "`vunofav'" ///
+ _col(`c5') in y "p=" `f93l' vu`mdl2'p
+ } // no zip vs prm
+
+ * prm vs zinb
+ if "`zinb'"!="" {
+ local mdl2 "`set'ZINB"
+ local mdl2type "ZINB"
+ * bic
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di in g "`dash'"
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ } // no zinb vs prm
+
+ } // if no prm
+
+ * base nbreg
+ if "`nbreg'"!="" {
+ local mdl1 "`set'NBRM"
+ local mdl1type "NBRM"
+ di in g "`dash'"
+ di in y "`mdl1'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl1' ///
+ _col(`c2') in g "AIC=" in y `f103' aic`mdl1' ///
+ _col(`c3') in g "Prefer" ///
+ _col(`c4') in g "Over" ///
+ _col(`c5') in g "Evidence"
+
+ * nbreg vs zip
+ if "`zip'"!="" {
+ local mdl2 "`set'ZIP"
+ local mdl2type "ZIP"
+ * bic
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di in g "`dash'"
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ } // no zip vs nbreg
+
+ * nbreg vs zinb
+ if "`zinb'"!="" {
+ local mdl2 "`set'ZINB"
+ local mdl2type "ZINB"
+ * bic
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di in g "`dash'"
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ * vuong test
+ local vufav "`mdl1type'"
+ local vunofav "`mdl2type'"
+ if vu`mdl2'>0 {
+ local vufav "`mdl2type'"
+ local vunofav "`mdl1type'"
+ }
+ di _col(`c1') in g "Vuong=" in y `f83' vu`mdl2' ///
+ _col(`c2') in g "prob=" in y `f93' vu`mdl2'p in g ///
+ _col(`c3') in y "`vufav'" ///
+ _col(`c4') in y "`vunofav'" ///
+ _col(`c5') in y "p=" `f93l' vu`mdl2'p
+
+ } // no zinb vs nbreg
+
+ } // if no nbreg
+
+ if "`zip'"!="" {
+
+ local mdl1 "`set'ZIP"
+ local mdl1type "ZIP"
+ di in g "`dash'"
+ di in y "`mdl1'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl1' ///
+ _col(`c2') in g "AIC=" in y `f103' aic`mdl1' ///
+ _col(`c3') in g "Prefer" ///
+ _col(`c4') in g "Over" ///
+ _col(`c5') in g "Evidence"
+
+ * zip vs zinb
+ if "`zinb'"!="" {
+ local mdl2 "`set'ZINB"
+ local mdl2type "ZINB"
+ * bic
+ global bic1 = bic`mdl1'
+ global bic2 = bic`mdl2'
+ _count_bic_dif
+ local pref = $bicpref
+ local nopref = $bicnopref
+ di in g "`dash'"
+ di in y " " in g " vs " in y "`mdl2'" ///
+ _col(`c1') in g "BIC=" in y `f103' bic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' $bicdif ///
+ _col(`c3') in y "`mdl`pref'type'" ///
+ _col(`c4') in y "`mdl`nopref'type'" ///
+ _col(`c5') in y "$bicsup"
+ * aic
+ scalar `aicd' = aic`mdl1' - aic`mdl2'
+ local aicfav "`mdl2type'"
+ local aicnofav "`mdl1type'"
+ if aic`mdl1' < aic`mdl2' {
+ local aicfav "`mdl1type'"
+ local aicnofav "`mdl2type'"
+ }
+ di _col(`c1') in g "AIC=" in y `f103' aic`mdl2' ///
+ _col(`c2') in g "dif=" in y `f103' `aicd' ///
+ _col(`c3') in y "`aicfav'" ///
+ _col(`c4') in y "`aicnofav'"
+ * lr test
+ local lrfav "`mdl1type'"
+ local lrnofav "`mdl2type'"
+ if lrnb_prmp < .05 {
+ local lrfav "`mdl2type'"
+ local lrnofav "`mdl1type'"
+ }
+ di _col(`c1') in g "LRX2=" in y `f93' lrzip_zinb ///
+ _col(`c2') in g "prob=" in y `f93' lrzip_zinbp in g ///
+ _col(`c3') in y "`lrfav'" ///
+ _col(`c4') in y "`lrnofav'" ///
+ _col(`c5') in y "p=" `f93l' lrnb_prmp
+ di in g "`dash'"
+
+ } // no zinb vs zip
+
+ } // no zip
+
+} // no fit
+
+end
+
+// compute strength of bic difference?
+
+capture program drop _count_bic_dif
+program define _count_bic_dif
+
+ * compute bin diff from model 1 and model 2
+ global bicdif = $bic1 - $bic2
+ tempname bicdabs // 0.8.0
+ scalar `bicdabs' = abs($bicdif)
+
+ * evaluate support based on bic difference
+ if `bicdabs'~=. {
+ global bicsup "Very strong"
+ if `bicdabs'<= .0000000001 {
+ global bicsup "no"
+ }
+ else if `bicdabs' <=2 {
+ global bicsup "Weak"
+ }
+ else if `bicdabs' <=6 {
+ global bicsup "Positive"
+ }
+ else if `bicdabs' <=10 {
+ global bicsup "Strong"
+ }
+ global bicpref = 2
+ global bicnopref = 1
+ if $bicdif < 0 {
+ global bicpref = 1
+ global bicnopref = 2
+ }
+ if `bicdabs'< .0000000001 & `bicdabs'>-.0000000001 {
+ global bicpref = 0
+ }
+
+ }
+end
+
+// ESTIMATE MODELS AND STORE RESULTS
+
+capture program drop _count_estimate
+program define _count_estimate, rclass
+
+ syntax varlist [if] [in] [, ///
+ inflate(varlist) ///
+ MAXcount(integer 9) Generate(string) replace ///
+ Prm Nbreg ZIP ZINb NOConstant ///
+ NOIsily ]
+
+// estimate models & create globals with stats
+
+ local set "`generate'"
+ tempname n
+
+ local noise ""
+ if "`noisily'"=="noisily" {
+ local noise "noisily"
+ }
+
+// prm
+
+ if "`prm'"!="" {
+ qui {
+ local modelnm "PRM"
+ local fullnm "`set'`modelnm'"
+ `noise' poisson `varlist' `if' `in', `noconstant'
+ estimates store `fullnm'
+ scalar ll`fullnm' = e(ll) // log lik
+ fitstat, bic
+ scalar bicp`fullnm' = r(bic_p) // bic'
+ return scalar bicp`fullnm' = r(bic_p) // 0.8.0
+ scalar aic`fullnm' = r(aic) // aic
+ scalar x2`fullnm' = r(lrx2) // lrx2 all b=0
+ scalar x2p`fullnm' = r(lrx2_p)
+ scalar bic`fullnm' = r(bic) // bic
+ if "`replace'"=="replace" {
+ capture drop `fullnm'rate
+ capture drop `fullnm'prgt
+ capture drop `fullnm'val
+ capture drop `fullnm'obeq
+ capture drop `fullnm'preq
+ capture drop `fullnm'prle
+ capture drop `fullnm'oble
+ capture drop `fullnm'absdif
+ capture drop `fullnm'dif
+ capture drop `fullnm'pearson
+ local i = 0
+ while `i'<=`maxcount' {
+ capture drop `fullnm'pr`i'
+ capture drop `fullnm'cu`i'
+ local i = `i' + 1
+ }
+ }
+ prcounts `fullnm', plot max(`maxcount') // predicted counts
+ label var `fullnm'preq "`modelnm' predicted" // predicted Pr(y)
+ gen `fullnm'dif = `fullnm'obeq - `fullnm'preq // obs - predicted
+ label var `fullnm'dif "`modelnm' obs - pred"
+ * 2004-10-29 add CT 5.34
+ scalar `n' = e(N) // sample size
+ gen `fullnm'pearson = ///
+ (`n' * `fullnm'dif * `fullnm'dif) / `fullnm'preq
+ label var `fullnm'pearson "`modelnm' contribution to Pearson X2"
+ sum `fullnm'pearson
+ } // qui
+ }
+
+// nbreg
+
+ if "`nbreg'"!="" {
+ qui {
+ local modelnm "NBRM"
+ local fullnm "`set'`modelnm'"
+ `noise' nbreg `varlist' `if' `in', `noconstant'
+ estimates store `fullnm'
+ scalar ll`fullnm' = e(ll) // log lik
+
+ scalar lrnb_prm = e(chi2_c) // lrx2 of nb vs prm
+ scalar lrnb_prmp = chiprob(1, e(chi2_c))*0.5
+
+ fitstat, bic
+ scalar bicp`fullnm' = r(bic_p) // bic'
+ scalar aic`fullnm' = r(aic) // aic
+ scalar x2`fullnm' = r(lrx2) // lrx2 all b=0
+ scalar x2p`fullnm' = r(lrx2_p)
+ scalar bic`fullnm' = r(bic) // bic
+
+ if "`replace'"=="replace" {
+ capture drop `fullnm'rate
+ capture drop `fullnm'prgt
+ capture drop `fullnm'val
+ capture drop `fullnm'obeq
+ capture drop `fullnm'preq
+ capture drop `fullnm'prle
+ capture drop `fullnm'oble
+ capture drop `fullnm'dif
+ capture drop `fullnm'absdif
+ capture drop `fullnm'pearson
+ local i = 0
+ while `i'<=`maxcount' {
+ capture drop `fullnm'pr`i'
+ capture drop `fullnm'cu`i'
+ local i = `i' + 1
+ }
+ }
+
+ prcounts `fullnm', plot max(`maxcount') // predicted counts
+ label var `fullnm'preq "`modelnm' predicted"
+ gen `fullnm'dif = `fullnm'obeq - `fullnm'preq
+ label var `fullnm'dif "`modelnm' obs - pred"
+ * 2004-10-29 add CT 5.34
+ scalar `n' = e(N) // sample size
+ gen `fullnm'pearson = ///
+ (`n' * `fullnm'dif * `fullnm'dif) / `fullnm'preq
+ label var `fullnm'pearson "`modelnm' contribution to Pearson X2"
+ sum `fullnm'pearson
+ } // qui
+ }
+
+// zip
+
+ if "`zip'"!="" {
+ qui {
+ local modelnm "ZIP"
+ local fullnm "`set'`modelnm'"
+ `noise' zip `varlist' `if' `in', ///
+ inf(`inflate') vuong `noconstant'
+ estimates store `fullnm'
+ scalar vu`fullnm' = e(vuong) // vuong vs prm
+ scalar vu`fullnm'p = 1-norm(abs(e(vuong)))
+ scalar ll`fullnm' = e(ll) // log lik
+ fitstat, bic
+ scalar bicp`fullnm' = r(bic_p) // bic'
+ scalar aic`fullnm' = r(aic) // aic
+ scalar x2`fullnm' = r(lrx2) // lrx2 all b=0
+ scalar x2p`fullnm' = r(lrx2_p)
+ scalar bic`fullnm' = r(bic) // bic
+ if "`replace'"=="replace" {
+ capture drop `fullnm'rate
+ capture drop `fullnm'prgt
+ capture drop `fullnm'val
+ capture drop `fullnm'obeq
+ capture drop `fullnm'preq
+ capture drop `fullnm'prle
+ capture drop `fullnm'oble
+ capture drop `fullnm'all0
+ capture drop `fullnm'dif
+ capture drop `fullnm'absdif
+ capture drop `fullnm'pearson
+ local i = 0
+ while `i'<=`maxcount' {
+ capture drop `fullnm'pr`i'
+ capture drop `fullnm'cu`i'
+ local i = `i' + 1
+ }
+ }
+
+ prcounts `fullnm', plot max(`maxcount') // predicted counts
+ label var `fullnm'preq "`modelnm' predicted"
+ gen `fullnm'dif = `fullnm'obeq - `fullnm'preq
+ label var `fullnm'dif "`modelnm' obs - pred"
+ * 2004-10-29 add CT 5.34
+ scalar `n' = e(N) // sample size
+ gen `fullnm'pearson = ///
+ (`n' * `fullnm'dif * `fullnm'dif) / `fullnm'preq
+ label var `fullnm'pearson "`modelnm' contribution to Pearson X2"
+ qui sum `fullnm'pearson
+ } // qui
+ }
+
+// zinb
+
+ if "`zinb'"!="" {
+ qui {
+ local modelnm "ZINB"
+ local fullnm "`set'`modelnm'"
+ `noise' zinb `varlist' `if' `in', ///
+ inf(`inflate') vuong zip `noconstant'
+ estimates store `fullnm'
+ scalar vu`fullnm' = e(vuong) // vuong vs nbreg
+ scalar vu`fullnm'p = 1-norm(abs(e(vuong)))
+ scalar ll`fullnm' = e(ll) // loglik
+ scalar lrzip_zinb = e(chi2_cp) // lrx2 zinb vs zip
+ scalar lrzip_zinbp = chiprob(1, e(chi2_cp))*0.5
+ fitstat, bic
+ scalar bicp`fullnm' = r(bic_p) // bic'
+ scalar aic`fullnm' = r(aic) // aic
+ scalar x2`fullnm' = r(lrx2) // lrx2 all b=0
+ scalar x2p`fullnm' = r(lrx2_p)
+ scalar bic`fullnm' = r(bic) // bic
+ if "`replace'"=="replace" {
+ capture drop `fullnm'rate
+ capture drop `fullnm'prgt
+ capture drop `fullnm'val
+ capture drop `fullnm'obeq
+ capture drop `fullnm'preq
+ capture drop `fullnm'prle
+ capture drop `fullnm'oble
+ capture drop `fullnm'absdif
+ capture drop `fullnm'dif
+ capture drop `fullnm'all0
+ capture drop `fullnm'pearson
+ local i = 0
+ while `i'<=`maxcount' {
+ capture drop `fullnm'pr`i'
+ capture drop `fullnm'cu`i'
+ local i = `i' + 1
+ }
+ }
+
+ prcounts `fullnm', plot max(`maxcount') // predicted counts
+ label var `fullnm'preq "`modelnm' predicted"
+ gen `fullnm'dif = `fullnm'obeq - `fullnm'preq
+ label var `fullnm'dif "`modelnm' obs - pred"
+ * 2004-10-29 add CT 5.34
+ scalar `n' = e(N) // sample size
+ gen `fullnm'pearson = ///
+ (`n' * `fullnm'dif * `fullnm'dif) / `fullnm'preq
+ label var `fullnm'pearson "`modelnm' contribution to Pearson X2"
+ qui sum `fullnm'pearson
+ } // qui
+ }
+
+end // _count_estimate
+
+exit
+* version 0.8.0 fix pr bug
+* version 0.2.1 13Apr2005 add replace; trap weights
+* version 0.2.0 27Feb2005 first documented version
diff --git a/Modules/ado/plus/c/countfit.hlp b/Modules/ado/plus/c/countfit.hlp
new file mode 100644
index 0000000..4fac473
--- /dev/null
+++ b/Modules/ado/plus/c/countfit.hlp
@@ -0,0 +1,86 @@
+.-
+help for ^countfit^ - 03Nov2005
+.-
+
+Compare fit of alternive count models
+-------------------------------------
+
+ ^countfit^ varlist [if] [in]^,^ [^inf^late^(^varlist2^)^ ^noc^onstant ^p^rm ^n^breg
+ ^zip^ ^zin^b ^g^enerate^(^prefix^)^ ^replace^ ^note(^string^)^
+ ^graph^export^(^filename[^, replace^]^)^ ^nog^raph ^nod^ifferences ^noprt^able
+ ^noe^stimates ^nof^it ^nodash^ ^max^count(#) ^noi^sily]
+
+Description
+-----------
+
+^countfit^ compares the fit of the Poissin, negative binomial, zero-inflated
+Poisson and zero-inflated negative binomial models, generateing a table of
+estimates, a table of differences between observed and average estimated
+probabilities for each count, a graph of these differences, and various tests
+and measures used to compare the fit of count models.
+
+Specifying the model
+--------------------
+Immediately afer the command name ^countfit^ you specify the dependent and
+independent variables as you would with ^poisson^ or the other models. For
+zero-inflated models, the ^inflate^ option is used in the same was as in the
+^zip^ and ^zinb^ commands. ^noconstant^ can be used to exclude the constant
+term.
+
+Options to select the models to fit
+-----------------------------------
+By default, ^poisson^, ^nbreg^, ^zip^ and ^zinb^ are estimated. If you
+only want some of these models, specify the modesl you want with:
+
+ ^prm^ - include ^poisson^
+ ^nbreg^ - include ^nbreg^
+ ^zip^ - include ^poisson^
+ ^zinb^ - include ^poisson^
+
+Options to label results
+------------------------
+^generate()^ is up to five letters to name the variables that are created
+ and to label the models in the output. This name is placed in front
+ of the type of model (e.g., namePRM). This is optional but will help
+ keep track of results from multiple specifications of models.
+
+^replace^ will replace variables created with the ^generate^ option if they
+ already exist.
+
+^note()^ is a label added to the graph that is saved.
+
+^graphexport()^ contains options to be sent to the ^graph export^ command to
+ export the graph that is create. For example, ^graph(mdl.emf, replace)^
+ would save the file mdl.emf and replace it if it exists. If this option
+ is not included, the graph is not saved.
+
+Options controlling what is printed
+-----------------------------------
+^noisily^ shows the output from the estimation commands called by ^countfit^.
+^nograph^ suppress graph of differences from observed counts.
+^nodifferences^ suppress table of differences from observed counts.
+^noprtable^ suppresses table of predictions for each model.
+^noestimates^ suppress table of estimated coefficients.
+^nofit^ suppress table of fit statistics and test of fit
+^nodash^ suppress dashed lines between measures of fit
+^maxcount()^ number of counts to evaluate.
+^noisily^ includes output from Stata estimation commands; without this option
+ the results are only shown in the ^estimates table^ output.
+
+Notes
+-----
+
+^countfit^ is based on the results from the Stata models described above,
+the predictions computed by ^prcounts^, and the fit measures computed by
+^fitstat^.
+
+Examples
+--------
+
+ ^. use couart2^
+ ^. countfit art fem mar kid5 phd ment, inf(ment fem) nbreg zinb nograph^
+
+.-
+Author: J. Scott Long and Jeremy Freese
+ www.indiana.edu/~jslsoc/spost.htm
+ spostsup@@indiana.edu
diff --git a/Modules/ado/plus/c/cseplist.ado b/Modules/ado/plus/c/cseplist.ado
new file mode 100644
index 0000000..6a59800
--- /dev/null
+++ b/Modules/ado/plus/c/cseplist.ado
@@ -0,0 +1,29 @@
+program def cseplist, rclass
+*! NJC 1.0.0 31 August 2000
+ version 6.0
+ gettoken list 0 : 0, parse(",")
+ if "`list'" == "" | "`list'" == "," {
+ di in r "nothing in list"
+ exit 198
+ }
+ syntax , [ Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ tokenize `list'
+ local n : word count `list'
+ local i = 1
+ while `i' < `n' {
+ local newlist "`newlist'``i'',"
+ local i = `i' + 1
+ }
+ local newlist "`newlist'``n''"
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
+
diff --git a/Modules/ado/plus/c/cseplist.hlp b/Modules/ado/plus/c/cseplist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/c/cseplist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/c/cvarlist.ado b/Modules/ado/plus/c/cvarlist.ado
new file mode 100644
index 0000000..986c1cb
--- /dev/null
+++ b/Modules/ado/plus/c/cvarlist.ado
@@ -0,0 +1,54 @@
+program def cvarlist, rclass
+*! NJC 1.0.0 18 August 2000
+ version 6.0
+ gettoken list 0 : 0, parse(",")
+ if "`list'" == "" | "`list'" == "," {
+ di in r "nothing in list"
+ exit 198
+ }
+ syntax , [ new NUmeric String Noisily Global(str)]
+
+ local nopts : word count `new' `numeric' `string'
+ if `nopts' > 1 {
+ di in r "use just one of options new, numeric, string"
+ exit 198
+ }
+
+ if "`global'" != "" {
+ tokenize `global'
+ args global1 global2 global3
+ if "`global3'" != "" {
+ di in r "global( ) must contain at most 2 names"
+ exit 198
+ }
+ if (length("`global1'") > 8) | (length("`global2'") > 8) {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+ }
+
+ tokenize `list'
+ local nwords : word count `list'
+ local i = 1
+ while `i' <= `nwords' {
+ capture confirm `new' `numeric' `string' variable ``i''
+ if _rc == 0 { local newlist "`newlist'``i'' " }
+ else local badlist "`badlist'``i'' "
+ local i = `i' + 1
+ }
+
+ if "`noisily'" != "" {
+ if "`newlist'" != "" {
+ di in g "list 1: " in y "`newlist'"
+ }
+ if "`badlist'" != "" {
+ di in g "list 2: " in y "`badlist'"
+ }
+ }
+
+ if "`global1'" != "" { global `global1' "`newlist'" }
+ if "`global2'" != "" { global `global2' "`badlist'" }
+ return local list1 `newlist'
+ return local list2 `badlist'
+end
+
diff --git a/Modules/ado/plus/c/cvarlist.hlp b/Modules/ado/plus/c/cvarlist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/c/cvarlist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/d/dellist.ado b/Modules/ado/plus/d/dellist.ado
new file mode 100644
index 0000000..96af1dd
--- /dev/null
+++ b/Modules/ado/plus/d/dellist.ado
@@ -0,0 +1,119 @@
+program def dellist, rclass
+*! NJC 1.5.0 14 December 2000
+* NJC 1.4.0 6 Sept 2000
+* NJC 1.3.0 6 June 2000
+* NJC 1.2.0 31 Jan 2000
+* NJC 1.1.0 22 Dec 1999
+* NJC 1.0.0 22 Sept 1999
+ version 6.0
+ gettoken list 0 : 0, parse(",")
+ if "`list'" == "" | "`list'" == "," {
+ di in r "nothing in list"
+ exit 198
+ }
+
+ local nlist : word count `list'
+
+ syntax , [ Delete(str) Pos(numlist sort int >=-`nlist' <=`nlist') /*
+ */ Exact All Global(str) Noisily ]
+
+ local nopts = ("`delete'" != "") + ("`pos'" != "")
+ if `nopts' != 1 {
+ di in r "must specify one of delete( ) and pos( )"
+ exit 198
+ }
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ if "`exact'" != "" & "`all'" != "" {
+ di in r "all option not allowed with exact option"
+ exit 198
+ }
+
+ tokenize `list'
+
+ if "`delete'" != "" {
+ local i = 1
+ while `i' <= `nlist' {
+ local len = length("``i''")
+ if `len' > 80 {
+ di in r "cannot handle word length > 80"
+ exit 498
+ }
+ local i = `i' + 1
+ }
+
+ tknz `delete', s(d)
+ local nd : word count `delete'
+
+ if "`exact'" != "" {
+ while "`1'" != "" {
+ local i = 1
+ local OK = 0
+ while `i' <= `nd' & !`OK' {
+ local OK = "`1'" == "`d`i''"
+ local i = `i' + 1
+ }
+ if !`OK' { local newlist "`newlist'`1' " }
+ mac shift
+ }
+ }
+ else {
+ while "`1'" != "" {
+ local i = 1
+ local OK = 0
+ while `i' <= `nd' {
+ local thisOK = /*
+ */ index("`1'", "`d`i''") > 0
+ local OK = `OK' + `thisOK'
+ local i = `i' + 1
+ }
+ if "`all'" != "" { local OK = `OK' == `nd' }
+ if !`OK' { local newlist "`newlist'`1' " }
+ mac shift
+ }
+ }
+ }
+ else {
+ local np1 = `nlist' + 1
+ tknz `pos' `np1', s(p)
+ local np : word count `pos'
+
+ * negative indexes to positive
+ local i = 1
+ while `p`i'' < 0 {
+ local p`i' = `nlist' + 1 + `p`i''
+ local i = `i' + 1
+ }
+
+ local i = 1
+ local j = 1
+ while `i' <= `nlist' {
+ if `i' == `p`j'' { local j = `j' + 1 }
+ else local newlist "`newlist'``i'' "
+ local i = `i' + 1
+ }
+ }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
+
+program def tknz, rclass
+* NJC 1.1.0 2 June 2000
+ version 6.0
+ gettoken list 0 : 0, parse(",")
+ syntax , Stub(str) [ * ]
+ tokenize `"`list'"' , `options'
+
+ local i = 1
+ while "``i''" != "" {
+ c_local `stub'`i' `"``i''"'
+ local i = `i' + 1
+ }
+end
+
diff --git a/Modules/ado/plus/d/dellist.hlp b/Modules/ado/plus/d/dellist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/d/dellist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/d/delta.ado b/Modules/ado/plus/d/delta.ado
new file mode 100644
index 0000000..5f431bf
--- /dev/null
+++ b/Modules/ado/plus/d/delta.ado
@@ -0,0 +1,108 @@
+*! Delta version 1.5 - 5 March 2008
+*! Jean-Benoit Hardouin
+************************************************************************************************************
+* DELTA: delta coefficient
+* Version 1.5: March 5, 2008
+*
+* Historic
+* Version 1 (2007-05-21): Jean-Benoit Hardouin
+* Version 1.1 (2007-05-22): Jean-Benoit Hardouin /* if in and possibility to use the score*/
+* Version 1.2 (2007-05-22): Jean-Benoit Hardouin /*bug when a score is missing*/
+* Version 1.3 (2007-06-16): Jean-Benoit Hardouin /*change in the options*/
+* Version 1.4 (2007-07-03): Jean-Benoit Hardouin /*correct a bug in the options*/
+* Version 1.5 (2008-03-05): Jean-Benoit Hardouin /*correct a bug in the ci option*/
+*
+* Jean-benoit Hardouin, Faculty of Pharmaceutical Sciences - University of Nantes - France
+* jean-benoit.hardouin@univ-nantes.fr
+*
+* News about this program : http://www.anaqol.org
+* FreeIRT Project : http://www.freeirt.org
+*
+* Copyright 2007-2008 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 delta , rclass
+version 7.0
+syntax varlist(min=1 numeric) [if] [in] [,ci(integer 0) noDots MINscore(int 0) MAXscore(int 0)]
+
+preserve
+tempfile deltafile
+qui save `deltafile'
+if "`if'"!=""|"`in'"!="" {
+ qui keep `if' `in'
+}
+
+local nbitems:word count `varlist'
+tokenize `varlist'
+
+local scoremin=`minscore'
+local scoremax=`maxscore'
+
+
+
+tempvar score
+if `nbitems'==1&`scoremax'==0 {
+ di in red "If you indicate only the score variable, you must define the {cmd:scoremax} option"
+ error 198
+}
+else if `nbitems'==1&`scoremax'!=0 {
+ qui gen `score'=`varlist'
+}
+else {
+ qui genscore `varlist',score(`score')
+}
+qui drop if `score'==.
+qui count
+local nbind=r(N)
+
+if `scoremax'==0 {
+ qui su `score'
+ local scoremax=r(max)
+}
+
+tempname error
+gen `error'=`score'<`scoremin'|`score'>`scoremax'
+qui count if `error'==1
+local err=r(N)
+if `err'!=0 {
+ di in red "`err' individuals has(have) a score inferior to `scoremin' or superior to `scoremax'"
+ error 198
+}
+
+local sumsqscore=0
+forvalues i=`scoremin'/`scoremax' {
+ qui count if `score'==`i'
+ local score`i'=r(N)
+ local sumsqscore=`sumsqscore'+`score`i''^2
+}
+local delta=(1+`scoremax')*(`nbind'^2-`sumsqscore')/(`nbind'^2*`scoremax')
+
+di in green "Range of the scores : " in ye `scoremin' in gr "/" in ye `scoremax'
+di in green "Number of used individuals : " in ye `nbind'
+
+if `ci'!=0 {
+ bootstrap delta=r(delta), reps(`ci') nowarn noheader nolegend `dots': delta `varlist' ,minscore(`scoremin') maxscore(`scoremax')
+}
+else {
+ display in green "Delta= " in yellow %8.6f `delta'
+}
+return scalar delta=`delta'
+qui use `deltafile',clear
+restore,not
+
+end
diff --git a/Modules/ado/plus/d/delta.hlp b/Modules/ado/plus/d/delta.hlp
new file mode 100644
index 0000000..511bcab
--- /dev/null
+++ b/Modules/ado/plus/d/delta.hlp
@@ -0,0 +1,61 @@
+{smcl}
+{* 16may2007}{...}
+{hline}
+help for {hi:delta}{right:Jean-Benoit Hardouin}
+{hline}
+
+{title:Syntax}
+
+{p 8 14 2}{cmd:delta} {it:varlist} [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [, {cmdab:ci}({it:#}) {cmdab:nod:ots} {cmdab:min:score}({it:#}) {cmdab:max:score}({it:#})]
+
+{title:Description}
+
+{p 4 8 2}{cmd:delta} computes the generalized delta index of scale discrimination developed by Hankins (2007) based on the original work of Ferguson (1949). This index measures the scale's ability to distinguish between individuals.
+A value of 1 indicates that the test has maximal discrimination (all possible scores occur with the same frequency) and a value of 0 means that the test has minimal discrimination (all the respondents have the same score).
+A value of 0.9 results from a set of scores that is normally distributed. A value of 1 is observed if the scores follow a uniform distribution. Individuals with a missing score are omitted.
+
+{title:Options}
+
+{p 4 8 2}If {it:varlist} is composed of only one variable, the {cmd:delta} module considers that this variable is the score of the individuals.
+
+{p 4 8 2}{cmd:ci}({it:#}) estimates the confidence interval by boostrap. {it:#} is the number of replications to be performed. By default, no confidence interval is calculated.
+
+{p 4 8 2}{cmd:nodots} avoids displaying a dot for each replication (only with {cmd:ci}).
+
+{p 4 8 2}{cmd:minscore}({it:#}) defines the minimal value of the score. By default, this value is fixed to 0.
+
+{p 4 8 2}{cmd:maxscore}({it:#}) defines the maximal value of the score. By default, the maximal observed score is used.
+
+{title:Output}
+
+{p 4 8 2}{cmd:r(delta)}: Observed value of the delta index.
+
+{title:Examples}
+
+{p 4 8 2}{cmd: . delta itemA*}
+
+{p 4 8 2}{cmd: . delta itemA*, ci(500) dots}
+
+{p 4 8 2}{cmd: . delta score, scoremax(8)}
+
+{title: References}
+
+{p 4 8 2}Ferguson G. A. (1949) On the theory of test discrimination. {it:Psychometrika}, 14: 61-68.
+
+{p 4 8 2}Hankins M. (2007) Questionnaire discrimination: (re)- introducting coefficient delta. {it:BMC Medical Research Methodology}, 7: 19.
+
+{title:Author}
+
+{p 4 8 2}Jean-Benoit Hardouin, PhD, assistant professor{p_end}
+{p 4 8 2}Team of Biostatistics, Clinical Research and Subjective Measures in Health Sciences{p_end}
+{p 4 8 2}University of Nantes - Faculty of Pharmaceutical Sciences{p_end}
+{p 4 8 2}1, rue Gaston Veil - BP 53508{p_end}
+{p 4 8 2}44035 Nantes Cedex 1 - FRANCE{p_end}
+{p 4 8 2}Email:
+{browse "mailto:jean-benoit.hardouin@univ-nantes.fr":jean-benoit.hardouin@univ-nantes.fr}{p_end}
+{p 4 8 2}Websites {browse "http://www.anaqol.org":AnaQol}
+and {browse "http://www.freeirt.org":FreeIRT}
+
+{title:Also see}
+
+{p 4 13 2}Online: help for {help alpha} and {help loevH} if installed.{p_end}
diff --git a/Modules/ado/plus/d/difflist.ado b/Modules/ado/plus/d/difflist.ado
new file mode 100644
index 0000000..b3f98e9
--- /dev/null
+++ b/Modules/ado/plus/d/difflist.ado
@@ -0,0 +1,90 @@
+program def difflist, rclass
+*! NJC 1.4.0 6 June 2000
+* NJC 1.3.0 31 Jan 2000
+* NJC 1.2.0 22 Dec 1999
+* NJC 1.1.0 21 Dec 1999
+* NJC 1.0.0 14 Oct 1999
+ version 6.0
+ gettoken lists 0 : 0, parse(",")
+ if "`lists'" == "" | "`lists'" == "," { /* no \ */
+ di in r "incorrect syntax: no separator"
+ exit 198
+ }
+
+ tokenize "`lists'", parse("\")
+ if "`4'" != "" {
+ di in r "incorrect syntax: too much stuff"
+ exit 198
+ }
+ if "`1'" == "\" { /* list1 empty */
+ if "`2'" == "\" {
+ di in r "incorrect syntax: one \ only"
+ exit 198
+ }
+ local list2 "`2'" /* might be empty */
+ }
+ else if "`2'" == "\" {
+ local list1 "`1'"
+ local list2 "`3'" /* might be empty */
+ }
+ else {
+ di in r "incorrect syntax: what to compare?"
+ exit 198
+ }
+
+ syntax [ , Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ * remove duplicates from `list1'
+
+ tokenize `list1'
+ local list1 "`1'"
+ mac shift
+
+ while "`1'" != "" {
+ local n1 : word count `list1'
+ local i = 1
+ local putin = 1
+ while `i' <= `n1' {
+ local word : word `i' of `list1'
+ if "`word'" == "`1'" {
+ local putin = 0
+ local i = `n1'
+ }
+ local i = `i' + 1
+ }
+ if `putin' { local list1 "`list1' `1'" }
+ mac shift
+ }
+
+ * what is in `list1' but not `list2'?
+
+ local n1 : word count `list1'
+ tokenize `list1'
+ local n2 : word count `list2'
+
+ local i = 1
+ while `i' <= `n1' {
+ local j = 1
+ local putin = 1
+ while `j' <= `n2' {
+ local word : word `j' of `list2'
+ if "`word'" == "``i''" {
+ local putin = 0
+ local j = `n2'
+ }
+ local j = `j' + 1
+ }
+ if `putin' { local newlist "`newlist' ``i''" }
+ local i = `i' + 1
+ }
+
+ if "`noisily'" != "" { di "`newlist'" }
+ if "`global'" != "" { global `global' "`newlist'" }
+ return local list `newlist'
+end
+
diff --git a/Modules/ado/plus/d/difflist.hlp b/Modules/ado/plus/d/difflist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/d/difflist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/d/discrim2.ado b/Modules/ado/plus/d/discrim2.ado
new file mode 100644
index 0000000..391a519
--- /dev/null
+++ b/Modules/ado/plus/d/discrim2.ado
@@ -0,0 +1,269 @@
+*! version 2.0 : Oct1995 : Joseph Hilbe
+* Dichotomous Discriminate Anaylsis
+* Based on version 1, written by Hilbe 12-7-91, published: STB-5 (Jan1992)
+
+program define discrim2
+ version 5.0
+ local varlist "req ex"
+ local options "Detail Graph Anova Predict Keep"
+ local in "opt"
+ local if "opt"
+ parse "`*'"
+ parse "`varlist'",parse(" ")
+ qui summ `1'
+
+ if (_result(6)<0 | _result(6)>1) {
+ noi di in red "Error: Group variable must be 0/1"
+ exit
+ }
+ if "`keep'"=="" {
+ preserve
+ }
+ qui {
+ dropmiss `varlist'
+ tempvar prob0 prob1 dummy D nvar obs obs1 obs0 c0 c1 prop D cntall
+ gen `cntall'=_n
+ local group `1'
+ local y "`1'"
+ mac shift
+ qui count
+ gen `obs' = _result(1)
+ count if `group'==0
+ gen `obs0'= _result(1)
+ count if `group'==1
+ gen `obs1'= _result(1)
+ tempvar c0
+ gen `c0' =`obs1'/`obs'
+ gen `c1' = -(`obs0'/`obs')
+ gen `prob0' = `obs1'/`obs'
+ gen `dummy' = `c0' if `group'==0
+ replace `dummy' = `c1' if `group'==1
+ reg `dummy' `*', noheader
+ global nvar = _result(3)
+ cap drop `dummy' `c0' `c1'
+ global rsquare = _result(7)
+ global mahala=($rsquare/(1-$rsquare))*((`obs'*(`obs'-2))/(`obs0'*`obs1'))
+ gen `prop' = $rsquare/$mahala
+ gen `D' = sqrt($mahala)
+
+* Calc discriminant scores
+ local i = 1
+ while "``i''"!= "" {
+ tempvar cof`i' dis`i'
+ gen `cof`i'' = _b[``i'']
+ gen `dis`i'' = `cof`i''/`prop'
+ local i = `i'+1
+ }
+
+* Calc main values */
+ local j = 1
+ local i = 1
+ tempvar konst usdfk dscorep dscore dsFp dfun
+ gen `usdfk'=0
+ gen `konst' = 0
+ gen `dscorep'=0
+ gen `dscore'=0
+ gen `dsFp'=0
+ gen `dfun'=0
+ while "``i''"!="" {
+ tempvar mean`j' mn0`j' mn1`j' mndff`j' usdf`j'
+ summ ``i''
+ gen `mean`j'' = _result(3)
+ summ ``i'' if `group'==0
+ gen `mn0`j'' = _result(3)
+ summ ``i'' if `group'==1
+ gen `mn1`j'' = _result(3)
+ gen `mndff`j'' = `mn0`j'' + `mn1`j''
+ replace `konst' = `dis`i''*`mndff`j''+`konst'
+ gen `usdf`i''=`dis`i''/-`D'
+ replace `usdfk'=`usdf`j'' * `mean`j'' + `usdfk'
+ replace `dscorep'=`usdf`i''*``i''
+ replace `dscore'=`dscore'+`dscorep'
+ replace `dsFp'=`dis`i''*``i''
+ replace `dfun'=`dfun'+`dsFp'
+ local i = `i'+1
+ local j = `j'+1
+ }
+ replace `usdfk'=`usdfk'* -1
+ replace `dscore'=`dscore'+`usdfk'
+ replace `konst'=`konst'*-.5
+ replace `dfun' = `dfun'+`konst'
+ local tsquare = $mahala*((`obs0'*`obs1')/`obs')
+ local F = `tsquare'*(`obs'-$nvar)/(($nvar-1)*(`obs'-2))
+ global cnt0 = -`D'*(`obs1'/`obs')
+ global cnt1 = `D'*(`obs0'/`obs')
+ noi di _n
+ noi di in gr _col(20) "Dichotomous Discriminant Analysis"
+ noi di " "
+ #delimit ;
+ noi di in gr "Observations = " in ye `obs'
+ in gr _col(50) "Obs Group 0 = " in ye %9.0g `obs0';
+ noi di in gr "Indep variables = " in ye $nvar
+ in gr _col(50) "Obs Group 1 = " in ye %9.0g `obs1';
+ noi di " ";
+ noi di in gr "Centroid 0 = " in ye %9.4f $cnt0
+ in gr _col(50) "R-square = " in ye %9.4f $rsquare;
+ noi di in gr "Centroid 1 = " in ye %9.4f $cnt1
+ in gr _col(50) "Mahalanobis = " in ye %9.4f $mahala;
+ noi di in gr "Grand Cntd = " in ye %9.4f
+ ((`obs1'*$cnt0)+(`obs0'*$cnt1))/`obs';
+ noi di " ";
+ #delimit cr
+ oneway `dscore' `group'
+ global eigen = _result(2)/_result(4)
+ global ccor = sqrt(_result(2)/(_result(2)+_result(4)))
+ global lambda = _result(4)/(_result(2)+_result(4))
+ global chisq = log($lambda)* -((`obs'-($nvar+2)/2)-1)
+ #delimit ;
+ noi di in gr "Eigenvalue = " in ye %9.4f $eigen
+ in gr _col(50) "Wilk's Lambda = " in ye %7.4f $lambda;
+ noi di in gr "Canon. Corr. = " in ye %9.4f $ccor
+ in gr _col(50) "Chi-square = " in ye %7.4f $chisq;
+ noi di in gr "Eta Squared = " in ye %9.4f $ccor^2
+ in gr _col(50) "Sign Chi2 = " in ye %7.4f chiprob($nvar,$chisq);
+ #delimit cr
+
+* DISPLAY COEFFICIENTS
+ noi di _n(1)
+ noi di in gr _col(26) "Discrim Function" _col(46) "Unstandardized"
+ noi di in gr _col(11) /*
+ */ "Variable" _col(28) "Coefficients" _col(48) "Coefficients"
+ noi di in gr _col(11) _dup(49) "-"
+ local i=1
+ while "``i''"!="" {
+ noi di in gr _col(11) "``i''" in ye _col(28) %9.4f `dis`i'' /*
+ */ _col(51) %9.4f `usdf`i''
+ local i = `i'+1
+ }
+ noi di in gr _col(11) "constant" in ye _col(28) %9.4f `konst' /*
+ */ _col(51) %9.4f `usdfk'
+
+ tempvar lprob grpred cell
+ gen `lprob' = 1/(1+exp(`dfun'))
+ gen `grpred' = 1 if `lprob'>=0.5
+ replace `grpred' = 0 if `lprob'<0.5
+ gen `cell' = 1
+ summ `cell' if `group'==0 & `lprob'<0.5
+ local aa=_result(2)
+ summ `cell' if `group'==0 & `lprob'>=0.5
+ local bb=_result(2)
+ summ `cell' if `group'==1 & `lprob'<0.5
+ local cc=_result(2)
+ summ `cell' if `group'==1 & `lprob'>=0.5
+ local dd=_result(2)
+ local tot = `aa'+`bb'+`cc'+`dd'
+
+* CONFUSION MATRIX AND RELATED STATS OPTION
+if "`predict'" !="" {
+ noi di _n " "
+ noi di in gr _col(25) "----- Predicted -----"
+ noi di in gr _col(13) "Actual | Group 0 Group 1 | Total"
+ noi di in gr _col(13) "---------+" _dup(26) "-" "+--------"
+ noi di in gr _col(13) "Group 0 |" in ye _col(26) %6.0g `aa' /*
+ */ _col(40) %6.0g `bb' in gr _col(49) "|" in ye _col(52) %6.0g `aa'+`bb'
+ noi di in gr _col(13) "Group 1 |" in ye _col(26) %6.0g `cc' /*
+ */ _col(40) %6.0g `dd' in gr _col(49) "|" in ye _col(52) %6.0g `cc'+`dd'
+ noi di in gr _col(13) "---------+" _dup(26) "-" "+--------"
+ noi di in gr _col(13) "Total |" in ye _col(26) %6.0g `aa'+`cc' /*
+ */ _col(40) %6.0g `bb'+`dd' in gr _col(49) "|" in ye _col(52) /*
+ */ %6.0g `tot'
+ noi di in gr _col(13) "---------+" _dup(26) "-" "+--------"
+ noi di " "
+ noi di in gr _col(21) "Correctly predicted = " in ye /*
+ */ %6.2f ((`aa'+`dd')/`tot')*100 " %"
+ noi di in gr _col(21) "Model sensitivity = " in ye /*
+ */ %6.2f (`aa'/(`aa'+`bb'))*100 " %"
+ noi di in gr _col(21) "Model specificity = " in ye /*
+ */ %6.2f (`dd'/(`cc'+`dd'))*100 " %"
+ noi di in gr _col(21) "False positive = " in ye /*
+ */ %6.2f (`cc'/(`aa'+`cc'))*100 " %"
+ noi di in gr _col(21) "False negative = " in ye /*
+ */ %6.2f (`bb'/(`bb'+`dd'))*100 " %"
+}
+
+* ANOVA OPTION
+ if "`anova'"!="" {
+ noi di _n(1)
+ noi di in gr _col(18) "Discriminant Scores v Group Variable"
+ noi oneway `dscore' `group'
+ }
+
+* GRAPH OPTION
+ if "`graph'"!="" {
+ tempvar lnp lnm
+ gen `lnp'=`lprob' if (`lprob'>=0.5 & `group'==1) | /*
+ */ (`lprob'<0.5 & `group'==0)
+ gen `lnm'=`lprob' if `lnp'==.
+ lab var `lnp' "Classified"
+ lab var `lnm' "Misclassified"
+ lab var `dfun' "Discriminant Index"
+ noi gr `lnp' `lnm' `dfun', s(.p) xlab ylab(.1,.3,.4,.5,.6,.7,.9) /*
+ */ border yline(.5) ti(" Probability of Classification")
+ cap drop `lnp' `lnm'
+ }
+
+* INDIVIDUAL CLASSIFICATION STATISTICS OPTION: SAVES WITH SAVE OPTION
+ if "`detail'"!="" {
+ cap drop PRED DscScore DscIndex LnProb1 Group DIFF
+ sort `cntall'
+ noi di _n(2)
+ gen PRED=`grpred'
+ gen DscScore = `dscore'
+ gen DscIndex = `dfun'
+ gen LnProb1 = `lprob'
+ gen Group = `group'
+ compress Group PRED
+ gen str2 DIFF = " *" if `group'!=PRED
+ format DIFF %2s
+ format DscIndex DscScore LnProb1 %9.4f
+ noi di in gr " PRED = Predicted Group DIFF = Misclassification"
+ noi di in gr " LnProb1 = Probability Gr 1 DscScore = Discriminant Score"
+ noi di in gr " DscIndex = Discriminant Index"
+ noi di in gr _dup(63) "-"
+ di " "
+ noi l `y' PRED DIFF LnProb1 DscIndex DscScore, nol
+ }
+
+global S_E_var $nvar
+global S_E_obs `obs'
+global S_E_ob0 `obs0'
+global S_E_ob1 `obs1'
+global S_E_cn0 $cnt0
+global S_E_cn1 $cnt1
+global S_E_cng ((`obs1'*$cnt0)+(`obs0'*$cnt1))/`obs'
+global S_E_r2 $rsquare
+global S_E_mah $mahala
+global S_E_eig $eigen
+global S_E_lam $lamda
+global S_E_cc $ccor
+global S_E_chi $chisq
+global S_E_e2 $ccor^2
+global S_E_cmd "discrim"
+
+}
+
+if "`keep'"!="" {
+ noi di _n in bl " Caution: data changed in memory"
+ }
+if "`keep'"=="" {
+ restore
+}
+
+end
+
+
+
+* DROP MISSING VALUES
+ capture program drop dropmiss
+ program define dropmiss
+ local varlist "req ex"
+ parse "`*'"
+ parse "`varlist'", parse(" ")
+ local i= 1
+ while "``i''"!="" {
+ drop if ``i''==.
+ local i=`i'+1
+ }
+end
+
+
diff --git a/Modules/ado/plus/d/discrim2.hlp b/Modules/ado/plus/d/discrim2.hlp
new file mode 100644
index 0000000..1aee917
--- /dev/null
+++ b/Modules/ado/plus/d/discrim2.hlp
@@ -0,0 +1,77 @@
+.-
+help for ^discrim^ (STB-x)
+.-
+
+Dichotomous Discriminant Analysis
+---------------------------------
+
+ ^discrim^ grpvar [varlist] [^, p^redict^ a^nova^ g^raph^ d^etail^ k^eep]
+
+Description
+-----------
+^discrim^ allows the user to perform a discriminant analysis on a Bernoulli
+distributed response of grouping variable (1/0).
+
+Output includes table with the following statistics and their global
+designation for post-estimation use when applicable:
+
+ 1. Observations [S_E_obs] 2. Independent vars [S_E_var]
+ 3. Obs: group==0 [S_E_ob0] 4. Obs: group==1 [S_E_ob1]
+ 5. Centroid 0 [S_E_cn0] 6. Centroid 1 [S_E_cn1]
+ 7. Grand centroid [S_E_cng] 8. R-square [S_E_r2]
+ 9. Mahalanobis [S_E_mah] 10. Eigenvalue [S_E_eig]
+ 11. Canon. Correl [S_E_cc] 12. Eta squared [S_E_e2]
+ 13. Wilk's lambda [S_E_lam] 14. Chi-square [S_E_chi]
+
+Output also includes a table displaying both the Discriminant Function and
+Unstandardized Coefficients.
+
+Cases in which a variable has a missing value are dropped from estimation.
+The ^keep^ command does not restore such cases to active memory.
+
+Options
+-------
+^predict^ provides a confusion matrix of actual vs predicted group cell
+ counts. Also included is a listing of the following percentages:
+ 1. Correctly predicted 2. Model sensitivity
+ 3. Model specificity 4. False Positive
+ 5. False Negative
+
+^anova^ provides an ANOVA of discriminant scores vs the group variable.
+ Bartlett's test for equal variances in included.
+
+^graph^ provides a classification graph showing correctly and incorrectly
+ classified cases.
+
+^detail^ creates and lists the following for each retained case:
+ 1. Group : actual group value
+ 2. PRED : predicted group value
+ 3. DIFF : a star indicating misclassified cases
+ 4. LnProb1 : logistic probability of grouyp 1 membership
+ 5. DscIndex : discriminant index
+ 6. DscScore : discriminant score
+
+^keep^ allows the user to keep the variables created in the Detail option.
+ The data set in memory is altered, so care must be taken when saving the
+ resultant file to disk.
+
+Examples
+--------
+ . ^discrim foreign price mpg length^
+
+ . ^discrim foreign price mpg length, p a gr d^
+
+ . ^discrim foreign price mpg length, detail keep^
+
+Also see
+--------
+STB-5 (Jan1992): smv3 - Hilbe, "Regression based dichotomous discriminant
+ analysis".
+Selvin, Steve (1995, 1996) "Practical Biostatistical Methods", Chap 6.
+ Explanation and use of the 1st version of the ^discrim^ command.
+
+Additional help
+---------------
+Joseph Hilbe, Dept of Sociology, Arizona State University
+Email: atjmh@@asuvm.inre.asu.edu
+
diff --git a/Modules/ado/plus/d/dropvars.ado b/Modules/ado/plus/d/dropvars.ado
new file mode 100644
index 0000000..7fc2f42
--- /dev/null
+++ b/Modules/ado/plus/d/dropvars.ado
@@ -0,0 +1,15 @@
+*! 1.0.1 14mar2000 jw/ics
+program define dropvars
+ version 6
+
+ while "`1'" != "" {
+ capture drop `1'
+ if _rc {
+ local nodropv "`nodropv' `1'"
+ }
+ mac shift
+ }
+ if "`nodropv'" != "" {
+ di in gr "Unable to drop" in ye "`nodropv'"
+ }
+end
diff --git a/Modules/ado/plus/d/dropvars.hlp b/Modules/ado/plus/d/dropvars.hlp
new file mode 100644
index 0000000..9b15a80
--- /dev/null
+++ b/Modules/ado/plus/d/dropvars.hlp
@@ -0,0 +1,35 @@
+.-
+help for ^dropvars^ [jw] Mar 14, 2000
+.-
+
+Drop variables
+--------------
+
+ ^dropvars^ list
+
+
+Description
+-----------
+
+^dropvars^ drops the variables that match the varlist specifications in list.
+In contrast with ^drop^, ^dropvars^ allows terms in list that do not match
+any variables; ^drop^ complain if any variable does not exist, and then
+drops nothing.
+
+^dropvars list^ is equivalent to
+
+ ^for any list : capture drop X^
+
+
+Example
+-------
+
+ . ^dropvars a* b*^
+ drop all variables that start with either a or b.
+
+
+Also see
+--------
+
+ Manual: ^[R] drop^
+On-line: help for @drop@
diff --git a/Modules/ado/plus/e/elapse.ado b/Modules/ado/plus/e/elapse.ado
new file mode 100644
index 0000000..1153bb9
--- /dev/null
+++ b/Modules/ado/plus/e/elapse.ado
@@ -0,0 +1,81 @@
+
+/* elapse.ado 10/24/97 */
+
+program define elapse /* start_time name_of_operation (optional)*/
+
+ version 5.0
+ local hdiff = real(substr("$S_TIME",1,2)) - real(substr("`1'",1,2))
+ local mdiff = real(substr("$S_TIME",4,2)) - real(substr("`1'",4,2))
+ local sdiff = real(substr("$S_TIME",7,2)) - real(substr("`1'",7,2))
+ if `sdiff' < 0 {
+ local sdiff = `sdiff' + 60
+ local mdiff = `mdiff' -1
+ }
+ if `mdiff' < 0 {
+ local mdiff = `mdiff' + 60
+ local hdiff = `hdiff' -1
+ }
+ if `hdiff' < 0 {
+ local hdiff = `hdiff' + 24
+ }
+ local selap = 10000 * `hdiff' + 100 * `mdiff' + `sdiff'
+ global S_elap = `selap'
+
+ local hdiff = string(`hdiff')
+ local mdiff = string(`mdiff')
+ local sdiff = string(`sdiff')
+
+ if "`2'" == "" {
+ if `hdiff' > 0 {
+ di in ye "Elapsed time was " in wh "`hdiff'" _c
+ if `hdiff' > 1 {di in ye " hours, " _c}
+ else { di in ye " hour, " _c}
+ di in wh "`mdiff'" _c
+ if `mdiff' > 1 {di in ye " minutes, " _c}
+ else {di in ye " minute, " _c}
+ di in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ else if `mdiff' > 0 {
+ di in ye "Elapsed time was " in wh "`mdiff'" _c
+ if `mdiff' > 1 {di in ye " minutes, " _c}
+ else {di in ye " minute, " _c}
+ di in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ else {
+ di in ye "Elapsed time was " in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ }
+ else {
+ if `hdiff' > 0 {
+ di in ye "`2' took " in wh "`hdiff'" _c
+ if `hdiff' > 1 {di in ye " hours, " _c}
+ else { di in ye " hour, " _c}
+ di in wh "`mdiff'" _c
+ if `mdiff' > 1 {di in ye " minutes, " _c}
+ else {di in ye " minute, " _c}
+ di in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ else if `mdiff' > 0 {
+ di in ye "`2' took " in wh "`mdiff'" _c
+ if `mdiff' > 1 {di in ye " minutes, " _c}
+ else {di in ye " minute, " _c}
+ di in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ else {
+ di in ye "`2' took " in wh "`sdiff'" _c
+ if `sdiff' > 1 {di in ye " seconds."}
+ else {di in ye " second."}
+ }
+ }
+
+end
diff --git a/Modules/ado/plus/e/elapse.hlp b/Modules/ado/plus/e/elapse.hlp
new file mode 100644
index 0000000..d07ec9a
--- /dev/null
+++ b/Modules/ado/plus/e/elapse.hlp
@@ -0,0 +1,68 @@
+..-
+help for ^elapse^
+..-
+
+Timing portions of a program
+- ----------------------------
+
+ ^elapse^ start_time [name_of_operation]
+
+
+Where start_time is a previously defined macro equal to
+the global system macro S_TIME at some earlier point, and
+name_of_operation is a string.
+
+
+Description
+- -----------
+
+^Elapse^ displays a string with the name of the operation,
+if specified, and the time elapsed between start_time and
+current time.
+
+
+
+Options
+- -------
+
+name_of_operation is a user-defined string.
+
+
+Remarks
+- -------
+
+^Elapse^ automates the procedure of timing a piece of code
+or an entire program. It is accurate over midnight, but not
+over several days. It also creates a global S_elap, which is
+a numerical macro of the form hhmmss, where hh is the number
+of hours, mm the number of minutes, and ss the number of seconds.
+
+
+Examples
+- --------
+
+ ^local st = "$S_TIME"^
+ ^...^
+ ^local oper "Maximum likelihood estimation"^
+ ^elapse "`st'" "`oper'"^
+ - Maximum likelihood estimation took 7 minutes, 15 seconds.
+
+ ^elapse `st'^
+ - Elapsed time was 1 hour, 10 minutes, 32 seconds.
+
+ ^quietly elapse `st'^
+ ^if $S_elap > 4500 { mat xx = startxx }^
+
+
+Saved Results
+- -------------
+
+S_elap (see above).
+
+
+Author
+- ------
+
+ Frederic Zimmerman
+ Food Research Institute
+ Stanford University
diff --git a/Modules/ado/plus/e/eq_g.hlp b/Modules/ado/plus/e/eq_g.hlp
new file mode 100644
index 0000000..dd55366
--- /dev/null
+++ b/Modules/ado/plus/e/eq_g.hlp
@@ -0,0 +1,81 @@
+.-
+help for ^eq^
+.-
+
+Define and list equations
+-------------------------
+
+ ^eq^ [^define^] eqtn
+ ^eq^ [^define^] eqname ^:^ [eqtn]
+
+ ^eq dir^ [^_all^ | eqname [eqname ..]]
+ ^eq list^ [^_all^ | eqname [eqname ..]]
+
+ ^eq drop^ {^_all^ | eqname [eqname ..]}
+
+
+Description
+-----------
+
+^eq define^ is used to define equations in ^gllamm^. In Stata 5 and earlier this
+was also used by Stata's own multivariate estimation commands. The command
+continues to work in Stata 8 but is no longer documented.
+
+^eq dir^ and ^eq list^ are used to review equations that
+have been defined. ^eq drop^ is used to eliminate previously defined equations.
+
+^gllamm^ has options ^eqs(eqnames)^ ^geqs(eqnames)^ ^peqs(eqname)^ and ^s(eqname)^
+where eqnames is a list of equation names and eqname is an equation name.
+You first define equations using ^eq^ and then estimate the model.
+
+Equations are named and usually define a variable list. For instance,
+to estimate a factor model in ^gllamm^, an equation of the following
+kind must be defined:
+
+ . ^eq load: d1 d2 d3^
+
+where d1, d2 and d3 are dummy variables for three variables or items
+loading on one of the factors. You can abbreviate variable names and
+take all the other shortcuts you would when specifying a varlist in a
+command:
+
+ . ^eq load: d1-d3^
+
+When you do not specify the equation name followed by a colon, the first name
+is taken both as the equation name and as part of the contents of the equation.
+
+There is one exception to this rule. You may not type
+
+ . ^eq price^
+
+You must type instead
+
+ . ^eq price: price^
+
+(Such nearly empty equations are not silly; it could mean that price is to
+be estimated by an intercept-only equation.) One can also define completely
+empty equations in this way:
+
+ . ^eq price: ^
+
+Note the distinction: "^eq price: price^" defines equation price to contain
+"price"; "^eq price:^" defines price to contain nothing.
+
+Equations can be dropped,
+
+ . ^eq drop load^
+ . ^eq load: d1 d2 d3^
+
+or you can redefine equations without bothering to drop them first.
+
+Equations may be listed for review:
+
+ . ^eq list load^
+ . ^eq list load1 load2^
+ . ^eq list^
+
+You can list just the equation names using ^eq dir^:
+
+ . ^eq dir^
+
+
diff --git a/Modules/ado/plus/e/eqlist.ado b/Modules/ado/plus/e/eqlist.ado
new file mode 100644
index 0000000..8fc2b09
--- /dev/null
+++ b/Modules/ado/plus/e/eqlist.ado
@@ -0,0 +1,64 @@
+program def eqlist, rclass
+*! NJC 1.1.0 23 January 2001
+* NJC 1.0.0 5 January 2001
+ version 6.0
+ gettoken lists 0 : 0, parse(",")
+ if "`lists'" == "" | "`lists'" == "," { /* no \ */
+ di in r "incorrect syntax: no separator"
+ exit 198
+ }
+
+ tokenize "`lists'", parse("\")
+ if "`4'" != "" {
+ di in r "incorrect syntax: too much stuff"
+ exit 198
+ }
+ if "`1'" == "\" { /* list1 empty */
+ if "`2'" == "\" {
+ di in r "incorrect syntax: one \ only"
+ exit 198
+ }
+ local list2 "`2'" /* might be empty */
+ }
+ else if "`2'" == "\" {
+ local list1 "`1'"
+ local list2 "`3'" /* might be empty */
+ }
+ else {
+ di in r "incorrect syntax: what to compare?"
+ exit 198
+ }
+
+ syntax [ , Global(str) Noisily ]
+
+ if length("`global'") > 8 {
+ di in r "global name must be <=8 characters"
+ exit 198
+ }
+
+ local n1 : word count `list1'
+ tokenize `list1'
+ local n2 : word count `list2'
+
+ if `n1' != `n2' {
+ local iseq = 0
+ }
+ else {
+ local iseq = 1
+ local i = 1
+ while `i' <= `n1' & `iseq' {
+ local word : word `i' of `list2'
+ if length("``i''") > 80 | length("`word'") > 80 {
+ di in r "cannot handle word length > 80"
+ exit 498
+ }
+ if "`word'" != "``i''" { local iseq 0 }
+ local i = `i' + 1
+ }
+ }
+
+ if "`noisily'" != "" { di `iseq' }
+ if "`global'" != "" { global `global' = `iseq' }
+ return local iseq = `iseq'
+end
+
diff --git a/Modules/ado/plus/e/eqlist.hlp b/Modules/ado/plus/e/eqlist.hlp
new file mode 100644
index 0000000..eacf780
--- /dev/null
+++ b/Modules/ado/plus/e/eqlist.hlp
@@ -0,0 +1,2 @@
+.h listutil
+
diff --git a/Modules/ado/plus/e/espoisson.ado b/Modules/ado/plus/e/espoisson.ado
new file mode 100644
index 0000000..731377b
--- /dev/null
+++ b/Modules/ado/plus/e/espoisson.ado
@@ -0,0 +1,128 @@
+*! version 1.0 Alfonso Miranda-Caso-Luengo, November 26 2002 (SJ4-1: st0057)
+*! FIML endogenous-switch Poisson Regression
+
+program define espoisson, eclass
+ version 6
+ if replay() {
+ if "`e(cmd)'" != "espoisson" { error 301 }
+ else espDisplay `0'
+ }
+ else espEstimate `0'
+end
+
+program define espEstimate, eclass
+ syntax varlist [if] [in] , EDummy(varname) /*
+ */ [Switch(varlist) Quadrature(integer 6) /*
+ */ SIGMA0(real 1) RHO0(real 0.1) /*
+ */ EXS *]
+
+ /* Obtaining dependent variable and explanatory variables */
+
+ gettoken endgv exogv : varlist, parse("")
+
+ /* Selecting sample */
+
+ marksample touse
+ markout `touse' `varlist'
+
+ /* defining some globals */
+
+ global S_quad "`quadrature'"
+ global S_edum "`edummy'"
+
+
+ /* Diverting to exsp if EXS option active */
+
+ if "`exs'"!="" {
+ #delimit ;
+ exspoisson `endgv' `exogv' `if' `in', edummy(`edummy')
+ s(`switch') q(`quadrature')
+ sigma0(`sigma0') ;
+ #delimit cr
+ exit
+ }
+
+ /* Get points and weights for Gaussian-Hermite quadrature. */
+
+ tempvar x w
+ qui gen double `x' = 0
+ qui gen double `w' = 0
+ ghquad `x' `w', n(`quadrature')
+ local j = `quadrature'
+ while `j' >0 {
+ scalar x`j' = `x'[`j']
+ local j = `j' -1
+ }
+ local j = `quadrature'
+ while `j' >0 {
+ scalar w`j' = `w'[`j']
+ local j = `j' - 1
+ }
+
+
+ /* GETTING INITIAL VALUES */
+
+ di _skip(3)
+ qui probit `edummy' `switch' if `touse'
+
+ tempname b b1 b2 ch cr b0 bi
+
+ mat `b'=e(b)
+ xcolnames `b', head(switch)
+
+ di as txt "Getting Initial Values:"
+ qui poisson `endgv' `exogv' if `touse'
+
+ mat `b1' = e(b)
+ mat `b2' = (`b1',`b')
+ matrix `ch' = ln(`sigma0')
+ matrix colnames `ch' = lnsigma:_cons
+ matrix `cr' = `rho0'
+ matrix colnames `cr' = rho:_cons
+ matrix `b0' = (`b2',`ch',`cr')
+
+ ml model d0 espoisson_ll ("`endgv'": `endgv' = `exogv') /*
+ */ (switch:`switch')(lnsigma:)(rho:) /*
+ */ if `touse', init(`b0')
+
+ qui ml search rho: 14 -14
+ mat `cr' = ML_b[1,"rho:_cons"]
+ mat `bi' = (`b2',`ch',`cr')
+
+ /* FITTING FULL MODEL */
+
+ di _skip(3)
+ di in gr "Fitting Full model:"
+
+ ml model d0 espoisson_ll ("`endgv'": `endgv' = `exogv') /*
+ */ (switch:`switch')(lnsigma:)(rho:)/*
+ */ if `touse', init(`bi', skip) max `options' search(off)
+
+ estimates local cmd "espoisson"
+ estimates local edummy "`edummy'"
+ est local predict "espoisson_p"
+ est local quad "`quadrature'"
+
+ /* Display Results */
+
+ espDisplay
+end
+
+
+program define espDisplay
+
+ di _skip(12)
+ di _n as txt /*
+ */ "Endogenous-Switch Poisson Regression"
+ di as text "(`e(quad)' quadrature points)"
+
+ ml di, neq(2)plus
+ _diparm lnsigma, exp pr label("sigma")
+ _diparm rho, f((exp(2*@)-1)/(exp(2*@)+1)) /*
+ */ d(4*exp(2*@)/(exp(2*@)+1)^2) label("rho") pr
+ di in gre in smcl "{hline 13}{c BT}{hline 64}"
+end
+
+
+
+
diff --git a/Modules/ado/plus/e/espoisson.hlp b/Modules/ado/plus/e/espoisson.hlp
new file mode 100644
index 0000000..b59ee3d
--- /dev/null
+++ b/Modules/ado/plus/e/espoisson.hlp
@@ -0,0 +1,84 @@
+{smcl}
+{hline}
+help for {hi:espoisson} {right:(SJ4-1: st0057)}
+{hline}
+
+{title:FIML endogenous switching Poisson model}
+
+{p 8 13 2}{cmd:espoisson}{space 2}{it:depvar} [{it:varlist}]
+ [{cmd:if} {it:exp}] [{cmd:in} {it:range}] {cmd:,}
+ {cmdab:ed:ummy(}{it:varname}{cmd:)} [ {cmdab:s:witch(}{it:varlist}{cmd:)}
+ {cmdab:q:uadrature(}{it:#}{cmd:)} {cmd:rho0(}{it:#}{cmd:)}
+ {cmd:sigma0(}{it:#}{cmd:)} {cmd:exs} {it:maximize_options}]
+
+{p 8 8 2}Note: the vector {it:varlist} should include the switch variable
+(endogenous dummy) as one of its elements.{p_end}
+
+{p 4 4 2} The syntax of {help predict} after {cmd:espoisson} is
+
+{p 8 16 2}{cmd:predict} {it:newvar} [{cmd:if} {it:exp}]
+ [{cmd:in} {it:range}] [{cmd:,} n ]
+
+{p 4 4 2}where,
+
+{p 8 21 2}{cmd:n}{space 9}predicted number of events (default){p_end}
+
+
+{title:Description}
+
+{p 4 4 2}{cmd:espoisson} fits a FIML endogenous switching Poisson model.
+An endogenous dummy variable is present in the vector of explanatory
+variables, and there is unobserved individual heterogeneity. The endogenous
+dummy variable indicates the realization of two different regimes. The
+endogenous switching model corrects for the simultaneous equation bias that
+the presence of the endogenous dummy may induce in a standard exogenous-switch
+count model.
+
+{p 4 4 2}This program uses {cmd:ml d0} method.
+
+
+{title:Options}
+
+{p 4 8 2}{cmd:edummy(}{it:varname}{cmd:)} (required) specifies the endogenous
+dummy variable.
+
+{p 4 8 2} {cmd:switch(}{it:varlist}{cmd:)} specifies explanatory variables for
+the index function governing the endogenous dummy. If {cmd:switch()} is
+unspecified then a constant-only model is fitted.
+
+{p 4 8 2}{cmd:quadrature(}{it:#}{cmd:)} specifies the number of quadrature
+points for the Gauss-Hermite integral. Six points are used by default.
+
+{p 4 8 2}{cmd:rho0(}{it:#}{cmd:)} specifies initial value for rho. If
+unspecified, {cmd:rho0()}=0.01.
+
+{p 4 8 2}{cmdab:sigma0(}{it:#}{cmdab:)} specifies initial value for sigma. If
+unspecified, {cmd:sigma0()}=1.0.
+
+{p 4 8 2}{cmdab:exs} causes the program to fit an exogenous switching
+model.
+
+
+{title:Examples}
+
+{p 8 12 2}{cmd:. espoisson y x1 x2, ed(x2) s(x1) q(16)}{p_end}
+{p 8 12 2}{cmd:. predict yhat, n}{p_end}
+
+{p 8 12 2}{cmd:. espoisson y x1 x2, ed(x2) s(x1) q(16) exs}{p_end}
+{p 8 12 2}{cmd:. predict yhat, n}{p_end}
+
+
+{title:Author}
+
+{p 4 8 2}{bf: Alfonso Miranda}{p_end}
+{p 4 8 2} Economics Department, Warwick University, CV4 7AL, UK.{p_end}
+{p 4 8 2}E-mail: Alfonso.Miranda-Caso-Luengo@warwick.ac.uk{p_end}
+
+
+{title:Also see}
+
+{p 4 14 2}Manual: {hi:[U] 23 Estimation and post-estimation commands},{p_end}
+{p 13 13 2}{hi:[U] 29 Overview of model estimation in Stata},{p_end}
+{p 13 13 2}{hi:[R] poisson}
+{p 4 13 2}Online: help for {help ml}, {help glm}, {help nbreg}, {help svypois},
+{help xtpois}, {help zip}
diff --git a/Modules/ado/plus/e/espoisson_ll.ado b/Modules/ado/plus/e/espoisson_ll.ado
new file mode 100644
index 0000000..1a5c0c1
--- /dev/null
+++ b/Modules/ado/plus/e/espoisson_ll.ado
@@ -0,0 +1,74 @@
+*! Alfonso Miranda Caso Luengo (SJ4-1: st0057)
+*! Version 1.0 November 21 2002
+
+program define espoisson_ll
+
+ args todo b f
+
+ tempname lnsigma kappa delta
+ tempvar xb zb
+
+ local y "$ML_y1"
+ local d "$S_edum"
+
+ mleval `xb' = `b', eq(1)
+ mleval `zb' = `b', eq(2)
+ mleval `lnsigma' = `b', eq(3) scalar
+ mleval `kappa' = `b', eq(4) scalar
+
+
+ scalar `lnsigma' = cond(`lnsigma'<-20,-20,`lnsigma')
+
+ if `kappa' <-14 {
+ scalar `kappa' = -14
+ }
+ if `kappa' > 14 {
+ scalar `kappa' = 14
+ }
+
+ tempname sma u rho
+
+ scalar `sma' = exp(`lnsigma')
+ scalar `rho' = (exp(2*`kappa')-1)/(exp(2*`kappa')+1)
+
+ tempvar F p r1 r2 r3 r4 r5 r6
+
+ qui {
+ gen double `F' = . if $ML_samp
+
+ gen double `p' = 0 if $ML_samp
+ gen double `r1' = 0 if $ML_samp
+ gen double `r2' = 0 if $ML_samp
+ gen double `r3' = 0 if $ML_samp
+ gen double `r4' = 0 if $ML_samp
+ gen double `r5' = 0 if $ML_samp
+ gen double `r6' = 0 if $ML_samp
+
+ local m = 1
+ while `m' <= $S_quad {
+ scalar `u' = sqrt(2)*`sma'*scalar(x`m')
+ replace `r1' = `xb' + `u' if $ML_samp
+ replace `r2' = exp(`r1')^(`y')*exp(-exp(`r1')) if $ML_samp
+ replace `r3' = `r2'/exp(lngamma(`y'+1)) if $ML_samp
+ replace `r4' = `zb' + sqrt(2)*`rho'*scalar(x`m') if $ML_samp
+ replace `r5' = `r4'/(sqrt(1-`rho'^2)) if $ML_samp
+ replace `r6' = `d'*norm(`r5') + /*
+ */ (1-`d')*norm(-`r5') if $ML_samp
+ replace `F' = `r3'*`r6' if $ML_samp
+ replace `p' = `p' + scalar(w`m')*`F' if $ML_samp
+ local m = `m' + 1
+ }
+ replace `p'= (1/sqrt(_pi))*`p' if $ML_samp
+ replace `F' = log(`p') if $ML_samp
+ mlsum `f' = `F' if $ML_samp
+ }
+end
+exit
+
+
+
+
+
+
+
+
diff --git a/Modules/ado/plus/e/espoisson_p.ado b/Modules/ado/plus/e/espoisson_p.ado
new file mode 100644
index 0000000..a433478
--- /dev/null
+++ b/Modules/ado/plus/e/espoisson_p.ado
@@ -0,0 +1,50 @@
+*! version 1.0 Alfonso Miranda-Caso-Luengo, June 2003 (SJ4-1: st0057)
+program define espoisson_p, sort
+ version 7
+
+ local myopts "n"
+
+ _pred_se "`myopts'" `0'
+ if `s(done)' { exit }
+ local vtyp `s(typ)'
+ local varn `s(varn)'
+ local 0 `"`s(rest)'"'
+
+ syntax [if] [in] [, `myopts' noOFFset]
+
+ local type "`n'"
+ marksample touse
+
+ if "`type'"=="n" | "`type'"=="" {
+
+ tempname mu zu lnsigma kappa
+ qui _predict double `mu' if `touse', xb `offset' eq(#1)
+ qui _predict double `zu' if `touse', xb `offset' eq(#2)
+ qui _predict double `lnsigma' if `touse', xb eq(#3)
+ qui _predict double `kappa' if `touse', xb eq(#4)
+
+ local d "`e(edummy)'"
+
+ tempvar sma u rho
+ gen double `sma' = exp(`lnsigma')
+ gen double `rho' = (exp(2*`kappa')-1)/(exp(2*`kappa')+1)
+
+ tempvar p eta
+ gen double `p'=0 if `touse'
+ gen double `eta'=0 if `touse'
+ qui replace `mu'=exp(`mu'-0.5*`sma'^2) if `touse'
+ #delimit ;
+ qui replace `eta' = `d'*(norm(`zu' +`rho'*`sma')/norm(`zu'))
+ + (1-`d')*(norm(-(`zu'+`rho'*`sma'))/norm(-(`zu'))) if `touse' ;
+ #delimit cr
+ qui replace `p'=`mu'*`eta' if `touse'
+ qui gen `vtyp' `varn'=`p' if `touse'
+ label var `varn' "predicted number of events of `e(depvar)'"
+ exit
+ }
+end
+
+
+
+
+
diff --git a/Modules/ado/plus/e/estadd.ado b/Modules/ado/plus/e/estadd.ado
new file mode 100644
index 0000000..6098764
--- /dev/null
+++ b/Modules/ado/plus/e/estadd.ado
@@ -0,0 +1,2457 @@
+*! version 2.3.1 07oct2009 Ben Jann
+* 1. estadd and helpers
+* 2. estadd_local
+* 3. estadd_scalar
+* 4. estadd_matrix
+* 5. estadd_mean
+* 6. estadd_sd
+* 7. estadd_beta
+* 8. estadd_coxsnell
+* 9. estadd_nagelkerke
+* 10. estadd_ysumm
+* 11. estadd_summ
+* 12. estadd_vif
+* 13. estadd_ebsd
+* 14. estadd_expb
+* 15. estadd_pcorr
+* 16. estadd_lrtest
+* 17. estadd_brent
+* 18. estadd_fitstat
+* 19. estadd_listcoef
+* 20. estadd_mlogtest
+* 21. estadd_prchange
+* 22. estadd_prvalue
+* 23. estadd_asprvalue
+* 24. estadd_margins
+* 99. copy of erepost.ado
+
+* 1.
+program estadd
+ version 8.2
+ local caller : di _caller()
+ capt _on_colon_parse `0'
+ if !_rc {
+ local 0 `"`s(before)'"'
+ local names `"`s(after)'"'
+ }
+ syntax anything(equalok id="subcommand") [if] [in] [fw aw iw pw] [, * ]
+ if regexm(`"`anything'"',"^r\((.*)\)$") { // check -estadd r(name)-
+ capt confirm scalar `anything'
+ if _rc {
+ capt confirm matrix `anything'
+ if _rc {
+ di as err `"`anything' not found"'
+ exit 111
+ }
+ else {
+ local anything `"matrix `anything'"'
+ }
+ }
+ else {
+ local anything `"scalar `anything'"'
+ }
+ }
+ gettoken subcommand : anything
+ capt confirm name `subcommand'
+ if _rc {
+ di as err "invalid subcommand"
+ exit 198
+ }
+ if `"`options'"'!="" local options `", `options'"'
+ if `"`weight'`exp'"'!="" local wgtexp `"[`weight'`exp']"'
+
+//expand estimates names and backup current estimates if necessary
+ tempname rcurrent ecurrent
+ capt _return drop `rcurrent'
+ _return hold `rcurrent'
+ capt noisily {
+ local names: list retok names
+ if "`names'"=="" {
+ local names "."
+ local qui
+ }
+ else local qui quietly
+ foreach name of local names {
+ if "`name'"=="." {
+ capt est_expand "`name'"
+ if _rc local enames "`enames'`name' "
+ else local enames "`enames'`r(names)' "
+ }
+ else {
+ est_expand "`name'" //=> error if estimates not found
+ local enames "`enames'`r(names)' "
+ }
+ }
+ local names: list uniq enames
+ if "`names'"=="." local active
+ else {
+ capt est_expand .
+ if _rc local active "."
+ else local active "`r(names)'"
+ if "`active'"=="." | `:list posof "`active'" in names'==0 {
+ local active
+ _est hold `ecurrent', restore estsystem nullok
+ }
+ }
+ }
+ if _rc {
+ _return restore `rcurrent'
+ exit _rc
+ }
+ _return restore `rcurrent', hold
+
+// cases:
+// - if active estimates not stored yet and "`names'"==".": simply execute
+// estadd_subcmd to active estimates
+// - else if active estimates not stored yet: backup/restore active estimates
+// - else if active estimates stored but not in `names': backup/restore active estimates
+// - else if active estimates stored: no backup but restore at end
+
+//loop over estimates names and run subcommand
+ nobreak {
+ foreach m of local names {
+ if "`names'"!="." {
+ if "`m'"=="." _est unhold `ecurrent'
+ else {
+ capt confirm new var _est_`m' // fix e(sample)
+ if _rc qui replace _est_`m' = 0 if _est_`m' >=.
+ _est unhold `m'
+ }
+ }
+ backup_estimates_name
+ capt n break `qui' version `caller': estadd_`anything' `if' `in' `wgtexp' `options'
+ local rc = _rc
+ restore_estimates_name
+ if "`names'"!="." {
+ if "`m'"=="." _est hold `ecurrent', restore estsystem nullok
+ else _est hold `m', estimates varname(_est_`m')
+ }
+ if `rc' continue, break
+ }
+ if "`active'"!="" estimates restore `active', noh
+ }
+ _return restore `rcurrent'
+ if `rc' {
+ if `rc' == 199 di as error "invalid subcommand"
+ exit `rc'
+ }
+end
+
+program define backup_estimates_name, eclass
+ ereturn local _estadd_estimates_name `"`e(_estimates_name)'"'
+ ereturn local _estimates_name ""
+end
+program define restore_estimates_name, eclass
+ ereturn local _estimates_name `"`e(_estadd_estimates_name)'"'
+ ereturn local _estadd_estimates_name ""
+end
+
+program confirm_new_ename
+ capture confirm existence `e(`0')'
+ if !_rc {
+ di as err "e(`0') already defined"
+ exit 110
+ }
+end
+
+program confirm_esample
+ local efun: e(functions)
+ if `:list posof "sample" in efun'==0 {
+ di as err "e(sample) information not available"
+ exit 498
+ }
+end
+
+program confirm_numvar
+ args var
+ local ts = index("`var'",".")
+ confirm numeric variable `=substr("`var'",`ts'+1,.)'
+end
+
+program define added_macro
+ args name
+ di as txt %25s `"e(`name') : "' `""{res:`e(`name')'}""'
+end
+
+program define added_scalar
+ args name label
+ di as txt %25s `"e(`name') = "' " " as res e(`name') _c
+ if `"`label'"'!="" {
+ di as txt _col(38) `"(`label')"'
+ }
+ else di ""
+end
+
+program define added_matrix
+ args name label
+ capture {
+ local r = rowsof(e(`name'))
+ local c = colsof(e(`name'))
+ }
+ if _rc {
+ tempname tmp
+ mat `tmp' = e(`name')
+ local r = rowsof(`tmp')
+ local c = colsof(`tmp')
+ }
+ di as txt %25s `"e(`name') : "' " " ///
+ as res "`r' x `c'" _c
+ if `"`label'"'=="_rown" {
+ local thelabel: rownames e(`name')
+ local thelabel: list retok thelabel
+ if `r'>1 {
+ local thelabel: subinstr local thelabel " " ", ", all
+ }
+ di as txt _col(38) `"(`thelabel')"'
+ }
+ else if `"`label'"'!="" {
+ di as txt _col(38) `"(`label')"'
+ }
+ else di ""
+end
+
+* 2.
+* -estadd- subroutine: add local
+program estadd_loc
+ estadd_local `0'
+end
+program estadd_loca
+ estadd_local `0'
+end
+program estadd_local, eclass
+ version 8.2
+ syntax anything(equalok) [, Prefix(name) Replace Quietly ]
+ gettoken name def : anything , parse(" =:")
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'`name'
+ }
+ ereturn local `prefix'`name'`def'
+ di _n as txt "added macro:"
+ added_macro `prefix'`name'
+end
+
+* 3.
+* -estadd- subroutine: add scalar
+program estadd_sca
+ estadd_scalar `0'
+end
+program estadd_scal
+ estadd_scalar `0'
+end
+program estadd_scala
+ estadd_scalar `0'
+end
+program estadd_scalar, eclass
+ version 8.2
+ syntax anything(equalok) [, Prefix(name) Replace Quietly ]
+ if regexm("`anything'","^r\((.*)\)$") { // estadd scalar r(name)
+ local name = regexs(1)
+ capt confirm name `name'
+ confirm scalar `anything'
+ if _rc error 198
+ local equ "`anything'"
+ }
+ else {
+ local isname 0
+ gettoken name equ0: anything, parse(" =")
+ capt confirm name `name'
+ if _rc error 198
+ else if `"`equ0'"'=="" { // estadd scalar name
+ local isname 1
+ local equ "scalar(`name')"
+ }
+ else { // estadd scalar name [=] exp
+ gettoken trash equ : equ0, parse(" =")
+ if `"`trash'"'!="=" {
+ local equ `"`equ0'"'
+ }
+ }
+ }
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'`name'
+ }
+ ereturn scalar `prefix'`name' = `equ'
+ di _n as txt "added scalar:"
+ added_scalar `prefix'`name'
+end
+
+* 4.
+* -estadd- subroutine: add matrix
+program estadd_mat
+ estadd_matrix `0'
+end
+program estadd_matr
+ estadd_matrix `0'
+end
+program estadd_matri
+ estadd_matrix `0'
+end
+program estadd_matrix, eclass
+ version 8.2
+ syntax anything(equalok) [, Prefix(name) Replace Quietly ]
+ if regexm("`anything'","^r\((.*)\)$") { // estadd matrix r(name)
+ local name = regexs(1)
+ capt confirm name `name'
+ if _rc error 198
+ confirm matrix `anything'
+ local equ "`anything'"
+ }
+ else {
+ local isname 0
+ gettoken name equ0: anything, parse(" =")
+ capt confirm name `name'
+ if _rc error 198
+ else if `"`equ0'"'=="" { // estadd matrix name
+ local isname 1
+ local equ "`name'"
+ }
+ else { // estadd matrix name [=] exp
+ gettoken trash equ : equ0, parse(" =")
+ if `"`trash'"'!="=" {
+ local equ `"`equ0'"'
+ }
+ }
+ }
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'`name'
+ }
+ tempname M
+ mat `M' = `equ'
+ ereturn matrix `prefix'`name' = `M'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'`name'
+end
+
+* 5.
+* -estadd- subroutine: means of regressors
+program define estadd_mean, eclass
+ version 8.2
+ syntax [, Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'mean
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//copy coefficients matrix and determine varnames
+ tempname results
+ mat `results' = e(b)
+ local vars: colnames `results'
+//loop over variables: calculate -mean-
+ local j 0
+ foreach var of local vars {
+ local ++j
+ capture confirm_numvar `var'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ capt su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop', meanonly
+ mat `results'[1,`j'] = cond(_rc,.,r(mean))
+ }
+ }
+//return the results
+ ereturn matrix `prefix'mean = `results'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'mean
+end
+
+* 6.
+* -estadd- subroutine: standard deviations of regressors
+program define estadd_sd, eclass
+ version 8.2
+ syntax [, noBinary Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'sd
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//copy coefficients matrix and determine varnames
+ tempname results
+ mat `results' = e(b)
+ local vars: colnames `results'
+//loop over variables: calculate -mean-
+ local j 0
+ foreach var of local vars {
+ local ++j
+ capture confirm_numvar `var'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ capture assert `var'==0 | `var'==1 if e(sample) & `subpop'
+ if _rc | "`binary'"=="" {
+ capt su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop'
+ mat `results'[1,`j'] = cond(_rc,.,r(sd))
+ }
+ else mat `results'[1,`j'] = .z
+ }
+ }
+//return the results
+ ereturn matrix `prefix'sd = `results'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'sd
+end
+
+* 7.
+* -estadd- subroutine: standardized coefficients
+program define estadd_beta, eclass
+ version 8.2
+ syntax [, Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'beta
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//copy coefficients matrix and determine varnames
+ tempname results sddep
+ mat `results' = e(b)
+ local vars: colnames `results'
+ local eqs: coleq `results', q
+ local depv "`e(depvar)'"
+//loop over variables: calculate -beta-
+ local j 0
+ local lastdepvar
+ foreach var of local vars {
+ local depvar: word `++j' of `eqs'
+ if "`depvar'"=="_" local depvar "`depv'"
+ capture confirm_numvar `depvar'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ if "`depvar'"!="`lastdepvar'" {
+ capt su `depvar' [`wtype'`e(wexp)'] if e(sample) & `subpop'
+ scalar `sddep' = cond(_rc,.,r(sd))
+ }
+ capture confirm_numvar `var'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ capt su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop'
+ mat `results'[1,`j'] = cond(_rc,.,`results'[1,`j'] * r(sd) / `sddep')
+ }
+ }
+ local lastdepvar "`depvar'"
+ }
+//return the results
+ ereturn matrix `prefix'beta = `results'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'beta
+end
+
+* 8.
+* -estadd- subroutine: Cox & Snell Pseudo R-Squared
+program define estadd_coxsnell, eclass
+ version 8.2
+ syntax [, Prefix(name) Replace Quietly ]
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'coxsnell
+//compute statistic
+ tempname results
+ scalar `results' = 1 - exp((e(ll_0)-e(ll))*2/e(N)) // = 1 - exp(e(ll_0)-e(ll))^(2/e(N))
+//return the results
+ *di as txt "Cox & Snell Pseudo R2 = " as res `results'
+ ereturn scalar `prefix'coxsnell = `results'
+ di _n as txt "added scalar:"
+ added_scalar `prefix'coxsnell
+end
+
+* 9.
+* -estadd- subroutine: Nagelkerke Pseudo R-Squared
+program define estadd_nagelkerke, eclass
+ version 8.2
+ syntax [, Prefix(name) Replace Quietly ]
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'nagelkerke
+//compute statistic
+ tempname results
+ scalar `results' = (1 - exp((e(ll_0)-e(ll))*2/e(N))) / (1 - exp(e(ll_0)*2/e(N)))
+ // = (1 - exp(e(ll_0)-e(ll))^(2/e(N))) / (1 - exp(e(ll_0))^(2/e(N)))
+//return the results
+ *di as txt "Nagelkerke Pseudo R2 = " as res `results'
+ ereturn scalar `prefix'nagelkerke = `results'
+ di _n as txt "added scalar:"
+ added_scalar `prefix'nagelkerke
+end
+
+* 10.
+* -estadd- subroutine: summary statistics for dependent variable
+program define estadd_ysumm, eclass
+ version 8.2
+ syntax [, MEan SUm MIn MAx RAnge sd Var cv SEMean SKewness ///
+ Kurtosis MEDian p1 p5 p10 p25 p50 p75 p90 p95 p99 iqr q all ///
+ Prefix(passthru) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//default prefix
+ if `"`prefix'"'=="" local prefix y
+ else {
+ local 0 ", `prefix'"
+ syntax [, prefix(name) ]
+ }
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//determine list of stats
+ tempname results
+ local Stats p99 p95 p90 p75 p50 p25 p10 p5 p1 kurtosis ///
+ skewness var sd max min sum mean
+ if "`all'"!="" {
+ local stats `Stats'
+ local range range
+ local cv cv
+ local semean semean
+ local iqr iqr
+ local sumtype detail
+ }
+ else {
+ if "`q'"!="" {
+ local p25 p25
+ local p50 p50
+ local p75 p75
+ }
+ if "`median'"!="" local p50 p50
+ foreach stat of local Stats {
+ if "``stat''"!="" {
+ local stats: list stats | stat
+ }
+ }
+ if "`stats'"=="" & "`range'"=="" & "`cv'"=="" & ///
+ "`semean'"=="" & "`iqr'"=="" local stats sd max min mean
+ local sumtype sum mean min max
+ if "`:list stats - sumtype'"=="" & "`cv'"=="" & ///
+ "`semean'"=="" & "`iqr'"=="" local sumtype meanonly
+ else {
+ local sumtype `sumtype' Var sd
+ if "`:list stats - sumtype'"=="" & "`iqr'"=="" local sumtype
+ else local sumtype detail
+ }
+ }
+ local Stats: subinstr local stats "var" "Var"
+ local nstats: word count `iqr' `semean' `cv' `range' `stats'
+ if "`replace'"=="" {
+ foreach stat in `iqr' `semean' `cv' `range' `stats' {
+ confirm_new_ename `prefix'`=lower("`stat'")'
+ }
+ }
+//calculate stats
+ local var: word 1 of `e(depvar)'
+ mat `results' = J(`nstats',1,.z)
+ qui su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop', `sumtype'
+ local i 0
+ if "`iqr'"!="" {
+ mat `results'[`++i',1] = r(p75) - r(p25)
+ }
+ if "`semean'"!="" {
+ mat `results'[`++i',1] = r(sd) / sqrt(r(N))
+ }
+ if "`cv'"!="" {
+ mat `results'[`++i',1] = r(sd) / r(mean)
+ }
+ if "`range'"!="" {
+ mat `results'[`++i',1] = r(max) - r(min)
+ }
+ foreach stat of local Stats {
+ mat `results'[`++i',1] = r(`stat')
+ }
+//return the results
+ local i 0
+ di as txt _n "added scalars:"
+ foreach stat in `iqr' `semean' `cv' `range' `stats' {
+ local sname = lower("`stat'")
+ ereturn scalar `prefix'`sname' = `results'[`++i',1]
+ added_scalar `prefix'`sname'
+ }
+end
+
+* 11.
+* -estadd- subroutine: various summary statistics
+program define estadd_summ, eclass
+ version 8.2
+ syntax [, MEan SUm MIn MAx RAnge sd Var cv SEMean SKewness ///
+ Kurtosis MEDian p1 p5 p10 p25 p50 p75 p90 p95 p99 iqr q all ///
+ Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//determine list of stats
+ tempname results results2
+ local Stats p99 p95 p90 p75 p50 p25 p10 p5 p1 kurtosis ///
+ skewness var sd max min sum mean
+ if "`all'"!="" {
+ local stats `Stats'
+ local range range
+ local cv cv
+ local semean semean
+ local iqr iqr
+ local sumtype detail
+ }
+ else {
+ if "`q'"!="" {
+ local p25 p25
+ local p50 p50
+ local p75 p75
+ }
+ if "`median'"!="" local p50 p50
+ foreach stat of local Stats {
+ if "``stat''"!="" {
+ local stats: list stats | stat
+ }
+ }
+ if "`stats'"=="" & "`range'"=="" & "`cv'"=="" & ///
+ "`semean'"=="" & "`iqr'"=="" local stats sd max min mean
+ local sumtype sum mean min max
+ if "`:list stats - sumtype'"=="" & "`cv'"=="" & ///
+ "`semean'"=="" & "`iqr'"=="" local sumtype meanonly
+ else {
+ local sumtype `sumtype' Var sd
+ if "`:list stats - sumtype'"=="" & "`iqr'"=="" local sumtype
+ else local sumtype detail
+ }
+ }
+ local Stats: subinstr local stats "var" "Var"
+ local nstats: word count `iqr' `semean' `cv' `range' `stats'
+ if "`replace'"=="" {
+ foreach stat in `iqr' `semean' `cv' `range' `stats' {
+ confirm_new_ename `prefix'`=lower("`stat'")'
+ }
+ }
+//copy coefficients matrix and determine varnames
+ mat `results' = e(b)
+ local vars: colnames `results'
+ if `nstats'>1 {
+ mat `results' = `results' \ J(`nstats'-1,colsof(`results'),.z)
+ }
+//loop over variables: calculate stats
+ local j 0
+ foreach var of local vars {
+ local ++j
+ capture confirm_numvar `var'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ capt su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop', `sumtype'
+ local i 0
+ if "`iqr'"!="" {
+ mat `results'[`++i',`j'] = cond(_rc,.,r(p75) - r(p25))
+ }
+ if "`semean'"!="" {
+ mat `results'[`++i',`j'] = cond(_rc,.,r(sd) / sqrt(r(N)))
+ }
+ if "`cv'"!="" {
+ mat `results'[`++i',`j'] = cond(_rc,.,r(sd) / r(mean))
+ }
+ if "`range'"!="" {
+ mat `results'[`++i',`j'] = cond(_rc,.,r(max) - r(min))
+ }
+ foreach stat of local Stats {
+ mat `results'[`++i',`j'] = cond(_rc,.,r(`stat'))
+ }
+ }
+ }
+//return the results
+ local i 0
+ di as txt _n "added matrices:"
+ foreach stat in `iqr' `semean' `cv' `range' `stats' {
+ local sname = lower("`stat'")
+ mat `results2' = `results'[`++i',1...]
+ ereturn matrix `prefix'`sname' = `results2'
+ added_matrix `prefix'`sname'
+ }
+end
+
+* 12.
+* -estadd- subroutine: variance inflation factors
+program define estadd_vif, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax [, TOLerance SQRvif Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'vif
+ if "`tolerance'"!="" confirm_new_ename `prefix'tolerance
+ if "`sqrvif'"!="" confirm_new_ename `prefix'sqrvif
+ }
+//copy coefficients matrix and set to .z
+ tempname results results2 results3
+ matrix `results' = e(b)
+ forv j = 1/`=colsof(`results')' {
+ mat `results'[1,`j'] = .z
+ }
+ if "`tolerance'"!="" mat `results2' = `results'
+ if "`sqrvif'"!="" mat `results3' = `results'
+//compute VIF and add to results vector
+ capt n `quietly' version `caller': vif
+ if _rc {
+ if _rc == 301 di as err "-estadd:vif- can only be used after -regress-"
+ exit _rc
+ }
+ local i 0
+ local name "`r(name_`++i')'"
+ while "`name'"!="" {
+ local j = colnumb(`results',"`name'")
+ if `j'<. {
+ matrix `results'[1,`j'] = r(vif_`i')
+ if "`tolerance'"!="" matrix `results2'[1,`j'] = 1 / r(vif_`i')
+ if "`sqrvif'"!="" matrix `results3'[1,`j'] = sqrt( r(vif_`i') )
+ }
+ local name "`r(name_`++i')'"
+ }
+//return the results
+ if "`sqrvif'"!="" | "`tolerance'"!="" di as txt _n "added matrices:"
+ else di as txt _n "added matrix:"
+ if "`sqrvif'"!="" {
+ ereturn matrix `prefix'sqrvif = `results3'
+ added_matrix `prefix'sqrvif
+ }
+ if "`tolerance'"!="" {
+ ereturn matrix `prefix'tolerance = `results2'
+ added_matrix `prefix'tolerance
+ }
+ ereturn matrix `prefix'vif = `results'
+ added_matrix `prefix'vif
+end
+
+* 13.
+* -estadd- subroutine: standardized factor change coefficients
+program define estadd_ebsd, eclass
+ version 8.2
+ syntax [, Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'ebsd
+//use aweights with -summarize-
+ local wtype `e(wtype)'
+ if "`wtype'"=="pweight" local wtype aweight
+//subpop?
+ local subpop "`e(subpop)'"
+ if "`subpop'"=="" local subpop 1
+//copy coefficients matrix and determine varnames
+ tempname results
+ mat `results' = e(b)
+ local vars: colnames `results'
+//loop over variables: calculate -mean-
+ local j 0
+ foreach var of local vars {
+ local ++j
+ capture confirm_numvar `var'
+ if _rc mat `results'[1,`j'] = .z
+ else {
+ capt su `var' [`wtype'`e(wexp)'] if e(sample) & `subpop'
+ mat `results'[1,`j'] = cond(_rc,.,exp( `results'[1,`j'] * r(sd)))
+ }
+ }
+//return the results
+ ereturn matrix `prefix'ebsd = `results'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'ebsd
+end
+
+* 14.
+* -estadd- subroutine: exponentiated coefficients
+program define estadd_expb, eclass
+ version 8.2
+ syntax [, noCONStant Prefix(name) Replace Quietly ]
+//check e()-names
+ if "`replace'"=="" confirm_new_ename `prefix'expb
+//copy coefficients matrix and determine names of coefficients
+ tempname results
+ mat `results' = e(b)
+ local coefs: colnames `results'
+//loop over coefficients
+ local j 0
+ foreach coef of local coefs {
+ local ++j
+ if `"`constant'"'!="" & `"`coef'"'=="_cons" {
+ mat `results'[1,`j'] = .z
+ }
+ else {
+ mat `results'[1,`j'] = exp(`results'[1,`j'])
+ }
+ }
+//return the results
+ ereturn matrix `prefix'expb = `results'
+ di _n as txt "added matrix:"
+ added_matrix `prefix'expb
+end
+
+* 15.
+* -estadd- subroutine: partial and semi-partial correlations
+program define estadd_pcorr, eclass
+ version 8.2
+ syntax [, semi Prefix(name) Replace Quietly ]
+//check availability of e(sample)
+ confirm_esample
+//check e()-names
+ if "`replace'"=="" {
+ if "`semi'"!="" confirm_new_ename `prefix'spcorr
+ confirm_new_ename `prefix'pcorr
+ }
+//copy coefficients matrix and set to .z
+ tempname results results2
+ matrix `results' = e(b)
+ forv j = 1/`=colsof(`results')' {
+ mat `results'[1,`j'] = .z
+ }
+ local eqs: coleq `results', quoted
+ local eq: word 1 of `eqs'
+ mat `results2' = `results'[1,"`eq':"]
+ local vars: colnames `results2'
+ foreach var of local vars {
+ capt confirm numeric var `var'
+ if !_rc local temp "`temp'`var' "
+ }
+ local vars "`temp'"
+ if "`semi'"!="" mat `results2' = `results'
+ else {
+ mat drop `results2'
+ local results2
+ }
+ local depv: word 1 of `e(depvar)'
+//compute statistics and add to results vector
+ local wtype `e(wtype)'
+ if inlist("`wtype'","pweight","iweight") local wtype aweight
+ _estadd_pcorr_compute `depv' `vars' [`wtype'`e(wexp)'] if e(sample), ///
+ eq(`eq') results(`results') results2(`results2')
+//return the results
+ if "`semi'"!="" {
+ di as txt _n "added matrices:"
+ ereturn matrix `prefix'spcorr = `results2'
+ added_matrix `prefix'spcorr
+ }
+ else di as txt _n "added matrix:"
+ ereturn matrix `prefix'pcorr = `results'
+ added_matrix `prefix'pcorr
+end
+program define _estadd_pcorr_compute // based on pcorr.ado by StataCorp
+ // and pcorr2.ado by Richard Williams
+ syntax varlist(min=1) [aw fw] [if], eq(str) results(str) [ results2(str) ]
+ marksample touse
+ tempname hcurrent
+ _est hold `hcurrent', restore
+ quietly reg `varlist' [`weight'`exp'] if `touse'
+ if (e(N)==0 | e(N)>=.) error 2000
+ local NmK = e(df_r)
+ local R2 = e(r2)
+ gettoken depv varlist: varlist
+ foreach var of local varlist {
+ quietly test `var'
+ if r(F)<. {
+ local s "1"
+ if _b[`var']<0 local s "-1"
+ local c = colnumb(`results',"`eq':`var'")
+ mat `results'[1,`c'] = `s' * sqrt(r(F)/(r(F)+`NmK'))
+ if "`results2'"!="" {
+ mat `results2'[1,`c'] = `s' * sqrt(r(F)*((1-`R2')/`NmK'))
+ }
+ }
+ }
+end
+
+* 16.
+* -estadd- subroutine: Likelihood-ratio test
+program define estadd_lrtest, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax anything(id="model") [, Name(name) Prefix(name) Replace Quietly * ]
+ if "`name'"=="" local name lrtest_
+//check e()-names
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'`name'p
+ confirm_new_ename `prefix'`name'chi2
+ confirm_new_ename `prefix'`name'df
+ }
+//compute statistics
+ `quietly' version `caller': lrtest `anything', `options'
+//return the results
+ ereturn scalar `prefix'`name'p = r(p)
+ ereturn scalar `prefix'`name'chi2 = r(chi2)
+ ereturn scalar `prefix'`name'df = r(df)
+ di _n as txt "added scalars:"
+ added_scalar `prefix'`name'p
+ added_scalar `prefix'`name'chi2
+ added_scalar `prefix'`name'df
+end
+
+* 17.
+* -estadd- subroutine: support for -brant- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_brant, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax [ , Prefix(name) Replace Quietly * ]
+ capt findfile brant.ado
+ if _rc {
+ di as error "fitstat.ado from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+// check names
+ if "`replace'"=="" {
+ foreach name in brant_chi2 brant_df brant_p brant {
+ confirm_new_ename `prefix'`name'
+ }
+ }
+// compute and return the results
+ `quietly' version `caller': brant, `options'
+ di as txt _n "added scalars:"
+ foreach stat in chi2 df p {
+ ereturn scalar `prefix'brant_`stat' = r(`stat')
+ added_scalar `prefix'brant_`stat'
+ }
+ tempname mat
+ matrix `mat' = r(ivtests)
+ matrix `mat' = `mat''
+ ereturn matrix `prefix'brant = `mat'
+ di as txt _n "added matrix:"
+ added_matrix `prefix'brant _rown
+end
+
+* 18.
+* -estadd- subroutine: support for -fitstat- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_fitstat, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax [ , Prefix(name) Replace Quietly Bic * ]
+ capt findfile fitstat.ado
+ if _rc {
+ di as error "fitstat.ado from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+ `quietly' version `caller': fitstat, `bic' `options'
+ local stats: r(scalars)
+ local allstats ///
+ dev dev_df lrx2 lrx2_df lrx2_p r2_adj r2_mf r2_mfadj r2_ml ///
+ r2_cu r2_mz r2_ef v_ystar v_error r2_ct r2_ctadj aic aic_n ///
+ bic bic_p statabic stataaic n_rhs n_parm
+ local stats: list allstats & stats
+ if "`bic'"!="" {
+ local bic aic aic_n bic bic_p statabic stataaic
+ local stats: list bic & stats
+ }
+
+
+// check names
+ if "`replace'"=="" {
+ foreach stat of local stats {
+ if inlist("`stat'", "bic", "aic") local rname `stat'0
+ else local rname `stat'
+ confirm_new_ename `prefix'`rname'
+ }
+ }
+
+// return the results
+ di as txt _n "added scalars:"
+ foreach stat of local stats {
+ if inlist("`stat'", "bic", "aic") local rname `stat'0
+ else local rname `stat'
+ ereturn scalar `prefix'`rname' = r(`stat')
+ added_scalar `prefix'`rname'
+ }
+end
+
+* 19.
+* -estadd- subroutine: support for -listcoef- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_listcoef, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax [anything] [ , Prefix(name) Replace Quietly ///
+ nosd gt lt ADJacent Matrix EXpand * ]
+
+// handle some options and look for e(sample)
+ if `"`matrix'"'!="" {
+ local matrix matrix
+ }
+ if `"`e(cmd)'"'=="slogit" & "`expand'"!="" {
+ di as err "-expand- option not supported"
+ exit 198
+ }
+ confirm_esample
+
+// set some constants
+ local listcoef_matrices "xs ys std fact facts pct pcts"
+ if "`sd'"=="" local listcoef_matrices "`listcoef_matrices' sdx"
+
+// run listcoef
+ capt findfile listcoef.ado
+ if _rc {
+ di as error "-listcoef- from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+ `quietly' version `caller': listcoef `anything' , matrix `gt' `lt' `adjacent' `options'
+
+// check existing e()'s
+ if "`replace'"=="" {
+ confirm_new_ename `prefix'pvalue
+ foreach matrix of local listcoef_matrices {
+ _estadd_listcoef_ChkEName b_`matrix', prefix(`prefix')
+ }
+ }
+
+// grab r()-results and post in e()
+ di as txt _n "added matrices:"
+ if inlist(`"`e(cmd)'"',"mlogit","mprobit") {
+ _estadd_listcoef_AddResToNomModl `listcoef_matrices', prefix(`prefix') `gt' `lt' `adjacent'
+ }
+ else {
+ foreach matrix of local listcoef_matrices {
+ _estadd_listcoef_AddMatToE `matrix', prefix(`prefix')
+ }
+ }
+end
+program define _estadd_listcoef_ChkEName
+ syntax name [, prefix(str) ]
+ capt confirm matrix r(`namelist')
+ if _rc exit
+ confirm_new_ename `prefix'`namelist'
+end
+program define _estadd_listcoef_AddMatToE, eclass
+ syntax name [, prefix(str) ]
+ capt confirm matrix r(b_`namelist')
+ if _rc exit
+ tempname tmp
+ matrix `tmp' = r(b_`namelist')
+ capt confirm matrix r(b2_`namelist')
+ if _rc==0 {
+ local eqnames: coleq e(b), quoted
+ local eqnames: list uniq eqnames
+ local eqname: word 1 of `eqnames'
+ mat coleq `tmp' = `"`eqname'"'
+ tempname tmp2
+ matrix `tmp2' = r(b2_`namelist')
+ local eqname: word 2 of `eqnames'
+ mat coleq `tmp2' = `"`eqname'"'
+ mat `tmp' = `tmp' , `tmp2'
+ mat drop `tmp2'
+ }
+ ereturn matrix `prefix'b_`namelist' = `tmp'
+ added_matrix `prefix'b_`namelist' _rown
+end
+program define _estadd_listcoef_AddResToNomModl, eclass
+ syntax anything(name=listcoef_matrices) [, prefix(str) gt lt ADJacent ]
+ if "`lt'"=="" & "`gt'"=="" {
+ local lt lt
+ local gt gt
+ }
+ local adjacent = "`adjacent'"!=""
+ local lt = "`lt'"!=""
+ local gt = "`gt'"!=""
+
+// outcomes and labels
+ tempname outcomes
+ if `"`e(cmd)'"'=="mlogit" {
+ if c(stata_version) < 9 local type cat
+ else local type out
+ mat `outcomes' = e(`type')
+ local noutcomes = colsof(`outcomes')
+ local eqnames `"`e(eqnames)'"'
+ if (`:list sizeof eqnames'<`noutcomes') {
+ local ibase = e(ibase`type')
+ }
+ else local ibase 0
+ forv i = 1/`noutcomes' {
+ if `i'==`ibase' {
+ local outcomelab`i' `"`e(baselab)'"'
+ }
+ else {
+ gettoken eq eqnames : eqnames
+ local outcomelab`i' `"`eq'"'
+ }
+ if `"`outcomelab`i''"'=="" {
+ local outcomelab`i': di `outcomes'[1,`i']
+ }
+ }
+ }
+ else if `"`e(cmd)'"'=="mprobit" {
+ mat `outcomes' = e(outcomes)'
+ local noutcomes = colsof(`outcomes')
+ forv i = 1/`noutcomes' {
+ local outcomelab`i' `"`e(out`i')'"'
+ }
+ }
+ else {
+ di as err `"`e(cmd)' not supported"
+ exit 499
+ }
+
+// collect vectors
+ tempname stats
+ mat `stats' = r(b) \ r(b_z) \ r(b_z) \ r(b_p)
+ forv i = 1/`=colsof(`stats')' {
+ mat `stats'[2,`i'] = `stats'[1,`i'] / `stats'[3,`i']
+ }
+ mat rown `stats' = "b" "se" "z" "P>|z|"
+ local enames "b_raw b_se b_z b_p"
+ foreach matrix of local listcoef_matrices {
+ capt confirm matrix r(b_`matrix')
+ if _rc continue
+ mat `stats' = `stats' \ r(b_`matrix')
+ local enames `"`enames' b_`matrix'"'
+ }
+
+// select/reorder contrasts of interest
+ local contrast "r(contrast)"
+ local ncontrast = colsof(`contrast')
+ tempname stats0 temp
+ matrix rename `stats' `stats0'
+ forv i = 1/`noutcomes' {
+ local out1 = `outcomes'[1, `i']
+ local j 0
+ forv j = 1/`noutcomes' {
+ local out2 = `outcomes'[1, `j']
+ if `out1'==`out2' continue
+ if `adjacent' & abs(`i'-`j')>1 continue
+ if `lt'==0 & `out1'<`out2' continue
+ if `gt'==0 & `out1'>`out2' continue
+ forv l = 1/`ncontrast' {
+ if el(`contrast',1,`l')!=`out1' continue
+ if el(`contrast',2,`l')!=`out2' continue
+ mat `temp' = `stats0'[1..., `l']
+ mat coleq `temp' = `"`outcomelab`i''-`outcomelab`j'"'
+ mat `stats' = nullmat(`stats'), `temp'
+ }
+ }
+ }
+ capt mat drop `stats0'
+
+// post rows to e()
+ local i 0
+ foreach ename of local enames {
+ local ++i
+ mat `temp' = `stats'[`i', 1...]
+ ereturn matrix `prefix'`ename' = `temp'
+ added_matrix `prefix'`ename' _rown
+ }
+end
+
+* 20.
+* -estadd- subroutine: support for -mlogtest- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_mlogtest, eclass
+ version 8.2
+ local caller : di _caller()
+ syntax [anything] [ , Prefix(name) Replace Quietly set(passthru) * ]
+ `quietly' version `caller': mlogtest `anything' , `set' `options'
+ local rmat: r(matrices)
+
+ // check names
+ if `"`replace'"'=="" {
+ foreach m in combine lrcomb {
+ if `:list m in rmat'==0 continue
+ forv r = 1/`=rowsof(r(`m'))' {
+ local cat1 = el(r(`m'),`r',1)
+ local cat2 = el(r(`m'),`r',2)
+ confirm_new_ename `prefix'`m'_`cat1'_`cat2'_chi2
+ confirm_new_ename `prefix'`m'_`cat1'_`cat2'_df
+ confirm_new_ename `prefix'`m'_`cat1'_`cat2'_p
+ }
+ }
+ foreach m in hausman suest smhsiao {
+ if `:list m in rmat'==0 continue
+ forv r = 1/`=rowsof(r(`m'))' {
+ local cat = el(r(`m'),`r',1)
+ confirm_new_ename `prefix'`m'_`cat'_chi2
+ confirm_new_ename `prefix'`m'_`cat'_df
+ confirm_new_ename `prefix'`m'_`cat'_p
+ }
+ }
+ if `"`set'"'!="" {
+ foreach m in wald lrtest {
+ if `:list m in rmat'==0 continue
+ local i 0
+ local r = rownumb(r(`m'),"set_`++i'")
+ while(`r'<.) {
+ confirm_new_ename `prefix'`m'_set`i'_chi2
+ confirm_new_ename `prefix'`m'_set`i'_df
+ confirm_new_ename `prefix'`m'_set`i'_p
+ local r = rownumb(r(`m'),"set_`++i'")
+ }
+ }
+ }
+ foreach m in wald lrtest {
+ if `:list m in rmat'==0 continue
+ local r .
+ if `"`set'"'!="" local r = rownumb(r(`m'),"set_1")-1
+ if `r'<1 continue
+ confirm_new_ename `prefix'`m'
+ }
+ }
+
+ local di_added_scalars `"di _n as txt "added scalars:"'
+ // combine
+ foreach m in combine lrcomb {
+ if `:list m in rmat'==0 continue
+ `di_added_scalars'
+ local di_added_scalars
+ forv r = 1/`=rowsof(r(`m'))' {
+ local cat1 = el(r(`m'),`r',1)
+ local cat2 = el(r(`m'),`r',2)
+ eret scalar `prefix'`m'_`cat1'_`cat2'_chi2 = el(r(`m'),`r',3)
+ added_scalar `prefix'`m'_`cat1'_`cat2'_chi2
+ eret scalar `prefix'`m'_`cat1'_`cat2'_df = el(r(`m'),`r',4)
+ added_scalar `prefix'`m'_`cat1'_`cat2'_df
+ eret scalar `prefix'`m'_`cat1'_`cat2'_p = el(r(`m'),`r',5)
+ added_scalar `prefix'`m'_`cat1'_`cat2'_p
+ }
+ }
+ // iia
+ foreach m in hausman suest smhsiao {
+ if `:list m in rmat'==0 continue
+ `di_added_scalars'
+ local di_added_scalars
+ if "`m'"=="smhsiao" local skip 2
+ else local skip 0
+ forv r = 1/`=rowsof(r(`m'))' {
+ local cat = el(r(`m'),`r',1)
+ eret scalar `prefix'`m'_`cat'_chi2 = el(r(`m'),`r',2+`skip')
+ added_scalar `prefix'`m'_`cat'_chi2
+ eret scalar `prefix'`m'_`cat'_df = el(r(`m'),`r',3+`skip')
+ added_scalar `prefix'`m'_`cat'_df
+ eret scalar `prefix'`m'_`cat'_p = el(r(`m'),`r',4+`skip')
+ added_scalar `prefix'`m'_`cat'_p
+ }
+ }
+
+ // wald/lrtest
+ tempname tmp
+ if `"`set'"'!="" {
+ foreach m in wald lrtest {
+ if `:list m in rmat'==0 continue
+ local i 0
+ local r = rownumb(r(`m'),"set_`++i'")
+ if `r'>=. continue
+ `di_added_scalars'
+ local di_added_scalars
+ while(`r'<.) {
+ eret scalar `prefix'`m'_set`i'_chi2 = el(r(`m'),`r',1)
+ added_scalar `prefix'`m'_set`i'_chi2
+ eret scalar `prefix'`m'_set`i'_df = el(r(`m'),`r',2)
+ added_scalar `prefix'`m'_set`i'_df
+ eret scalar `prefix'`m'_set`i'_p = el(r(`m'),`r',3)
+ added_scalar `prefix'`m'_set`i'_p
+ local r = rownumb(r(`m'),"set_`++i'")
+ }
+ }
+ }
+ local di_added_matrices `"di _n as txt "added matrices:"'
+ foreach m in wald lrtest {
+ if `:list m in rmat'==0 continue
+ local r .
+ if `"`set'"'!="" local r = rownumb(r(`m'),"set_1")-1
+ if `r'<1 continue
+ `di_added_matrices'
+ local di_added_matrices
+ mat `tmp' = r(`m')
+ mat `tmp' = `tmp'[1..`r',1...]'
+ eret mat `prefix'`m' = `tmp'
+ added_matrix `prefix'`m' _rown
+ }
+
+end
+
+
+* 21.
+* -estadd- subroutine: support for -prchange- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_prchange
+ version 8.2
+ local caller : di _caller()
+ syntax [anything] [if] [in] [ , Prefix(name) Replace Quietly ///
+ PAttern(str) Binary(str) Continuous(str) NOAvg Avg split SPLIT2(name) ///
+ adapt /// old syntax; now works as synonym for noavg
+ Outcome(passthru) Fromto noBAse * ]
+
+// handle some options
+ if `"`split2'"'!="" local split split
+ if "`split'"!="" & `"`outcome'"'!="" {
+ di as err "split and outcome() not both allowed"
+ exit 198
+ }
+ if "`split'"!="" & `"`avg'`noavg'"'!="" {
+ di as err "split and avg not both allowed"
+ exit 198
+ }
+ if "`avg'"!="" & `"`outcome'"'!="" {
+ di as err "avg and outcome not both allowed"
+ exit 198
+ }
+ if "`avg'"!="" & "`noavg'"!="" {
+ di as err "avg and noavg not both allowed"
+ exit 198
+ }
+ if `"`adapt'"'!="" local noavg noavg
+ if `:list sizeof binary'>1 | `:list sizeof continuous'>1 error 198
+ estadd_prchange_ExpandType binary `"`binary'"'
+ estadd_prchange_ExpandType continuous `"`continuous'"'
+ if `"`binary'"'=="" local binary 2
+ if `"`continuous'"'=="" local continuous 4
+ if `"`pattern'"'!="" {
+ estadd_prchange_ExpandType pattern `"`pattern'"'
+ }
+
+// check e(sample)
+ confirm_esample
+
+// run prchange
+ capt findfile prchange.ado
+ if _rc {
+ di as error "-prchange- from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+ `quietly' version `caller': prchange `anything' `if' `in', `base' `outcome' `fromto' `options'
+
+// determine type of model (ordinal: nomord = 1; nominal: nomord = 2)
+ local nomord = (r(modeltype)=="typical nomord")
+ if inlist(`"`e(cmd)'"',"mlogit","mprobit") local nomord = 2
+ if "`avg'`noavg'"!="" {
+ if `nomord'==0 {
+ di as err "avg not allowed with this model"
+ exit 198
+ }
+ }
+ if !`nomord' & "`split'"!="" {
+ di as err "split not allowed with this model"
+ exit 198
+ }
+
+// determine outcome number (in prchange-returns)
+ if `"`outcome'"'!="" {
+ if `nomord' {
+ forv i = 1/`=colsof(r(catval))' {
+ if el(r(catval), 1, `i') == r(outcome) {
+ local outcomenum `i'
+ continue, break
+ }
+ }
+ if "`outcomenum'"=="" { // should never happen
+ di as err `"outcome `outcome' not found"'
+ exit 499
+ }
+ }
+ else {
+ local outcomenum = colnumb(r(predval), `"`r(outcome)'"')
+ }
+ }
+
+// check names
+ if "`replace'"=="" {
+ if `"`outcome'"'!="" | "`split'"!="" | `nomord'==0 {
+ confirm_new_ename `prefix'predval
+ if `"`outcome'"'!="" | "`split'"!="" {
+ confirm_new_ename `prefix'outcome
+ }
+ }
+ else {
+ forv i = 1/`=colsof(r(catval))' {
+ local theoutcome: di el(r(catval),1,`i')
+ confirm_new_ename `prefix'predval`theoutcome'
+ }
+ }
+ confirm_new_ename `prefix'delta
+ confirm_new_ename `prefix'centered
+ confirm_new_ename `prefix'dc
+ if "`fromto'"!="" {
+ confirm_new_ename `prefix'dcfrom
+ confirm_new_ename `prefix'dcto
+ }
+ if "`nobase'"=="" {
+ confirm_new_ename `prefix'X
+ }
+ }
+
+// grab r()-results and post in e()
+ if "`split'"!="" {
+ if `"`split2'"'=="" {
+ local split2 `"`e(_estadd_estimates_name)'"'
+ if `"`split2'"'=="" {
+ local split2 `"`e(cmd)'"'
+ }
+ local split2 `"`split2'_"'
+ }
+ _estadd_prchange_StoreEachOutc `split2' , nomord(`nomord') ///
+ pattern(`pattern') binary(`binary') continuous(`continuous') ///
+ `base' `fromto' prefix(`prefix')
+ }
+ else {
+ _estadd_prchange_AddStuffToE, nomord(`nomord') outcome(`outcomenum') ///
+ pattern(`pattern') binary(`binary') continuous(`continuous') ///
+ `avg' `noavg' `base' `fromto' prefix(`prefix')
+ }
+end
+program estadd_prchange_ExpandType
+ args name list
+ foreach l of local list {
+ local w = length(`"`l'"')
+ if `"`l'"'==substr("minmax",1,max(2,`w')) local type 1
+ else if `"`l'"'==substr("01",1,max(1,`w')) local type 2
+ else if `"`l'"'==substr("delta",1,max(1,`w')) local type 3
+ else if `"`l'"'==substr("sd",1,max(1,`w')) local type 4
+ else if `"`l'"'==substr("margefct",1,max(1,`w')) local type 5
+ else {
+ di as err `"'`l'' not allowed"'
+ exit 198
+ }
+ local newlist `newlist' `type'
+ }
+ c_local `name' `newlist'
+end
+program define _estadd_prchange_AddStuffToE, eclass
+// input add
+// ========================= ========================================
+// outcome() nomord opt change changenm change# predval outcome
+// no 0 - x last
+// yes 0 - x x x
+// no 1/2 - x all all
+// yes 1/2 - x x x
+// no 1/2 avg x all
+// no 1/2 noavg all all
+// nobase=="" => add X, SD, Min, Max
+// all models => add centered, delta
+ syntax , nomord(str) [ pattern(passthru) binary(passthru) continuous(passthru) ///
+ outcome(str) NOAVG avg nobase fromto prefix(str) ] //
+// prepare predval and determine value of outcome
+ if `"`outcome'"'!="" {
+ tempname predv
+ mat `predv' = r(predval)
+ mat `predv' = `predv'[1...,`outcome']
+ if `nomord' {
+ local theoutcome: di el(r(catval),1,`outcome')
+ }
+ else {
+ local theoutcome: colnames `predv'
+ }
+ }
+// add scalars
+ di _n as txt "added scalars:"
+// - predval and outcome
+ local cpredval = colsof(r(predval))
+ if `"`outcome'"'!="" {
+ ereturn scalar `prefix'predval = `predv'[1,1]
+ added_scalar `prefix'predval `"`lab_predval'"'
+ ereturn scalar `prefix'outcome = `theoutcome'
+ added_scalar `prefix'outcome
+ }
+ else if `nomord' { // add all
+ forv i=1/`cpredval' {
+ local theoutcome: di el(r(catval),1,`i')
+ ereturn scalar `prefix'predval`theoutcome' = el(r(predval),1,`i')
+ added_scalar `prefix'predval`theoutcome'
+ }
+ }
+ else { // add last
+ ereturn scalar `prefix'predval = el(r(predval),1,`cpredval')
+ added_scalar `prefix'predval
+ }
+// - delta and centered
+ ereturn scalar `prefix'delta = r(delta)
+ added_scalar `prefix'delta
+ ereturn scalar `prefix'centered = r(centered)
+ added_scalar `prefix'centered
+// add matrices
+ di _n as txt "added matrices:"
+ if `nomord'==0 {
+ if r(modeltype)=="twoeq count" & "`test'"=="" {
+ local eq: coleq e(b)
+ local eq: word 1 of `eq'
+ }
+ _estadd_prchange_PostMat r(change), prefix(`prefix') ///
+ name(dc) `pattern' `binary' `continuous' `fromto' eq(`eq')
+ }
+ else {
+ if `"`outcome'"'=="" {
+ if "`avg'"!="" local nomordmat "r(changemn)"
+ else {
+ tempname nomordmat
+ _estadd_prchange_GatherNomChMat `nomordmat' `noavg'
+ }
+ _estadd_prchange_PostMat `nomordmat', prefix(`prefix') ///
+ name(dc) `pattern' `binary' `continuous' `fromto'
+ }
+ else {
+ if `nomord'==2 {
+ _estadd_prchange_GetEqnmNomModl `theoutcome'
+ }
+ _estadd_prchange_PostMat r(change`theoutcome'), prefix(`prefix') ///
+ name(dc) `pattern' `binary' `continuous' `fromto' eq(`eq')
+ }
+ }
+ if `"`base'"'=="" {
+ _estadd_prchange_PostMat r(baseval), prefix(`prefix') name(X)
+ }
+ if `"`pattern'"'=="" {
+ _estadd_prchange_dcNote, prefix(`prefix') name(dc) `binary' `continuous'
+ }
+end
+program define _estadd_prchange_dcNote
+ syntax [ , prefix(str) name(str) binary(str) continuous(str) ]
+ local res `""{res:minmax} change" "{res:01} change" "{res:delta} change" "{res:sd} change" "{res:margefct}""'
+ local bres: word `binary' of `res'
+ local cres: word `continuous' of `res'
+ di _n as txt `"first row in e(dc) contains:"'
+ di _n `" `bres' for binary variables"'
+ di `" `cres' for continuous variables"'
+end
+program define _estadd_prchange_PostMat, eclass
+ syntax anything, name(str) [ Fromto eq(str) prefix(str) ///
+ pattern(passthru) binary(passthru) continuous(passthru) ]
+ capt confirm matrix `anything'
+ if _rc exit
+ tempname tmp1
+ local nmlist "`name'"
+ matrix `tmp1' = `anything'
+ if `"`eq'"'!="" {
+ mat coleq `tmp1' = `"`eq'"'
+ }
+ if `"`pattern'`binary'`continuous'"'!="" {
+ tempname pattmat
+ _estadd_prchange_Merge `tmp1', pattmat(`pattmat') `pattern' `binary' `continuous' `fromto'
+ }
+ if "`fromto'"!="" {
+ local nmlist "`nmlist' `name'from `name'to"
+ tempname tmp tmp2 tmp3
+ mat rename `tmp1' `tmp'
+ local r = rowsof(`tmp')
+ local i = 1
+ while (`i'<=`r') {
+ if (`r'-`i')>=2 {
+ mat `tmp2' = nullmat(`tmp2') \ `tmp'[`i++',1...] // from
+ mat `tmp3' = nullmat(`tmp3') \ `tmp'[`i++',1...] // to
+ }
+ mat `tmp1' = nullmat(`tmp1') \ `tmp'[`i++',1...]
+ }
+ mat drop `tmp'
+ }
+ local i 0
+ foreach nm of local nmlist {
+ local ++i
+ local rown: rown `tmp`i''
+ mat rown `tmp`i'' = `rown' // fix problem with leading blanks in equations
+ ereturn matrix `prefix'`nm' = `tmp`i''
+ added_matrix `prefix'`nm' _rown
+ }
+ if `"`pattmat'"'!="" {
+ ereturn matrix `prefix'pattern = `pattmat'
+ added_matrix `prefix'pattern
+ }
+end
+program define _estadd_prchange_Merge
+ syntax name(name=tmp1) [, pattmat(str) pattern(str) binary(str) continuous(str) fromto ]
+ tempname tmp
+ mat rename `tmp1' `tmp'
+ local r = cond("`fromto'"!="", 3, 1)
+ mat `tmp1' = `tmp'[1..`r',1...]*.
+ mat `pattmat' = `tmp'[1,1...]*.
+ local rtot = rowsof(`tmp')
+ mat rown `tmp1' = main
+ mat rown `pattmat' = :type
+ local vars: colnames `tmp1'
+ local eqs: coleq `tmp1', quoted
+ local j 0
+ foreach var of local vars {
+ local ++j
+ gettoken eq eqs : eqs
+ if `"`eq'"'!=`"`lasteq'"' gettoken type rest : pattern
+ else gettoken type rest : rest
+ local lasteq `"`eq'"'
+ if `"`type'"'=="" {
+ capt assert `var'==0|`var'==1 if e(sample) & `var'<.
+ if _rc local type `continuous'
+ else local type `binary'
+ }
+ local ii = (`type'-1)*`r'+1
+ forv i = 1/`r' {
+ if `r'>1 & `i'<3 & `ii'>=`rtot' {
+ mat `tmp1'[`i',`j'] = .z
+ }
+ else {
+ mat `tmp1'[`i',`j'] = `tmp'[`ii++',`j']
+ }
+ }
+ mat `pattmat'[1,`j'] = `type'
+ }
+ mat `tmp1' = `tmp1' \ `tmp'
+end
+program define _estadd_prchange_GatherNomChMat
+ args mat noavg
+ local cmd `"`e(cmd)'"'
+ tempname tmpmat
+ if `"`noavg'"'=="" {
+ mat `tmpmat' = r(changemn)
+ mat coleq `tmpmat' = `"Avg|Chg|"'
+ mat `mat' = `tmpmat'
+ }
+ if `"`cmd'"'=="mlogit" {
+ if c(stata_version) < 9 local outcat cat
+ else local outcat out
+ local k_cat = e(k_`outcat')
+ local eqnames `"`e(eqnames)'"'
+ if `k_cat'>`:list sizeof eqnames' { // no base equation
+ local ibase = e(ibase`outcat')
+ local baselab `"`e(baselab)'"'
+ if `"`baselab'"'=="" {
+ local baselab `"`e(base`outcat')'"'
+ }
+ forv i = 1/`k_cat' {
+ if `i'==`ibase' {
+ local eq `"`"`baselab'"'"'
+ }
+ else gettoken eq eqnames : eqnames, quotes
+ local temp `"`temp' `eq'"'
+ }
+ local eqnames: list retok temp
+ }
+ local i 0
+ foreach eq of local eqnames {
+ local ++i
+ local theoutcome: di el(e(`outcat'),1,`i')
+ mat `tmpmat' = r(change`theoutcome')
+ mat coleq `tmpmat' = `"`eq'"'
+ mat `mat' = nullmat(`mat'), `tmpmat'
+ }
+ }
+ else if `"`cmd'"'=="mprobit" {
+ local eqnames `"`e(outeqs)'"'
+ local i 0
+ foreach eq of local eqnames {
+ local ++i
+ local theoutcome: di el(e(outcomes),`i',1)
+ mat `tmpmat' = r(change`theoutcome')
+ mat coleq `tmpmat' = `"`eq'"'
+ mat `mat' = nullmat(`mat'), `tmpmat'
+ }
+ }
+ else { // ordered models
+ local eqnames : colnames r(catval)
+ local i 0
+ foreach eq of local eqnames {
+ local ++i
+ local theoutcome: di el(r(catval),1,`i')
+ mat `tmpmat' = r(change`theoutcome')
+ mat coleq `tmpmat' = `"`eq'"'
+ mat `mat' = nullmat(`mat'), `tmpmat'
+ }
+ }
+end
+program define _estadd_prchange_GetEqnmNomModl
+ args theoutcome
+ local cmd `"`e(cmd)'"'
+ if `"`cmd'"'=="mlogit" {
+ if c(stata_version) < 9 local outcat cat
+ else local outcat out
+ local k_cat = e(k_`outcat')
+ local eqnames `"`e(eqnames)'"'
+ local nobase = (`k_cat'>`:list sizeof eqnames')
+ if `nobase' {
+ local ibase = e(ibase`outcat')
+ local baselab `"`e(baselab)'"'
+ }
+ forv i = 1/`k_cat' {
+ if `nobase' {
+ if `i'==`ibase' {
+ local eq `"`baselab'"'
+ }
+ else gettoken eq eqnames : eqnames
+ }
+ else gettoken eq eqnames : eqnames
+ if el(e(`outcat'),1,`i')==`theoutcome' {
+ local value `"`eq'"'
+ continue, break
+ }
+ }
+ }
+ else if `"`cmd'"'=="mprobit" {
+ local eqnames `"`e(outeqs)'"'
+ local i 0
+ foreach eq of local eqnames {
+ if el(e(outcomes),`++i',1)==`theoutcome' {
+ local value `"`eq'"'
+ continue, break
+ }
+ }
+ }
+ if `"`value'"'=="" local value `theoutcome'
+ c_local eq `"`value'"'
+end
+program define _estadd_prchange_StoreEachOutc // only for nomord models
+ syntax anything [, nomord(str) nobase fromto prefix(passthru) ///
+ pattern(passthru) binary(passthru) continuous(passthru) ]
+// backup estimates
+ tempname hcurrent
+ _est hold `hcurrent', copy restore estsystem
+ if `"`nomord'"'=="2" { // backup b and V
+ tempname b bi V Vi
+ mat `b' = e(b)
+ mat `V' = e(V)
+ }
+// cycle through categories
+ local k_kat = colsof(r(predval))
+ tempname catval catvali
+ mat `catval' = r(catval)
+ forv i=1/`k_kat' {
+ mat `catvali' = `catval'[1...,`i']
+ local catlabi: colnames `catvali'
+ local catnumi: di `catvali'[1,1]
+ if `"`nomord'"'=="2" {
+ _estadd_prchange_GetEqnmNomModl `catnumi'
+ if colnumb(`b', `"`eq':"')<. {
+ mat `bi' = `b'[1...,`"`eq':"']
+ mat `Vi' = `V'[`"`eq':"',`"`eq':"']
+ }
+ else { // base outcome; get first eq and set zero
+ local tmp : coleq `b', q
+ gettoken tmp : tmp
+ mat `bi' = `b'[1...,`"`tmp':"'] * 0
+ mat `Vi' = `V'[`"`tmp':"',`"`tmp':"'] * 0
+ }
+ mat coleq `bi' = ""
+ mat coleq `Vi' = ""
+ mat roweq `Vi' = ""
+ erepost b=`bi' V=`Vi'
+ }
+ `qui' _estadd_prchange_AddStuffToE, nomord(1) outcome(`i') ///
+ `base' `fromto' `pattern' `binary' `continuous' `prefix'
+ `qui' di ""
+ local qui qui
+ _eststo `anything'`catnumi', title(`"`catlabi'"') // store without e(sample)
+ di as txt "results for outcome " as res `catnumi' ///
+ as txt " stored as " as res "`anything'`catnumi'"
+ }
+// retore estimates
+ _est unhold `hcurrent'
+end
+
+* 22.
+* -estadd- subroutine: support for -prvalue- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_prvalue, eclass
+ version 9.2
+ local caller : di _caller()
+ syntax [anything] [if] [in] [ , Prefix(passthru) Replace Quietly ///
+ LABel(str) Title(passthru) swap Diff * ]
+
+// post
+ if `"`anything'"'!="" {
+ gettoken post post2 : anything
+ if `"`post'"'!="post" {
+ di as err `"`post' not allowed"'
+ exit 198
+ }
+ else if `"`label'"'!="" {
+ di as err "label() not allowed"
+ exit 198
+ }
+ _estadd_prvalue_Post `post2' `if' `in', `prefix' `replace' `quietly' ///
+ `title' `swap' `diff' `options'
+ exit
+ }
+ else if `"`title'"'!="" {
+ di as err "title() not allowed"
+ exit 198
+ }
+ else if "`swap'"!="" {
+ di as err "swap not allowed"
+ exit 198
+ }
+
+// look for e(sample)
+ confirm_esample
+
+// run prvalue
+ capt findfile prvalue.ado
+ if _rc {
+ di as error "-prvalue- from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+ `quietly' version `caller': prvalue `if' `in', `diff' `options'
+
+// append?
+ capture confirm existence `e(_estadd_prvalue)'
+ local append = (_rc==0) & ("`replace'"=="")
+ tempname prvalue prvalue_x prvalue_x2
+ if `append' {
+ mat `prvalue' = e(_estadd_prvalue)
+ mat `prvalue_x' = e(_estadd_prvalue_x)
+ capt mat `prvalue_x2' = e(_estadd_prvalue_x2)
+ local ires = rowsof(`prvalue') + 1
+ }
+ else local ires 1
+ if `"`label'"'=="" {
+ local label "pred`ires'"
+ }
+ else {
+ local label = substr(`"`label'"', 1, 30) // 30 characters max
+ local problemchars `": . `"""'"'
+ foreach char of local problemchars {
+ local label: subinstr local label `"`char'"' "_", all
+ }
+ }
+
+// collect results
+ tempname pred
+ mat `pred' = r(pred)
+ if `"`diff'"'!="" {
+ _estadd_prvalue_GetRidOfD `pred'
+ }
+ _estadd_prvalue_ReshapePred `pred', label(`label')
+ _estadd_prvalue_AddPred `prvalue' `pred' `append'
+ _estadd_prvalue_AddX `prvalue_x', label(`label')
+ capture confirm matrix r(x2)
+ local hasx2 = _rc==0
+ if `hasx2' {
+ _estadd_prvalue_AddX `prvalue_x2', label(`label') two
+ }
+
+// post in e()
+ di as txt _n cond(`append',"updated","added") " matrices:"
+ ereturn matrix _estadd_prvalue = `prvalue'
+ added_matrix _estadd_prvalue
+ ereturn matrix _estadd_prvalue_x = `prvalue_x'
+ added_matrix _estadd_prvalue_x
+ if `hasx2' {
+ ereturn matrix _estadd_prvalue_x2 = `prvalue_x2'
+ added_matrix _estadd_prvalue_x2
+ }
+end
+program _estadd_prvalue_GetRidOfD
+ args pred
+ local coln: colnames `pred'
+ local firstcol: word 1 of `coln'
+ local nfirstcol = substr("`firstcol'",2,.)
+ local coln : subinstr local coln "`firstcol'" "`nfirstcol'" , word
+ mat coln `pred' = `coln'
+end
+program _estadd_prvalue_ReshapePred
+ syntax anything, label(str)
+ tempname tmp res
+ local r = rowsof(`anything')
+ forv i=1/`r' {
+ mat `tmp' = `anything'[`i',1...]
+ local nm: rownames `tmp'
+ mat coleq `tmp' = `"`nm'"'
+ mat `res' = nullmat(`res'), `tmp'
+ }
+ mat rown `res' = `"`label'"'
+ mat `anything' = `res'
+end
+program _estadd_prvalue_AddPred
+ args prvalue pred append
+ if `append' {
+ local coln1: colfullnames `prvalue'
+ local coln2: colfullnames `pred'
+ if `"`coln1'"'!=`"`coln2'"' {
+ di as err "incompatible prvalue results"
+ exit 498
+ }
+ }
+ mat `prvalue' = nullmat(`prvalue') \ `pred'
+end
+program _estadd_prvalue_AddX
+ syntax anything, label(str) [ two ]
+ if "`two'"!="" local two 2
+ tempname tmp
+ mat `tmp' = r(x`two')
+ mat rown `tmp' = `"`label'"'
+ mat `anything' = nullmat(`anything') \ `tmp'
+end
+program _estadd_prvalue_Post, eclass
+ syntax [name(name=post2)] [ , Prefix(name) Replace Quietly ///
+ Title(passthru) swap ]
+ capture confirm matrix e(_estadd_prvalue)
+ if _rc {
+ di as err "prvalue results not found"
+ exit 498
+ }
+// backup estimates
+ tempname hcurrent
+ _est hold `hcurrent', copy restore estsystem
+ local cmd = e(cmd)
+ local depvar = e(depvar)
+ local N = e(N)
+ local estname `"`e(_estadd_estimates_name)'"'
+
+// get results
+ tempname prvalue prvalue_x prvalue_x2
+ mat `prvalue' = e(_estadd_prvalue)
+ mat `prvalue_x' = e(_estadd_prvalue_x)
+ capture confirm matrix e(_estadd_prvalue_x2)
+ local hasx2 = _rc==0
+ if `hasx2' {
+ mat `prvalue_x2' = e(_estadd_prvalue_x2)
+ }
+
+// return prvalues
+ tempname tmp tmp2 b se
+ if "`swap'"=="" {
+ local eqs: coleq `prvalue', q
+ local eqs: list uniq eqs
+ foreach eq of local eqs {
+ mat `tmp' = `prvalue'[1...,`"`eq':"']
+ mat `tmp2' = `tmp'[1...,1]'
+ mat coleq `tmp2' = `"`eq'"'
+ mat roweq `tmp2' = ""
+ mat `b' = nullmat(`b'), `tmp2'
+ mat `tmp2' = `tmp'[1...,`"`eq':SE"']'
+ mat coleq `tmp2' = `"`eq'"'
+ mat roweq `tmp2' = ""
+ mat `se' = nullmat(`se'), `tmp2'
+ }
+ mat drop `tmp' `tmp2'
+ }
+ else {
+ local r = rowsof(`prvalue')
+ local c = colsof(`prvalue')
+ local coln: colnames `prvalue'
+ local eqs: coleq `prvalue', q
+ mat coln `prvalue' = `eqs'
+ mat coleq `prvalue' = `coln'
+ local coln: list uniq coln
+ local ncol: list sizeof coln
+ local icol: list posof "SE" in coln
+ forv i=1/`r' {
+ mat `tmp' = `prvalue'[`i',1...]
+ local labl : rownames `tmp'
+ forv j=1(`ncol')`c' {
+ mat `tmp2' = nullmat(`tmp2'), `tmp'[1...,`j']
+ }
+ mat coleq `tmp2' = `"`labl'"'
+ mat `b' = nullmat(`b'), `tmp2'
+ mat drop `tmp2'
+ forv j=`icol'(`ncol')`c' {
+ mat `tmp2' = nullmat(`tmp2'), `tmp'[1...,`j']
+ }
+ mat coleq `tmp2' = `"`labl'"'
+ mat `se' = nullmat(`se'), `tmp2'
+ mat drop `tmp2'
+ }
+ mat drop `tmp'
+ }
+ ereturn post `b', obs(`N')
+ ereturn local model "`cmd'"
+ ereturn local cmd "estadd_prvalue"
+ ereturn local depvar "`depvar'"
+ di as txt _n "scalars:"
+ added_scalar N
+ di as txt _n "macros:"
+ added_macro depvar
+ added_macro cmd
+ added_macro model
+ added_macro properties
+ di as txt _n "matrices:"
+ added_matrix b "predictions"
+ ereturn matrix se = `se'
+ added_matrix se "standard errors"
+ local istat 0
+ foreach stat in LB UB Category Cond {
+ local elabel: word `++istat' of "lower CI bounds" "upper CI bounds" ///
+ "outcome values" "conditional predictions"
+ if "`swap'"=="" {
+ foreach eq of local eqs {
+ local colnumb = colnumb(`prvalue',`"`eq':`stat'"')
+ if `colnumb'>=. continue
+ mat `tmp2' = `prvalue'[1...,`colnumb']'
+ mat coleq `tmp2' = `"`eq'"'
+ mat roweq `tmp2' = ""
+ mat `tmp' = nullmat(`tmp'), `tmp2'
+ }
+ }
+ else {
+ local icol: list posof "`stat'" in coln
+ if `icol'==0 continue
+ forv i=1/`r' {
+ mat `tmp2' = `prvalue'[`i',1...]
+ local labl : rownames `tmp2'
+ mat coleq `tmp2' = `"`labl'"'
+ forv j=`icol'(`ncol')`c' {
+ mat `tmp' = nullmat(`tmp'), `tmp2'[1...,`j']
+ }
+ }
+ mat drop `tmp2'
+ }
+ capt confirm matrix `tmp'
+ if _rc==0 {
+ ereturn matrix `prefix'`stat' = `tmp'
+ added_matrix `prefix'`stat' "`elabel'"
+ }
+ }
+
+// return x-values
+ matrix `prvalue_x' = `prvalue_x''
+ ereturn matrix `prefix'X = `prvalue_x'
+ added_matrix `prefix'X _rown
+ if `hasx2' {
+ matrix `prvalue_x2' = `prvalue_x2''
+ ereturn matrix `prefix'X2 = `prvalue_x2'
+ added_matrix `prefix'X2 _rown
+ }
+
+// store
+ if "`post2'"!="" {
+ _eststo `estname'`post2', `title'
+ di as txt _n "results stored as " as res "`estname'`post2'"
+ }
+ else if `"`title'"'!="" {
+ estimates change ., `title'
+ }
+
+// retore estimates
+ if "`post2'"!="" {
+ _est unhold `hcurrent'
+ }
+ else {
+ _est unhold `hcurrent', not
+ }
+end
+
+* 23.
+* -estadd- subroutine: support for -asprvalue- by Long and Freese
+* (see http://www.indiana.edu/~jslsoc/spost.htm)
+program define estadd_asprvalue, eclass
+ version 9.2
+ local caller : di _caller()
+ syntax [anything] [ , Prefix(passthru) Replace Quietly ///
+ LABel(str) Title(passthru) swap * ]
+
+// post
+ if `"`anything'"'!="" {
+ gettoken post post2 : anything
+ if `"`post'"'!="post" {
+ di as err `"`post' not allowed"'
+ exit 198
+ }
+ else if `"`label'"'!="" {
+ di as err "label() not allowed"
+ exit 198
+ }
+ _estadd_asprvalue_Post `post2' , `prefix' `replace' `quietly' ///
+ `title' `swap' `options'
+ exit
+ }
+ else if `"`title'"'!="" {
+ di as err "title() not allowed"
+ exit 198
+ }
+ else if "`swap'"!="" {
+ di as err "swap not allowed"
+ exit 198
+ }
+
+// look for e(sample)
+ confirm_esample
+
+// run prvalue
+ capt findfile asprvalue.ado
+ if _rc {
+ di as error "-asprvalue- from the -spost9_ado- package by Long and Freese required"
+ di as error `"type {stata "net from http://www.indiana.edu/~jslsoc/stata"}"'
+ error 499
+ }
+ `quietly' version `caller': asprvalue , `options'
+
+// append?
+ capture confirm existence `e(_estadd_asprval)'
+ local append = (_rc==0) & ("`replace'"=="")
+ tempname asprval asprval_asv asprval_csv
+ if `append' {
+ mat `asprval' = e(_estadd_asprval)
+ capt mat `asprval_asv' = e(_estadd_asprval_asv)
+ capt mat `asprval_csv' = e(_estadd_asprval_csv)
+ local ires = rowsof(`asprval') + 1
+ }
+ else local ires 1
+ if `"`label'"'=="" {
+ local label "pred`ires'"
+ }
+ else {
+ local label = substr(`"`label'"', 1, 30) // 30 characters max
+ local problemchars `": . `"""'"'
+ foreach char of local problemchars {
+ local label: subinstr local label `"`char'"' "_", all
+ }
+ }
+
+// collect results
+ tempname res
+ mat `res' = r(p)
+ _estadd_asprvalue_Reshape `res', label(`label')
+ _estadd_asprvalue_Add `asprval' `res' `append'
+ capture confirm matrix r(asv)
+ local hasasv = _rc==0
+ if `hasasv' {
+ mat `res' = r(asv)
+ _estadd_asprvalue_Reshape `res', label(`label')
+ _estadd_asprvalue_Add `asprval_asv' `res' `append'
+ }
+ capture confirm matrix r(csv)
+ local hascsv = _rc==0
+ if `hascsv' {
+ _estadd_asprvalue_AddCsv `asprval_csv', label(`label')
+ }
+
+// post in e()
+ di as txt _n cond(`append',"updated","added") " matrices:"
+ ereturn matrix _estadd_asprval = `asprval'
+ added_matrix _estadd_asprval
+ if `hasasv' {
+ ereturn matrix _estadd_asprval_asv = `asprval_asv'
+ added_matrix _estadd_asprval_asv
+ }
+ if `hascsv' {
+ ereturn matrix _estadd_asprval_csv = `asprval_csv'
+ added_matrix _estadd_asprval_csv
+ }
+end
+program _estadd_asprvalue_Reshape
+ syntax anything, label(str)
+ tempname tmp res
+ local r = rowsof(`anything')
+ forv i=1/`r' {
+ mat `tmp' = `anything'[`i',1...]
+ local nm: rownames `tmp'
+ mat coleq `tmp' = `"`nm'"'
+ mat `res' = nullmat(`res'), `tmp'
+ }
+ mat rown `res' = `"`label'"'
+ mat `anything' = `res'
+end
+program _estadd_asprvalue_Add
+ args master using append
+ if `append' {
+ local coln1: colfullnames `master'
+ local coln2: colfullnames `using'
+ if `"`coln1'"'!=`"`coln2'"' {
+ di as err "incompatible asprvalue results"
+ exit 498
+ }
+ }
+ mat `master' = nullmat(`master') \ `using'
+end
+program _estadd_asprvalue_AddCsv
+ syntax anything, label(str)
+ tempname tmp
+ mat `tmp' = r(csv)
+ mat rown `tmp' = `"`label'"'
+ mat `anything' = nullmat(`anything') \ `tmp'
+end
+program _estadd_asprvalue_Post, eclass
+ syntax [name(name=post2)] [ , Prefix(name) Replace Quietly ///
+ Title(passthru) swap ]
+ capture confirm matrix e(_estadd_asprval)
+ if _rc {
+ di as err "asprvalue results not found"
+ exit 498
+ }
+
+// backup estimates
+ tempname hcurrent
+ _est hold `hcurrent', copy restore estsystem
+ local cmd = e(cmd)
+ local depvar = e(depvar)
+ local N = e(N)
+ local estname `"`e(_estadd_estimates_name)'"'
+
+// get results
+ tempname asprval asprval_asv asprval_csv
+ mat `asprval' = e(_estadd_asprval)
+ capture confirm matrix e(_estadd_asprval_asv)
+ local hasasv = _rc==0
+ if `hasasv' {
+ mat `asprval_asv' = e(_estadd_asprval_asv)
+ }
+ capture confirm matrix e(_estadd_asprval_csv)
+ local hascsv = _rc==0
+ if `hascsv' {
+ mat `asprval_csv' = e(_estadd_asprval_csv)
+ }
+
+// return predictions
+ tempname tmp tmp2 b
+ if "`swap'"=="" {
+ local eqs: coleq `asprval', q
+ local eqs: list uniq eqs
+ foreach eq of local eqs {
+ mat `tmp' = `asprval'[1...,`"`eq':"']
+ mat `tmp2' = `tmp'[1...,1]'
+ mat coleq `tmp2' = `"`eq'"'
+ mat roweq `tmp2' = ""
+ mat `b' = nullmat(`b'), `tmp2'
+ }
+ mat drop `tmp' `tmp2'
+ }
+ else {
+ local r = rowsof(`asprval')
+ local coln: colnames `asprval'
+ local eqs: coleq `asprval', q
+ mat coln `asprval' = `eqs'
+ forv i=1/`r' {
+ mat `tmp' = `asprval'[`i',1...]
+ local labl : rownames `tmp'
+ mat coleq `tmp' = `"`labl'"'
+ mat `b' = nullmat(`b'), `tmp'
+ }
+ mat drop `tmp'
+ }
+ ereturn post `b', obs(`N')
+ ereturn local model "`cmd'"
+ ereturn local cmd "estadd_asprvalue"
+ ereturn local depvar "`depvar'"
+ di as txt _n "scalars:"
+ added_scalar N
+ di as txt _n "macros:"
+ added_macro depvar
+ added_macro cmd
+ added_macro model
+ added_macro properties
+ di as txt _n "matrices:"
+ added_matrix b "predictions"
+
+// return asv-values
+ if `hasasv' {
+ if "`swap'"=="" {
+ local vars: coleq `asprval_asv'
+ local vars: list uniq vars
+ local cats: colnames `asprval_asv'
+ local cats: list uniq cats
+ foreach var of local vars {
+ foreach cat of local cats {
+ mat `tmp2' = `asprval_asv'[1...,`"`var':`cat'"']'
+ mat coleq `tmp2' = `"`cat'"'
+ mat roweq `tmp2' = ""
+ mat `tmp' = nullmat(`tmp'), `tmp2'
+ }
+ mat rown `tmp' = `"`var'"'
+ mat `b' = nullmat(`b') \ `tmp'
+ mat drop `tmp'
+ }
+ }
+ else {
+ local r = rowsof(`asprval_asv')
+ local vars: coleq `asprval_asv'
+ local vars: list uniq vars
+ forv i=1/`r' {
+ foreach var of local vars {
+ mat `tmp2' = `asprval_asv'[`i',`"`var':"']
+ local lbl: rownames `tmp2'
+ mat coleq `tmp2' = `"`lbl'"'
+ mat rown `tmp2' = `"`var'"'
+ mat `tmp' = nullmat(`tmp') \ `tmp2'
+ }
+ mat `b' = nullmat(`b') , `tmp'
+ mat drop `tmp'
+ }
+ }
+ ereturn matrix `prefix'asv = `b'
+ added_matrix `prefix'asv _rown
+ }
+// return csv-values
+ if `hascsv' {
+ matrix `asprval_csv' = `asprval_csv''
+ ereturn matrix `prefix'csv = `asprval_csv'
+ added_matrix `prefix'csv _rown
+ }
+
+// store
+ if "`post2'"!="" {
+ _eststo `estname'`post2', `title'
+ di as txt _n "results stored as " as res "`estname'`post2'"
+ }
+ else if `"`title'"'!="" {
+ estimates change ., `title'
+ }
+
+// retore estimates
+ if "`post2'"!="" {
+ _est unhold `hcurrent'
+ }
+ else {
+ _est unhold `hcurrent', not
+ }
+end
+
+* 24. estadd_margins
+program define estadd_margins, eclass
+ version 11.0
+ local caller : di _caller()
+ syntax [ anything(everything equalok)] [fw aw iw pw] [, Prefix(name) Replace Quietly * ]
+
+// set default prefix
+ if "`prefix'"=="" local prefix "margins_"
+
+// compute and return the results
+ if `"`weight'`exp'"'!="" local wgtexp `"[`weight'`exp']"'
+ `quietly' version `caller': margins `anything' `wgtexp', `options'
+
+// check names
+ local rscalars: r(scalars)
+ local rmacros: r(macros)
+ local rmatrices: r(matrices)
+ local rmatrices: subinstr local rmatrices "V" "se", word
+ if "`replace'"=="" {
+ foreach nmlist in rscalars rmacros rmatrices {
+ foreach name of local `nmlist' {
+ confirm_new_ename `prefix'`name'
+ }
+ }
+ }
+
+// add results
+ di as txt _n "added scalars:"
+ foreach name of local rscalars {
+ ereturn scalar `prefix'`name' = r(`name')
+ added_scalar `prefix'`name'
+ }
+ di as txt _n "added macros:"
+ foreach name of local rmacros {
+ ereturn local `prefix'`name' `"`r(`name')'"'
+ added_macro `prefix'`name'
+ }
+ di as txt _n "added matrices:"
+ tempname tmpmat
+ foreach name of local rmatrices {
+ if "`name'"=="se" {
+ mat `tmpmat' = vecdiag(r(V))
+ forv i = 1/`=colsof(`tmpmat')' {
+ mat `tmpmat'[1,`i'] = sqrt(`tmpmat'[1,`i'])
+ }
+ }
+ else {
+ mat `tmpmat' = r(`name')
+ }
+ eret matrix `prefix'`name' = `tmpmat'
+ added_matrix `prefix'`name'
+ }
+end
+
+* 99.
+* copy of erepost.ado, version 1.0.1, Ben Jann, 30jul2007
+* used by estadd_listcoef and estadd_prchange
+prog erepost, eclass
+ version 8.2
+ syntax [anything(equalok)] [, cmd(str) noEsample Esample2(varname) REName ///
+ Obs(passthru) Dof(passthru) PROPerties(passthru) * ]
+ if "`esample'"!="" & "`esample2'"!="" {
+ di as err "only one allowed of noesample and esample()"
+ exit 198
+ }
+// parse [b = b] [V = V]
+ if `"`anything'"'!="" {
+ tokenize `"`anything'"', parse(" =")
+ if `"`7'"'!="" error 198
+ if `"`1'"'=="b" {
+ if `"`2'"'=="=" & `"`3'"'!="" {
+ local b `"`3'"'
+ confirm matrix `b'
+ }
+ else error 198
+ if `"`4'"'=="V" {
+ if `"`5'"'=="=" & `"`6'"'!="" {
+ local v `"`6'"'
+ confirm matrix `b'
+ }
+ else error 198
+ }
+ else if `"`4'"'!="" error 198
+ }
+ else if `"`1'"'=="V" {
+ if `"`4'"'!="" error 198
+ if `"`2'"'=="=" & `"`3'"'!="" {
+ local v `"`3'"'
+ confirm matrix `v'
+ }
+ else error 198
+ }
+ else error 198
+ }
+//backup existing e()'s
+ if "`esample2'"!="" {
+ local sample "`esample2'"
+ }
+ else if "`esample'"=="" {
+ tempvar sample
+ gen byte `sample' = e(sample)
+ }
+ local emacros: e(macros)
+ if `"`properties'"'!="" {
+ local emacros: subinstr local emacros "properties" "", word
+ }
+ foreach emacro of local emacros {
+ local e_`emacro' `"`e(`emacro')'"'
+ }
+ local escalars: e(scalars)
+ if `"`obs'"'!="" {
+ local escalars: subinstr local escalars "N" "", word
+ }
+ if `"`dof'"'!="" {
+ local escalars: subinstr local escalars "df_r" "", word
+ }
+ foreach escalar of local escalars {
+ tempname e_`escalar'
+ scalar `e_`escalar'' = e(`escalar')
+ }
+ local ematrices: e(matrices)
+ if "`b'"=="" & `:list posof "b" in ematrices' {
+ tempname b
+ mat `b' = e(b)
+ }
+ if "`v'"=="" & `:list posof "V" in ematrices' {
+ tempname v
+ mat `v' = e(V)
+ }
+ local bV "b V"
+ local ematrices: list ematrices - bV
+ foreach ematrix of local ematrices {
+ tempname e_`ematrix'
+ matrix `e_`ematrix'' = e(`ematrix')
+ }
+// rename
+ if "`b'"!="" & "`v'"!="" & "`rename'"!="" {
+ local eqnames: coleq `b', q
+ local vnames: colnames `b'
+ mat coleq `v' = `eqnames'
+ mat coln `v' = `vnames'
+ mat roweq `v' = `eqnames'
+ mat rown `v' = `vnames'
+ }
+// post results
+ if "`esample'"=="" {
+ eret post `b' `v', esample(`sample') `obs' `dof' `properties' `options'
+ }
+ else {
+ eret post `b' `v', `obs' `dof' `properties' `options'
+ }
+ foreach emacro of local emacros {
+ eret local `emacro' `"`e_`emacro''"'
+ }
+ if `"`cmd'"'!="" {
+ eret local cmd `"`cmd'"'
+ }
+ foreach escalar of local escalars {
+ eret scalar `escalar' = scalar(`e_`escalar'')
+ }
+ foreach ematrix of local ematrices {
+ eret matrix `ematrix' = `e_`ematrix''
+ }
+end
diff --git a/Modules/ado/plus/e/estadd.hlp b/Modules/ado/plus/e/estadd.hlp
new file mode 100644
index 0000000..b9b1f16
--- /dev/null
+++ b/Modules/ado/plus/e/estadd.hlp
@@ -0,0 +1,935 @@
+{smcl}
+{* 08oct2009}{...}
+{hi:help estadd}{right:also see: {helpb esttab}, {helpb estout}, {helpb eststo}, {helpb estpost}}
+{right: {browse "http://repec.org/bocode/e/estout"}}
+{hline}
+
+{title:Title}
+
+{p 4 4 2}{hi:estadd} {hline 2} Add results to (stored) estimates
+
+
+{title:Syntax}
+
+{p 8 15 2}
+{cmd:estadd} {it:{help estadd##subcommands:subcommand}} [{cmd:,}
+{it:{help estadd##opts:options}} ] [ {cmd::} {it:namelist} ]
+
+
+ where {it:namelist} is {cmd:_all} | {cmd:*} | {it:name} [{it:name} ...]
+
+{marker subcommands}
+ {it:subcommands}{col 26}description
+ {hline 64}
+ Elementary
+ {helpb estadd##local:{ul:loc}al} {it:name ...}{col 26}{...}
+add a macro
+ {helpb estadd##scalar:{ul:sca}lar} {it:name} {cmd:=} {it:exp}{col 26}{...}
+add a scalar
+ {helpb estadd##matrix:{ul:mat}rix} {it:name} {cmd:=} {it:mat}{col 26}{...}
+add a matrix
+ {helpb estadd##rreturn:r({it:name})}{col 26}{...}
+add contents of {cmd:r(}{it:name}{cmd:)} (matrix or scalar)
+
+ Statistics for each
+ coefficient
+ {helpb estadd##beta:beta}{col 26}{...}
+standardized coefficients
+ {helpb estadd##vif:vif}{col 26}{...}
+variance inflation factors (after {cmd:regress})
+ {helpb estadd##pcorr:pcorr}{col 26}{...}
+partial (and semi-partial) correlations
+ {helpb estadd##expb:expb}{col 26}{...}
+exponentiated coefficients
+ {helpb estadd##ebsd:ebsd}{col 26}{...}
+standardized factor change coefficients
+ {helpb estadd##mean:mean}{col 26}{...}
+means of regressors
+ {helpb estadd##sd:sd}{col 26}{...}
+standard deviations of regressors
+ {helpb estadd##summ:summ}{col 26}{...}
+various descriptives of the regressors
+
+ Summary statistics
+ {helpb estadd##coxsnell:coxsnell}{col 26}{...}
+Cox & Snell's pseudo R-squared
+ {helpb estadd##nagelkerke:nagelkerke}{col 26}{...}
+Nagelkerke's pseudo R-squared
+ {helpb estadd##lrtest:lrtest} {it:model}{col 26}{...}
+likelihood-ratio test
+ {helpb estadd##ysumm:ysumm}{col 26}{...}
+descriptives of the dependent variable
+
+ Other
+ {helpb estadd##margins:margins}{col 26}{...}
+add results from {cmd:margins} (Stata 11)
+
+ {help estadd##spost:SPost}
+ {helpb estadd##brant:brant}{col 26}{...}
+add results from {cmd:brant} (if installed)
+ {helpb estadd##fitstat:fitstat}{col 26}{...}
+add results from {cmd:fitstat} (if installed)
+ {helpb estadd##listcoef:listcoef}{col 26}{...}
+add results from {cmd:listcoef} (if installed)
+ {helpb estadd##mlogtest:mlogtest}{col 26}{...}
+add results from {cmd:mlogtest} (if installed)
+ {helpb estadd##prchange:prchange}{col 26}{...}
+add results from {cmd:prchange} (if installed)
+ {helpb estadd##prvalue:prvalue}{col 26}{...}
+add results from {cmd:prvalue} (if installed)
+ {helpb estadd##asprvalue:asprvalue}{col 26}{...}
+add results from {cmd:asprvalue} (if installed)
+ {hline 64}
+
+{marker opts}
+ {it:{help estadd##options:options}}{col 26}description
+ {hline 64}
+ {cmdab:r:eplace}{col 26}{...}
+permit overwriting existing {cmd:e()}'s
+ {cmdab:p:refix(}{it:string}{cmd:)}{col 26}{...}
+specify prefix for names of added results
+ {cmdab:q:uietly}{col 26}{...}
+suppress output from subcommand (if any)
+ {it:subcmdopts}{col 26}{...}
+subcommand specific options
+ {hline 64}
+
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:estadd} adds additional results to the {cmd:e()}-returns of an
+estimation command (see help {help estcom}, help {helpb ereturn}). If no
+{it:namelist} is provided, then the results are added to the
+currently active estimates (i.e. the model fit last). If these
+estimates have been previously stored, the stored copy of the
+estimates will also be modified. Alternatively, if {it:namelist} is
+provided after the colon, results are added to all indicated sets of
+stored estimates (see help {helpb estimates store} or help
+{helpb eststo}). You may use the {cmd:*} and {cmd:?}
+wildcards in {it:namelist}. Execution is silent if {it:namelist} is
+provided.
+
+{p 4 4 2}
+Adding additional results to the {cmd:e()}-returns is useful, for example,
+if the estimates be tabulated by commands such as {helpb estout}
+or {helpb esttab}. See the {help estadd##examples:Examples} section below for
+illustration of the usage of {cmd:estadd}.
+
+{p 4 4 2}Technical note: Some of the subcommands below make use of the
+information contained in {cmd:e(sample)} to determine estimation sample.
+These subcommands return error if the estimates do not contain
+{cmd:e(sample)}.
+
+
+{title:Subcommands}
+
+{dlgtab:Elementary}
+{marker local}
+{p 4 8 2}
+{cmd:estadd} {cmdab:loc:al} {it:name ...}
+
+{p 8 8 2}
+adds in macro {cmd:e(}{it:name}{cmd:)} the specified contents (also
+see help {helpb ereturn}).
+
+{marker scalar}
+{p 4 8 2}
+{cmd:estadd} {cmdab:sca:lar} {it:name} {cmd:=} {it:exp}
+
+{p 8 8 2}
+adds in scalar {cmd:e(}{it:name}{cmd:)} the evaluation of {it:exp}
+(also see help {helpb ereturn}).
+
+{p 4 8 2}
+{cmd:estadd} {cmdab:sca:lar} {cmd:r(}{it:name}{cmd:)}
+
+{p 8 8 2}
+adds in scalar {cmd:e(}{it:name}{cmd:)} the value of scalar {cmd:r(}{it:name}{cmd:)}.
+
+{p 4 8 2}
+{cmd:estadd} {cmdab:sca:lar} {it:name}
+
+{p 8 8 2}
+adds in scalar {cmd:e(}{it:name}{cmd:)} the the value of scalar {it:name}.
+
+{marker matrix}
+{p 4 8 2}
+{cmd:estadd} {cmdab:mat:rix} {it:name} {cmd:=} {it:matrix_expression}
+
+{p 8 8 2}
+adds in matrix {cmd:e(}{it:name}{cmd:)} the evaluation of {it:matrix_expression}
+(also see help {helpb matrix define}).
+
+{p 4 8 2}
+{cmd:estadd} {cmdab:mat:rix} {cmd:r(}{it:name}{cmd:)}
+
+{p 8 8 2}
+adds in matrix {cmd:e(}{it:name}{cmd:)} a copy of matrix {cmd:r(}{it:name}{cmd:)}.
+
+{p 4 8 2}
+{cmd:estadd} {cmdab:mat:rix} {it:name}
+
+{p 8 8 2}
+adds in matrix {cmd:e(}{it:name}{cmd:)} a copy of matrix {it:name}.
+
+{marker rreturn}
+{p 4 8 2}
+{cmd:estadd} {cmd:r(}{it:name}{cmd:)}
+
+{p 8 8 2}
+adds in {cmd:e(}{it:name}{cmd:)} the value of scalar {cmd:r(}{it:name}{cmd:)}
+or a copy of matrix {cmd:r(}{it:name}{cmd:)}, depending on the nature of
+{cmd:r(}{it:name}{cmd:)}.
+
+
+{dlgtab:Statistics for each coefficient}
+{marker beta}
+{p 4 8 2}
+{cmd:estadd} {cmd:beta}
+
+{p 8 8 2}
+adds in {cmd:e(beta)} the standardized beta coefficients.
+
+{marker vif}
+{p 4 8 2}
+{cmd:estadd} {cmd:vif} [{cmd:,} {cmdab:tol:erance} {cmdab:sqr:vif} ]
+
+{p 8 8 2}
+adds in {cmd:e(vif)} the variance inflation factors (VIFs) for the
+regressors (see help {helpb vif}). Note that {cmd:vif} only works
+with estimates produced by {helpb regress}. {cmd:tolerance}
+additionally adds the tolerances (1/VIF) in {cmd:e(tolerance)}.
+{cmd:sqrvif} additionally adds the square roots of the VIFs in
+{cmd:e(sqrvif)}.
+
+{marker pcorr}
+{p 4 8 2}
+{cmd:estadd} {cmd:pcorr} [{cmd:, semi} ]
+
+{p 8 8 2}
+adds the partial correlations (see help {helpb pcorr}) and,
+optionally, the semi-partial correlations between the dependent
+variable and the individual regressors (see, e.g., the {cmd:pcorr2}
+package from the SSC Archive). In the case of multiple-equations
+models, the results are computed for the first equation only. The
+partial correlations will be returned in {cmd:e(pcorr)} and, if
+{cmd:semi} is specified, the semi-partial correlations will be
+returned in {cmd:e(spcorr)}.
+
+{marker expb}
+{p 4 8 2}
+{cmd:estadd} {cmd:expb} [{cmd:,} {cmdab:nocons:tant} ]
+
+{p 8 8 2}
+adds in {cmd:e(expb)} the exponentiated coefficients (see the help
+{it:{help eform_option}}). {cmd:noconstant} excludes the constant
+from the added results.
+
+{marker ebsd}
+{p 4 8 2}
+{cmd:estadd} {cmd:ebsd}
+
+{p 8 8 2}
+adds in {cmd:e(ebsd)} the standardized factor change coefficients,
+i.e. exp(b_jS_j), where b_j is the raw coefficient and S_j is the
+standard deviation of regressor j, that are sometimes reported for
+logistic regression (see Long 1997).
+
+{marker mean}
+{p 4 8 2}
+{cmd:estadd} {cmd:mean}
+
+{p 8 8 2}
+adds in {cmd:e(mean)} the means of the regressors.
+
+{marker sd}
+{p 4 8 2}
+{cmd:estadd} {cmd:sd} [{cmd:,} {cmdab:nob:inary} ]
+
+{p 8 8 2}
+adds in {cmd:e(sd)} the standard deviations of the regressors.
+{cmd:nobinary} suppresses the computation of the standard deviation
+for 0/1 variables.
+
+{marker summ}
+{p 4 8 2}
+{cmd:estadd} {cmd:summ} [{cmd:,} {it:stats} ]
+
+{p 8 8 2}
+adds vectors of the regressors' descriptive statistics to the
+estimates. The following {it:stats} are available:
+{p_end}
+{marker stats}
+ {it:stats}{col 26}description
+ {hline 59}
+ {cmdab:me:an}{col 26}mean
+ {cmdab:su:m}{col 26}sum
+ {cmdab:mi:n}{col 26}minimum
+ {cmdab:ma:x}{col 26}maximum
+ {cmdab:ra:nge}{col 26}range = max - min
+ {cmd:sd}{col 26}standard deviation
+ {cmdab:v:ar}{col 26}variance
+ {cmd:cv}{col 26}coefficient of variation (sd/mean)
+ {cmdab:sem:ean}{col 26}standard error of mean = sd/sqrt(n)
+ {cmdab:sk:ewness}{col 26}skewness
+ {cmdab:k:urtosis}{col 26}kurtosis
+ {cmd:p1}{col 26}1st percentile
+ {cmd:p5}{col 26}5th percentile
+ {cmd:p10}{col 26}10th percentile
+ {cmd:p25}{col 26}25th percentile
+ {cmd:p50}{col 26}50th percentile
+ {cmd:p75}{col 26}75th percentile
+ {cmd:p90}{col 26}90th percentile
+ {cmd:p95}{col 26}95th percentile
+ {cmd:p99}{col 26}99th percentile
+ {cmd:iqr}{col 26}interquartile range = p75 - p25
+ {cmd:all}{col 26}all of the above
+ {cmdab:med:ian}{col 26}equivalent to specifying "{cmd:p50}"
+ {cmd:q}{col 26}equivalent to specifying "{cmd:p25 p50 p75}"
+ {hline 59}
+
+{p 8 8 2}
+The default is {cmd:mean sd min max}. Alternatively, indicate the
+desired statistics. For example, to add information on the
+regressors' skewness and kurtosis, type
+
+ {inp:. estadd summ, skewness kurtosis}
+
+{p 8 8 2}
+The statistics names are used as the names for the returned {cmd:e()}
+matrices. For example, {cmd:estadd summ, mean} will store the means
+of the regressors in {cmd:e(mean)}.
+
+
+{dlgtab:Summary statistics}
+{marker coxsnell}
+{p 4 8 2}
+{cmd:estadd} {cmd:coxsnell}
+
+{p 8 8 2}
+adds in {cmd:e(coxsnell)} the Cox & Snell pseudo R-squared, which is
+defined as
+
+{p 12 12 2}
+r2_coxsnell = 1 - ( L0 / L1 )^(2/N)
+
+{p 8 8 2}
+where L0 is the likelihood of the model without regressors, L1 the
+likelihood of the full model, and N is the sample size.
+
+{marker nagelkerke}
+{p 4 8 2}
+{cmd:estadd} {cmd:nagelkerke}
+
+{p 8 8 2}
+adds in {cmd:e(nagelkerke)} the Nagelkerke pseudo R-squared (or Cragg
+& Uhler pseudo R-squared), which is defined as
+
+{p 12 12 2}
+r2_nagelkerke = r2_coxsnell / (1 - L0^(2/N))
+
+{marker lrtest}
+{p 4 8 2}
+{cmd:estadd} {cmd:lrtest} {it:model} [{cmd:,} {cmdab:n:ame:(}{it:string}{cmd:)}
+{it:{help lrtest:lrtest_options}} ]
+
+{p 8 8 2}
+adds the results from a likelihood-ratio test, where {it:model} is
+the comparison model (see help {helpb lrtest}). Added are
+{cmd:e(lrtest_chi2)}, {cmd:e(lrtest_df)}, and {cmd:e(lrtest_p)}. The
+names may be modified using the {cmd:name()} option. Specify
+{cmd:name(}{it:myname}{cmd:)} to add {cmd:e(}{it:myname}{cmd:chi2)},
+{cmd:e(}{it:myname}{cmd:df)}, and {cmd:e(}{it:myname}{cmd:p)}. See
+help {helpb lrtest} for the {it:lrtest_options}.
+
+{marker ysumm}
+{p 4 8 2}
+{cmd:estadd} {cmd:ysumm} [{cmd:,} {it:stats} ]
+
+{p 8 8 2}
+adds descriptive statistics of the dependent variable. See the
+{helpb estadd##summ:summ} subcommand above for a list of the available
+{it:stats}. The default is {cmd:mean sd min max}. The default prefix
+for the names of the added scalars is {cmd:y} (e.g. the mean of the
+dependent variable will be returned in {cmd:e(ymean)}). Use
+{cmd:estadd}'s {cmd:prefix()} option to change the prefix. If a model
+has multiple dependent variables, results for the first variable will
+be added.
+
+{dlgtab:Other}
+{marker margins}
+{p 4 8 2}
+{cmd:estadd} {cmd:margins} [{it:marginlist}] [{it:if}] [{it:in}] [{it:weight}] [, {it:options} ]
+
+{p 8 8 2}
+adds results from the {cmd:margins} command, which was introduced
+in Stata 11. See help {helpb margins} for options. All results returned by
+{cmd:margins} except {cmd:e(V)} are added using "{cmd:margins_}" as a default
+prefix. For example, the margins are added in {cmd:e(margins_b)}. The
+standard errors are added in {cmd:e(margins_se)}. Use the {helpb estadd##opts:prefix()}
+option to change the default prefix.
+
+{marker spost}
+{dlgtab:SPost}
+
+{p 4 4 2} The following subcommands are wrappers for
+commands from Long and Freese's {helpb SPost} package (see
+{browse "http://www.indiana.edu/~jslsoc/spost.htm":http://www.indiana.edu/~jslsoc/spost.htm}). Type
+
+ . {net "from http://www.indiana.edu/~jslsoc/stata":net from http://www.indiana.edu/~jslsoc/stata}
+
+{p 4 4 2}
+to obtain the latest {cmd:SPost} version (spost9_ado). {cmd:SPost} for Stata 8 (spostado) is not
+supported.
+
+{p 4 4 2}For examples on using the subcommands see
+{browse "http://repec.org/bocode/e/estout/spost.html":http://repec.org/bocode/e/estout/spost.html}.
+
+{marker brant}
+{p 4 8 2}
+{cmd:estadd brant} [{cmd:,} {it:{help brant:brant_options}} ]
+
+{p 8 8 2}
+applies {helpb brant} from Long and
+Freese's {helpb SPost} package and adds the returned results to
+{cmd:e()}. You may specify {it:brant_options} as described in
+help {helpb brant}. The following results are added:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ Scalars
+ {cmd:brant_chi2} Chi-squared of overall Brant test
+ {cmd:brant_df} Degrees of freedom of overall Brant test
+ {cmd:brant_p} P-value of overall Brant test
+
+ Matrix
+ {cmd:brant} Test results for individual regressors
+ (rows: chi2, p LR or Wald X2
+ {cmd:r2_adj} Adjusted R2
+ {cmd:r2_mf} McFadden's R2
+ {cmd:r2_mfadj} McFadden's Adj R2
+ {cmd:r2_ml} ML (Cox-Snell) R2
+ {cmd:r2_cu} Cragg-Uhler(Nagelkerke) R2
+ {cmd:r2_mz} McKelvey & Zavoina's R2
+ {cmd:r2_ef} Efron's R2
+ {cmd:v_ystar} Variance of y*
+ {cmd:v_error} Variance of error
+ {cmd:r2_ct} Count R2
+ {cmd:r2_ctadj} Adj Count R2
+ {cmd:aic0} AIC
+ {cmd:aic_n} AIC*n
+ {cmd:bic0} BIC
+ {cmd:bic_p} BIC'
+ {cmd:statabic} BIC used by Stata
+ {cmd:stataaic} AIC used by Stata
+ {cmd:n_rhs} Number of rhs variables
+ {cmd:n_parm} Number of parameters
+ {hline 60}
+
+{marker listcoef}
+{p 4 8 2}
+{cmd:estadd listcoef} [{it:varlist}] [{cmd:,} {cmd:nosd} {it:{help listcoef:listcoef_options}} ]
+
+{p 8 8 2}
+applies {helpb listcoef} from Long and
+Freese's {helpb SPost} package and adds the returned results to
+{cmd:e()}. You may specify {it:listcoef_options} as described in
+help {helpb listcoef}. Furthermore, option {cmd:nosd} suppresses
+adding the standard deviations of the variables in {cmd:e(b_sdx)}.
+
+{p 8 8 2}Depending on the estimation command and options, several of the
+following matrices are added:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ {cmd:b_xs} x-standardized coefficients
+ {cmd:b_ys} y-standardized coefficients
+ {cmd:b_std} Fully standardized coefficients
+ {cmd:b_fact} Factor change coefficients
+ {cmd:b_facts} Standardized factor change coefficients
+ {cmd:b_pct} Percent change coefficients
+ {cmd:b_pcts} Standardized percent change coefficients
+ {cmd:b_sdx} Standard deviation of the Xs
+ {hline 60}
+
+{p 8 8 2}For nominal models ({helpb mlogit}, {helpb mprobit}) the
+original parametrization of {cmd:e(b)} may not match the contrasts
+computed by {cmd:listcoef}. To be able to tabulate standardized
+coefficients along with the raw coefficients for the requested
+contrasts, the following additional matrices are added for
+these models:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ {cmd:b_raw} raw coefficients
+ {cmd:b_se} standard errors of raw coefficients
+ {cmd:b_z} z statistics
+ {cmd:b_p} p-values
+ {hline 60}
+
+{marker mlogtest}
+{p 4 8 2}
+{cmd:estadd mlogtest} [{it:varlist}] [{cmd:,} {it:{help mlogtest:mlogtest_options}} ]
+
+{p 8 8 2}
+applies {helpb mlogtest} from Long and
+Freese's {helpb SPost} package and adds the returned results to
+{cmd:e()}. You may specify {it:mlogtest_options} as described in
+help {helpb mlogtest}.
+
+{p 8 8 2}Depending on the specified options, a selection of the following
+returns are added:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ Scalars
+ {cmd:hausman_set}{it:#}{cmd:_chi2} Hausman IIA tests using {helpb hausman}
+ {cmd:hausman_set}{it:#}{cmd:_df}
+ {cmd:hausman_set}{it:#}{cmd:_p}
+
+ {cmd:suest_set}{it:#}{cmd:_chi2} Hausman IIA tests using {helpb suest}
+ {cmd:suest_set}{it:#}{cmd:_df}
+ {cmd:suest_set}{it:#}{cmd:_p}
+
+ {cmd:smhsiao_set}{it:#}{cmd:_chi2} Small-Hsiao IIA tests
+ {cmd:smhsiao_set}{it:#}{cmd:_df}
+ {cmd:smhsiao_set}{it:#}{cmd:_p}
+
+ {cmd:combine_}{it:#1}{cmd:_}{it:#2}{cmd:_chi2} Wald tests for combination of outcomes
+ {cmd:combine_}{it:#1}{cmd:_}{it:#2}{cmd:_df}
+ {cmd:combine_}{it:#1}{cmd:_}{it:#2}{cmd:_p}
+
+ {cmd:lrcomb_}{it:#1}{cmd:_}{it:#2}{cmd:_chi2} LR tests for combination of outcomes
+ {cmd:lrcomb_}{it:#1}{cmd:_}{it:#2}{cmd:_df}
+ {cmd:lrcomb_}{it:#1}{cmd:_}{it:#2}{cmd:_p}
+
+ {cmd:wald_set}{it:#}{cmd:_chi2} Wald tests for sets of independent
+ {cmd:wald_set}{it:#}{cmd:_df} variables
+ {cmd:wald_set}{it:#}{cmd:_p}
+
+ {cmd:lrtest_set}{it:#}{cmd:_chi2} LR tests for sets of independent
+ {cmd:lrtest_set}{it:#}{cmd:_df} variables
+ {cmd:lrtest_set}{it:#}{cmd:_p}
+
+ Matrices
+ {cmd:wald} Wald tests for individual variables
+ (rows: chi2, df, p)
+ {cmd:lrtest} LR tests for individual variables
+ (rows: chi2, df, p)
+ {hline 60}
+
+{p 4 4 2}To address the rows of {cmd:e(wald)} and {cmd:e(lrtest)} in {helpb estout}'s
+{cmd:cells()} option type the row names in brackets, for example, {cmd:wald[p]} or
+{cmd:lrtest[chi2]}.
+
+{marker prchange}
+{p 4 8 2}
+{cmd:estadd prchange} [{it:varlist}] [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [{cmd:,}
+ {cmdab:pa:ttern(}{it:typepattern}{cmd:)} {cmdab:b:inary(}{it:type}{cmd:)} {cmdab:c:ontinuous(}{it:type}{cmd:)}
+ [{cmd:no}]{cmdab:a:vg} {cmd:split}[{cmd:(}{it:prefix}{cmd:)}] {it:{help prchange:prchange_options}} ]
+
+{p 8 8 2}
+applies {helpb prchange} from Long and
+Freese's {helpb SPost} package and adds the returned results to
+{cmd:e()}. You may specify {it:prchange_options} as described in
+help {helpb prchange}. In particular, the {cmd:outcome()} option may be
+used with models for count, ordered, or nominal outcomes
+to request results for a specific outcome. Further options are:
+
+{p 8 12 2}{cmd:pattern(}{it:typepattern}{cmd:)}, {cmd:binary(}{it:type}{cmd:)}, and
+{cmd:continuous(}{it:type}{cmd:)} to determine which types of discrete change
+effects are added as the main results. The default is to add the 0 to 1
+change effect for binary variables and the standard deviation change effect
+for continuous variables. Use {cmd:binary(}{it:type}{cmd:)} and
+{cmd:continuous(}{it:type}{cmd:)} to change these defaults. Available
+types are:
+
+ {it:type} Description
+ {hline 48}
+ {cmdab:mi:nmax} minimum to maximum change effect
+ {cmdab:0:1} 0 to 1 change effect
+ {cmdab:d:elta} {cmd:delta()} change effect
+ {cmdab:s:d} standard deviation change effect
+ {cmdab:m:argefct} marginal effect (some models only)
+ {hline 48}
+
+{p 12 12 2}Use {cmd:pattern(}{it:typepattern}{cmd:)} if you want to determine the
+type of the added effects individually for each regressor. For example,
+{bind:{cmd:pattern(minmax sd delta)}} would add {cmd:minmax} for the first regressor,
+{cmd:sd} for the second, and {cmd:delta} for the third, and then proceed
+using the defaults for the remaining variables.
+
+{p 8 12 2}{cmd:avg} to request that only the average results over
+all outcomes are added if applied to ordered
+or nominal models ({helpb ologit}, {helpb oprobit}, {helpb slogit}, {helpb mlogit}, {helpb mprobit}). The
+default is to add the average results as well as the individual results for
+the different outcomes (unless {helpb prchange}'s {cmd:outcome()} option is
+specified, in which case only results for the indicated outcome are
+added). Furthermore, specify {cmd:noavg} to suppress the average results
+and only add the outcome-specific results. {cmd:avg} cannot be combined with {cmd:split}
+or {cmd:outcome()}.
+
+{p 8 12 2}{cmd:split}[{cmd:(}{it:prefix}{cmd:)}] to save
+each outcome's results in a separate estimation set if applied to ordered
+or nominal models ({helpb ologit}, {helpb oprobit}, {helpb slogit}, {helpb mlogit},
+{helpb mprobit}). The estimation sets are named
+{it:prefix}{it:#}, where {it:#} is the value of the outcome at hand. If no
+{it:prefix} is provided, the name of the estimation set followed by an
+underscore is used as the prefix. If the estimation set has no name
+(because it has not been stored yet) the name of the estimation command
+followed by an underscore is used as the prefix (e.g. {cmd:ologit_}). The
+estimation sets stored by the {cmd:split} option are intended for
+tabulation only and should not be used with other post-estimation
+commands.
+
+{p 8 8 2}Depending on model and options, several of the following matrices
+and scalars are added:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ Scalars
+ {cmd:centered} {cmd:1} if effects are centered, {cmd:0} else
+ {cmd:delta} Value of {cmd:delta()}
+ {cmd:predval}[{it:#}] Prediction(s) at the base values
+ {cmd:outcome} Outcome value ({cmd:outcome()}/{cmd:split} only)
+
+ Matrices
+ {cmd:dc} Discrete change effects (rows: main, minmax,
+ 01, delta, sd [, margefct])
+ {cmd:pattern} Types of effects in the main row of {cmd:e(dc)}
+ {cmd:X} Base values and descriptive statistics
+ (rows: X, SD, Min, Max)
+ {hline 60}
+
+{p 8 8 2}The {cmd:e(dc)} and {cmd:e(X)} matrices have multiple rows. The
+{cmd:e(dc)} matrix contains the main results as determined by
+{cmd:pattern()}, {cmd:binary()}, and {cmd:continuous()} in the first row.
+The second and following rows contain the separate results for each type of
+effect using the labels provided by {cmd:prchange} as row names. Type
+{cmd:dc[}{it:#}{cmd:]} or {cmd:dc[}{it:rowname}{cmd:]} to address the rows
+in {helpb estout}'s {cmd:cells()} option, where {it:#} is the row number
+or {it:rowname} is the
+row name. For example, type {cmd:dc[-+sd/2]} to address the centered
+standard deviation change effects. To tabulate the main results (1st row),
+simply type {cmd:dc}. {cmd:e(pattern)} indicates the types of effects
+contained in the main row of {cmd:e(dc)} using numeric codes. The codes are 1
+for the minimum to maximum change effect, 2 for the 0 to 1 change effect, 3
+for the {cmd:delta()} change effect, 4 for the standard deviation change
+effect, and 5 for the marginal effect. {cmd:e(X)} has four rows
+containing the base values, standard deviations, minimums, and maximums. If
+the {cmd:fromto} option is specified, two additional matrices,
+{cmd:e(dcfrom)} and {cmd:e(dcto)} are added.
+
+{marker prvalue}
+{p 4 8 2}
+{cmd:estadd prvalue} [{cmd:if} {it:exp}] [{cmd:in} {it:range}] [{cmd:,} {cmdab:lab:el:(}{it:string}{cmd:)}
+{it:{help prvalue:prvalue_options}} ]
+
+{p 4 8 2}
+{cmd:estadd prvalue} {cmd:post} [{it:name}] [{cmd:,} {cmdab:t:itle:(}{it:string}{cmd:)} {cmd:swap} ]
+
+{p 8 8 2} applies {helpb prvalue} from Long and Freese's {helpb SPost}
+package and adds the returned results to {cmd:e()}. The procedure is to
+first collect a series of predictions by repeated calls to
+{cmd:estadd prvalue} and then apply {cmd:estadd prvalue post} to prepare the results
+for tabulation as in the following example:
+
+ {com}. logit lfp k5 k618 age wc hc lwg inc
+ . estadd prvalue, x(inc 10) label(low inc)
+ . estadd prvalue, x(inc 20) label(med inc)
+ . estadd prvalue, x(inc 30) label(high inc)
+ . estadd prvalue post
+ . estout{txt}
+
+{p 8 8 2} You may specify {it:prvalue_options} with {cmd:estadd prvalue} as
+described in help {helpb prvalue}. For example, use {cmd:x()} and
+{cmd:rest()} to set the values of the independent variables. Use
+{cmd:label()} to label the single calls. "pred#" is used as label if
+{cmd:label()} is omitted, where # is the number of the call. Labels may
+contain spaces but they will be trimmed to a maximum
+length of 30 characters and some characters ({cmd::},
+{cmd:.}, {cmd:"}) will be replaced by underscore. The results
+from the single calls are collected in matrix {cmd:e(_estadd_prvalue)}
+(predictions) and matrix {cmd:e(_estadd_prvalue_x)} (x-values). Specify
+{cmd:replace} to drop results from previous calls.
+
+{p 8 8 2}
+{cmd:estadd prvalue post} posts the collected predictions in {cmd:e(b)}
+so that they can be tabulated. The following results are saved:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ Scalars
+ {cmd:N} number of observations
+
+ Macros
+ {cmd:depvar} name of dependent variable
+ {cmd:cmd} {cmd:estadd_prvalue}
+ {cmd:model} model estimation command
+ {cmd:properties} {cmd:b}
+
+ Matrices
+ {cmd:b} predictions
+ {cmd:se} standard errors
+ {cmd:LB} lower confidence interval bounds
+ {cmd:UB} upper confidence interval bounds
+ {cmd:Category} outcome values
+ {cmd:Cond} conditional predictions (some models only)
+ {cmd:X} values of predictors (for each prediction)
+ {cmd:X2} second equation predictors (some models only)
+ {hline 60}
+
+{p 8 8 2} {cmd:estadd prvalue post} replaces the current model unless
+{it:name} is specified, in which case the results are stored under {it:name} and the model
+remains active. However, if the model has a name
+(because it has been stored), the name of the model is used as a prefix.
+If, for example, the model has been stored as {cmd:model1}, then
+{cmd:estadd prvalue post} stores its results under {cmd:model1}{it:name}.
+Use {cmd:title()} to specify a title for the stored results.
+
+{p 8 8 2}The default for {cmd:estadd prvalue post} is to arrange
+{cmd:e(b)} in a way so that predictions are grouped by outcome (i.e. outcome labels are used
+as equations). Alternatively, specify {cmd:swap} to group predictions by
+{cmd:prvalue} calls (i.e. to use the prediction labels as equations).
+
+{p 8 8 2}{cmd:e(X)} contains one row for each independent variable. To address the rows in
+{helpb estout}'s {cmd:cells()} option type {cmd:X[}{it:varname}{cmd:]}, where {it:varname} is
+the name of the variable of interest. {cmd:e(X2)}, if provided, is analogous to {cmd:e(X)}.
+
+{marker asprvalue}
+{p 4 8 2}
+{cmd:estadd asprvalue} [{cmd:,} {cmdab:lab:el:(}{it:string}{cmd:)}
+{it:{help asprvalue:asprvalue_options}} ]
+
+{p 4 8 2}
+{cmd:estadd asprvalue} {cmd:post} [{it:name}] [{cmd:,} {cmdab:t:itle:(}{it:string}{cmd:)} {cmd:swap} ]
+
+{p 8 8 2} applies {helpb asprvalue} from Long and Freese's {helpb SPost}
+package and adds the returned results to {cmd:e()}. The procedure is to
+first collect a series of predictions by repeated calls to
+{cmd:estadd asprvalue} and then apply {cmd:estadd asprvalue post} to prepare the results
+for tabulation as in the following example:
+
+ {com}. clogit choice train bus time invc, group(id)
+ . estadd asprvalue, cat(train bus) label(at means)
+ . estadd asprvalue, cat(train bus) rest(asmean) label(at asmeans)
+ . estadd asprvalue post
+ . estout{txt}
+
+{p 8 8 2} You may specify {it:asprvalue_options} with {cmd:estadd asprvalue} as
+described in help {helpb asprvalue}. For example, use {cmd:x()} and
+{cmd:rest()} to set the values of the independent variables. Use
+{cmd:label()} to label the single calls. "pred#" is used as label if
+{cmd:label()} is omitted, where # is the number of the call. Labels may
+contain spaces but they will be trimmed to a maximum
+length of 30 characters and some characters ({cmd::},
+{cmd:.}, {cmd:"}) will be replaced by underscore. The results
+from the single calls are collected in matrices {cmd:e(_estadd_asprval)}
+(predictions), {cmd:e(_estadd_asprval_asv)} (values of alternative-specific
+variables), and {cmd:e(_estadd_asprval_csv)} (values of case-specific
+variables). Specify {cmd:replace} to drop results from previous calls.
+
+{p 8 8 2}
+{cmd:estadd asprvalue post} posts the collected predictions in {cmd:e(b)}
+so that they can be tabulated. The following results are saved:
+
+ {cmd:e(}{it:...}{cmd:)} Contents
+ {hline 60}
+ Scalars
+ {cmd:N} number of observations
+
+ Macros
+ {cmd:depvar} name of dependent variable
+ {cmd:cmd} {cmd:estadd_asprvalue}
+ {cmd:model} model estimation command
+ {cmd:properties} {cmd:b}
+
+ Matrices
+ {cmd:b} predictions
+ {cmd:asv} alternative-specific variables (if available)
+ {cmd:csv} case-specific variables (if available)
+ {hline 60}
+
+{p 8 8 2} {cmd:estadd asprvalue post} replaces the current model unless
+{it:name} is specified, in which case the results are stored under
+{it:name} and the model remains active. However, if the model has a name
+(because it has been stored), the name of the model is used as a prefix.
+If, for example, the model has been stored as {cmd:model1}, then
+{cmd:estadd asprvalue post} stores its results under {cmd:model1}{it:name}.
+Use {cmd:title()} to specify a title for the stored results.
+
+{p 8 8 2}The default for {cmd:estadd asprvalue post} is to arrange
+{cmd:e(b)} in a way so that predictions are grouped by outcome (i.e. outcome labels are used
+as equations). Alternatively, specify {cmd:swap} to group predictions by
+{cmd:prvalue} calls (i.e. to use the prediction labels as equations).
+
+{p 8 8 2}{cmd:e(asv)} and {cmd:e(csv)} contain one row for each variable.
+To address the rows in {helpb estout}'s {cmd:cells()} option type
+{cmd:asv[}{it:varname}{cmd:]} or {cmd:csv[}{it:varname}{cmd:]}, where
+{it:varname} is the name of the variable of interest.
+
+{marker options}
+{title:Options}
+
+{p 4 8 2}
+{cmd:replace} permits {cmd:estadd} to overwrite existing {cmd:e()}
+macros, scalars, or matrices.
+
+{p 4 8 2}
+{cmd:prefix(}{it:string}{cmd:)} denotes a prefix for the names of the
+added results. The default prefix is an empty string. For example, if
+{cmd:prefix(}{it:string}{cmd:)} is specified, the {cmd:beta}
+subcommand will return the matrix {cmd:e(}{it:string}{cmd:beta)}.
+
+{p 4 8 2}{cmd:quietly} suppresses the output from the called subcommand and displays only
+the list of added results. Note that many of {cmd:estadd}'s subcommands do not generate
+output, in which case {cmd:quietly} has no effect.
+
+{p 4 8 2}
+{it:subcmdopts} are subcommand specific options. See the descriptions
+of the subcommands above.
+
+{marker examples}
+{title:Examples}
+
+{p 4 4 2}Example 1: Add {cmd:r()}-returns from other programs to the
+current estimates
+
+ {com}. sysuse auto
+ {txt}(1978 Automobile Data)
+
+ {com}. quietly regress price mpg weight
+ {txt}
+ {com}. test mpg=weight
+
+ {txt} ( 1) {res}mpg - weight = 0
+
+ {txt} F( 1, 71) ={res} 0.36
+ {txt}{col 13}Prob > F ={res} 0.5514
+ {txt}
+ {com}. estadd scalar p_diff = r(p)
+
+ {txt}added scalar:
+ e(p_diff) = {res}.55138216
+ {txt}
+ {com}. estout, stats(p_diff)
+ {res}
+ {txt}{hline 25}
+ {txt} b
+ {txt}{hline 25}
+ {txt}mpg {res} -49.51222{txt}
+ {txt}weight {res} 1.746559{txt}
+ {txt}_cons {res} 1946.069{txt}
+ {txt}{hline 25}
+ {txt}p_diff {res} .5513822{txt}
+ {txt}{hline 25}
+
+
+{p 4 4 2}Example 2: Add means and standard deviations of the model's regressors
+to the current estimates
+
+ {com}. quietly logit foreign price mpg
+ {txt}
+ {com}. estadd summ, mean sd
+
+ {txt}added matrices:
+ e(sd) : {res}1 x 3
+ {txt}e(mean) : {res}1 x 3
+ {txt}
+ {com}. estout, cells("mean sd") drop(_cons)
+ {res}
+ {txt}{hline 38}
+ {txt} mean sd
+ {txt}{hline 38}
+ {txt}price {res} 6165.257 2949.496{txt}
+ {txt}mpg {res} 21.2973 5.785503{txt}
+ {txt}{hline 38}
+
+
+{p 4 4 2}
+Example 3: Add standardized beta coefficients to stored estimates
+
+ {com}. eststo: quietly regress price mpg
+ {txt}({res}est1{txt} stored)
+
+ {com}. eststo: quietly regress price mpg foreign
+ {txt}({res}est2{txt} stored)
+
+ {com}. estadd beta: *
+ {txt}
+ {com}. estout, cells(beta) drop(_cons)
+ {res}
+ {txt}{hline 38}
+ {txt} est1 est2
+ {txt} beta beta
+ {txt}{hline 38}
+ {txt}mpg {res} -.4685967 -.5770712{txt}
+ {txt}foreign {res} .2757378{txt}
+ {txt}{hline 38}
+
+
+{p 4 4 2}See
+{browse "http://repec.org/bocode/e/estout":http://repec.org/bocode/e/estout}
+for additional examples.
+
+
+{title:Writing one's own subcommands}
+
+{p 4 4 2}
+A program providing a new {cmd:estadd} subcommand should be called
+{cmd:estadd_}{it:mysubcommand} (see help {helpb program} for advice
+on defining programs). {it:mysubcommand} will be available to {cmd:estadd} as a new
+{it:subcommand} after the program definition has been executed or
+saved to a file called "estadd_{it:mysubcommand}.ado" in either the
+current directory or somewhere else in the {cmd:adopath}
+(see help {helpb sysdir}).
+
+{p 4 4 2}
+Use the subcommands provided within "estadd.ado" as a starting
+point for writing new subcommands. See
+{browse "http://repec.org/bocode/e/estout/estadd.html#estadd007":http://repec.org/bocode/e/estout/estadd.html#estadd007}
+for an example.
+
+
+{title:Author}
+
+{p 4 4 2} Ben Jann, ETH Zurich, jannb@ethz.ch
+
+
+{title:Also see}
+
+ Manual: {hi:[R] estimates}
+
+{p 4 13 2}Online: help for
+ {helpb estimates},
+ {helpb ereturn},
+ {helpb program},
+ {helpb esttab},
+ {helpb estout},
+ {helpb eststo},
+ {helpb estpost}
+{p_end}
diff --git a/Modules/ado/plus/e/estout.ado b/Modules/ado/plus/e/estout.ado
new file mode 100644
index 0000000..e1ed449
--- /dev/null
+++ b/Modules/ado/plus/e/estout.ado
@@ -0,0 +1,4495 @@
+*! version 3.13 06aug2009 Ben Jann
+
+program define estout, rclass
+ version 8.2
+ return local cmdline estout `macval(0)'
+ syntax [anything] [using] [ , ///
+ Cells(string asis) ///
+ Drop(string asis) ///
+ Keep(string asis) ///
+ Order(string asis) ///
+ REName(passthru) ///
+ Indicate(string asis) ///
+ TRansform(string asis) ///
+ EQuations(passthru) ///
+ NOEFORM eform EFORM2(string) ///
+ NOMargin Margin Margin2(string) ///
+ NODIscrete DIscrete(string asis) ///
+ MEQs(string) ///
+ NODROPPED dropped DROPPED2(string) ///
+ level(numlist max=1 int >=10 <=99) ///
+ Stats(string asis) ///
+ STARLevels(string asis) ///
+ NOSTARDetach STARDetach ///
+ STARKeep(string asis) ///
+ STARDrop(string asis) ///
+ VARwidth(numlist max=1 int >=0) ///
+ MODELwidth(numlist int >=0) ///
+ NOABbrev ABbrev ///
+ NOUNStack UNStack ///
+ EXTRAcols(numlist sort) ///
+ BEGin(string asis) ///
+ DELimiter(string asis) ///
+ INCELLdelimiter(string asis) ///
+ end(string asis) ///
+ DMarker(string) ///
+ MSign(string) ///
+ NOLZ lz ///
+ SUBstitute(string asis) ///
+ TItle(string) ///
+ note(string) ///
+ NOLEgend LEgend ///
+ PREHead(string asis) ///
+ POSTHead(string asis) ///
+ PREFoot(string asis) ///
+ POSTFoot(string asis) ///
+ HLinechar(string) ///
+ NOLabel Label ///
+ VARLabels(string asis) ///
+ REFcat(string asis) ///
+ MLabels(string asis) ///
+ NONUMbers NUMbers NUMbers2(string asis) ///
+ COLLabels(string asis) ///
+ EQLabels(string asis) ///
+ MGRoups(string asis) ///
+ LABCOL2(string asis) ///
+ TOPfile(string) ///
+ BOTtomfile(string) ///
+ STYle(string) ///
+ DEFaults(string) ///
+ * ///
+ ]
+ MoreOptions, `options'
+ if "`style'"!="" local defaults "`style'"
+
+*Matrix mode
+ MatrixMode, `anything' `rename' // resets the cells argument
+ // and returns r(coefs) etc. and local 'matrixmode'
+
+*Parse suboptions
+ local elnum 0
+ if `"`cells'"'!="none" {
+ gettoken row rest: cells, bind match(par) qed(qed)
+ if `"`par'"'=="(" local qed 1
+ local cells
+ while `"`row'"'!="" {
+ local newrow
+ gettoken opt row: row, parse(" ([&")
+ if `"`macval(row)'"'=="" & `qed'==0 {
+ local row0
+ gettoken trash: rest, parse("[")
+ if `"`trash'"'=="[" {
+ gettoken trash rest: rest, parse("[")
+ gettoken mrow rest: rest, parse("]") q
+ gettoken trash rest: rest, parse("]")
+ if `"`trash'"'!="]" {
+ error 198
+ }
+ }
+ gettoken trash: rest, match(par)
+ if `"`par'"'=="(" {
+ gettoken opt2 rest: rest, match(par)
+ }
+ else local opt2
+ }
+ else {
+ gettoken trash: row, parse("[")
+ if `"`trash'"'=="[" {
+ gettoken trash row: row, parse("[")
+ gettoken mrow row: row, parse("]") q
+ gettoken trash row: row, parse("]")
+ if `"`trash'"'!="]" {
+ error 198
+ }
+ }
+ gettoken trash row0: row, match(par)
+ gettoken opt2: row, match(par)
+ }
+ while "`opt'"!="" {
+ if "`opt'"!="&" & "`opt'"!="." {
+ local `opt'_tname "el`++elnum'"
+ local ``opt'_tname'_ "`opt'"
+ local newrow `"`newrow' ``opt'_tname'"'
+ if `"`par'"'!="(" local opt2
+ ParseValueSubopts ``opt'_tname' `opt', mrow(`mrow') `macval(opt2)'
+ local mrow
+ }
+ else {
+ if `"`par'"'=="(" | `"`mrow'"'!="" error 198
+ local newrow `"`newrow' `opt'"'
+ }
+ if `"`par'"'!="(" {
+ gettoken opt row: row, parse(" ([&")
+ }
+ else {
+ gettoken opt row: row0, parse(" ([&")
+ }
+ gettoken trash: row, parse("[")
+ if `"`trash'"'=="[" {
+ gettoken trash row: row, parse("[")
+ gettoken mrow row: row, parse("]") q
+ gettoken trash row: row, parse("]")
+ if `"`trash'"'!="]" {
+ error 198
+ }
+ }
+ gettoken trash row0: row, match(par)
+ gettoken opt2: row, match(par)
+ }
+ local newrow: list retok newrow
+ if `qed' local cells `"`cells'"`newrow'" "'
+ else local cells `"`cells'`newrow' "'
+ gettoken row rest: rest, bind match(par) qed(qed)
+ if `"`par'"'=="(" local qed 1
+ }
+ local cells: list retok cells
+ }
+ if "`eform2'"!="" {
+ local eform "`eform2'"
+ local eform2
+ }
+ if `"`transform'"'!="" {
+ ParseTransformSubopts `transform'
+ }
+ if "`margin2'"!="" {
+ local margin "`margin2'"
+ local margin2
+ }
+ if `"`dropped'"'!="" local dropped "(dropped)"
+ if `"`macval(dropped2)'"'!="" {
+ local dropped `"`macval(dropped2)'"'
+ local dropped2
+ }
+ if `"`macval(stats)'"'!="" {
+ ParseStatsSubopts `macval(stats)'
+ if `"`macval(statslabels)'"'!="" {
+ if trim(`"`statslabels'"')=="none" {
+ local statslabelsnone none
+ local statslabels
+ }
+ else {
+ ParseLabelsSubopts statslabels `macval(statslabels)'
+ }
+ }
+ }
+ foreach opt in mgroups mlabels eqlabels collabels varlabels {
+ if `"`macval(`opt')'"'!="" {
+ if trim(`"``opt''"')=="none" {
+ local `opt'none none
+ local `opt'
+ }
+ else {
+ ParseLabelsSubopts `opt' `macval(`opt')'
+ }
+ }
+ }
+ if `"`macval(numbers2)'"'!="" {
+ local numbers `"`macval(numbers2)'"'
+ local numbers2
+ }
+ if `"`macval(indicate)'"'!="" {
+ ParseIndicateOpts `macval(indicate)'
+ }
+ if `"`macval(refcat)'"'!="" {
+ ParseRefcatOpts `macval(refcat)'
+ }
+ if `"`macval(starlevels)'"'!="" {
+ ParseStarlevels `macval(starlevels)'
+ }
+ if `"`macval(labcol2)'"'!="" {
+ ParseLabCol2 `macval(labcol2)'
+ }
+
+*Process No-Options
+ foreach opt in unstack eform margin dropped discrete stardetach wrap ///
+ legend label refcatlabel numbers lz abbrev replace append type showtabs ///
+ smcltags smclrules smclmidrules smcleqrules asis outfilenoteoff {
+ if "`no`opt''"!="" local `opt'
+ }
+
+*Defaults
+ if "`defaults'"=="esttab" local defaults "tab"
+ if "`defaults'"=="" & `"`using'"'=="" local defaults "smcl"
+ if inlist("`defaults'", "", "smcl", "tab", "fixed", "tex", "html","mmd") {
+ local varwidthfactor = (1 + ("`eqlabelsmerge'"!="" & "`unstack'"=="")*.5)
+ if inlist("`defaults'", "", "tab") {
+ if `"`macval(delimiter)'"'=="" local delimiter _tab
+ }
+ else if "`defaults'"=="smcl" {
+ if "`varwidth'"=="" local varwidth = cond("`label'"=="", 12, 20) * `varwidthfactor'
+ if "`modelwidth'"=="" local modelwidth 12
+ if "`noabbrev'"=="" local abbrev abbrev
+ if `"`macval(delimiter)'"'=="" local delimiter `"" ""'
+ if "`nosmcltags'"=="" local smcltags smcltags
+ if "`nosmclrules'"=="" local smclrules smclrules
+ if "`asis'"=="" local noasis noasis
+ }
+ else if "`defaults'"=="fixed" {
+ if "`varwidth'"=="" local varwidth = cond("`label'"=="", 12, 20) * `varwidthfactor'
+ if "`modelwidth'"=="" local modelwidth 12
+ if "`noabbrev'"=="" local abbrev abbrev
+ if `"`macval(delimiter)'"'=="" local delimiter `"" ""'
+ }
+ else if "`defaults'"=="tex" {
+ if "`varwidth'"=="" local varwidth = cond("`label'"=="", 12, 20) * `varwidthfactor'
+ if "`modelwidth'"=="" local modelwidth 12
+ if `"`macval(delimiter)'"'=="" local delimiter &
+ if `"`macval(end)'"'=="" {
+ local end \\\
+ }
+ }
+ else if "`defaults'"=="html" {
+ if "`varwidth'"=="" local varwidth = cond("`label'"=="", 12, 20) * `varwidthfactor'
+ if "`modelwidth'"=="" local modelwidth 12
+ if `"`macval(begin)'"'=="" local begin
+ if `"`macval(delimiter)'"'=="" local delimiter |
+ if `"`macval(end)'"'=="" local end |
+ }
+ else if "`defaults'"=="mmd" {
+ if "`varwidth'"=="" local varwidth = cond("`label'"=="", 12, 20) * `varwidthfactor'
+ if "`modelwidth'"=="" local modelwidth 12
+ if `"`macval(begin)'"'=="" local begin "| "
+ if `"`macval(delimiter)'"'=="" local delimiter " | "
+ if `"`macval(end)'"'=="" local end " |"
+ }
+ if "`nostatslabelsfirst'"=="" local statslabelsfirst first
+ if "`nostatslabelslast'"=="" local statslabelslast last
+ if "`novarlabelsfirst'"=="" local varlabelsfirst first
+ if "`novarlabelslast'"=="" local varlabelslast last
+ if "`noeqlabelsfirst'"=="" local eqlabelsfirst first
+ if "`noeqlabelslast'"=="" local eqlabelslast last
+ if "`nolz'"=="" local lz lz
+ if `"`macval(discrete)'"'=="" & "`nodiscrete'"=="" {
+ local discrete `"" (d)" for discrete change of dummy variable from 0 to 1"'
+ }
+ if `"`macval(indicatelabels)'"'=="" local indicatelabels "Yes No"
+ if `"`macval(refcatlabel)'"'=="" & "`norefcatlabel'"=="" local refcatlabel "ref."
+ if `"`macval(incelldelimiter)'"'=="" local incelldelimiter " "
+ }
+ else {
+ capture findfile estout_`defaults'.def
+ if _rc {
+ di as error `"`defaults' style not available "' ///
+ `"(file estout_`defaults'.def not found)"'
+ exit 601
+ }
+ else {
+ tempname file
+ file open `file' using `"`r(fn)'"', read text
+ if c(SE) local max 244
+ else local max 80
+ while 1 {
+ ReadLine `max' `file'
+ if `"`line'"'=="" continue, break
+ gettoken opt line: line
+ else if index(`"`opt'"',"_") {
+ gettoken opt0 opt1: opt, parse("_")
+ if `"``opt0'_tname'"'!="" {
+ local opt `"``opt0'_tname'`opt1'"'
+ }
+ }
+ if `"`macval(`opt')'"'=="" & `"`no`opt''"'=="" {
+ if `"`opt'"'=="cells" {
+ local newline
+ gettoken row rest: line, match(par) qed(qed)
+ if `"`par'"'=="(" local qed 1
+ while `"`row'"'!="" {
+ local newrow
+ gettoken el row: row, parse(" &")
+ while `"`el'"'!="" {
+ if `"`el'"'!="." & `"`el'"'!="&" {
+ local `el'_tname "el`++elnum'"
+ local ``el'_tname'_ "`el'"
+ local newrow "`newrow' ``el'_tname'"
+ }
+ else {
+ local newrow "`newrow' `el'"
+ }
+ gettoken el row: row, parse(" &")
+ }
+ local newrow: list retok newrow
+ if `qed' local newline `"`newline'"`newrow'" "'
+ else local newline `"`newline'`newrow' "'
+ gettoken row rest: rest, match(par) qed(qed)
+ if `"`par'"'=="(" local qed 1
+ }
+ local line `"`newline'"'
+ }
+ local line: list retok line
+ local `opt' `"`macval(line)'"'
+ }
+ }
+ file close `file'
+ }
+ }
+ if "`notype'"=="" & `"`using'"'=="" local type type
+ if "`smcltags'"=="" & "`noasis'"=="" local asis asis
+ if "`asis'"!="" local asis "_asis"
+ if "`smclrules'"!="" & "`nosmclmidrules'"=="" local smclmidrules smclmidrules
+ if "`smclmidrules'"!="" & "`nosmcleqrules'"=="" local smcleqrules smcleqrules
+ local haslabcol2 = (`"`macval(labcol2)'"'!="")
+
+*title/notes option
+ if `"`macval(prehead)'`macval(posthead)'`macval(prefoot)'`macval(postfoot)'"'=="" {
+ if `"`macval(title)'"'!="" {
+ local prehead `"`"`macval(title)'"'"'
+ }
+ if `"`macval(note)'"'!="" {
+ local postfoot `"`"`macval(note)'"'"'
+ }
+ }
+
+*Generate/clean-up cell contents
+ if `"`:list clean cells'"'=="" {
+ local cells b
+ local b_tname "b"
+ local b_ "b"
+ }
+ else if `"`:list clean cells'"'=="none" {
+ local cells
+ }
+ CellsCheck `"`cells'"'
+ if `:list sizeof incelldelimiter'==1 gettoken incelldelimiter: incelldelimiter
+
+*Special treatment of confidence intervalls
+ if "`level'"=="" local level $S_level
+ if `level'<10 | `level'>99 {
+ di as error "level(`level') invalid"
+ exit 198
+ }
+ if "`ci_tname'"!="" {
+ if `"`macval(`ci_tname'_label)'"'=="" {
+ local `ci_tname'_label "ci`level'"
+ }
+ if `"`macval(`ci_tname'_par)'"'=="" {
+ local `ci_tname'_par `""" , """'
+ }
+ gettoken 1 2 : `ci_tname'_par
+ gettoken 2 3 : 2
+ gettoken 3 : 3
+ local `ci_tname'_l_par `""`macval(1)'" "`macval(2)'""'
+ local `ci_tname'_u_par `""" "`macval(3)'""'
+ }
+ if "`ci_l_tname'"!="" {
+ if `"`macval(`ci_l_tname'_label)'"'=="" {
+ local `ci_l_tname'_label "min`level'"
+ }
+ }
+ if "`ci_u_tname'"!="" {
+ if `"`macval(`ci_u_tname'_label)'"'=="" {
+ local `ci_u_tname'_label "max`level'"
+ }
+ }
+
+*Formats
+ local firstv: word 1 of `values'
+ if "`firstv'"=="" local firstv "b"
+ if "``firstv'_fmt'"=="" local `firstv'_fmt %9.0g
+ foreach v of local values {
+ if "``v'_fmt'"=="" local `v'_fmt "``firstv'_fmt'"
+ if `"`macval(`v'_label)'"'=="" {
+ local `v'_label "``v'_'"
+ }
+ }
+
+*Check margin option / prepare discrete option / prepare dropped option
+ if "`margin'"!="" {
+ if !inlist("`margin'","margin","u","c","p") {
+ di as error "margin(`margin') invalid"
+ exit 198
+ }
+ if `"`macval(discrete)'"'!="" {
+ gettoken discrete discrete2: discrete
+ }
+ }
+ else local discrete
+ local droppedison = (`"`macval(dropped)'"'!="")
+
+*Formats/labels/stars for statistics
+ if "`statsfmt'"=="" local statsfmt: word 1 of ``firstv'_fmt'
+ ProcessStatslayout `"`stats'"' `"`statsfmt'"' `"`statsstar'"' ///
+ `"`statslayout'"' `"`statspchar'"'
+ local stats: list uniq stats
+ if "`statsstar'"!="" local p " p"
+ else local p
+
+*Significance stars
+ local tablehasstars 0
+ foreach v of local values {
+ local el "``v'_'"
+ if "``v'_star'"!="" | inlist("`el'","_star","_sigsign") {
+ if "``v'_pvalue'"=="" local `v'_pvalue p
+ local tablehasstars 1
+ }
+ }
+
+*Check/define starlevels/make levelslegend
+ if `tablehasstars' | `"`statsstar'"'!="" {
+ if `"`macval(starlevels)'"'=="" ///
+ local starlevels "* 0.05 ** 0.01 *** 0.001"
+ CheckStarvals `"`macval(starlevels)'"' `"`macval(starlevelslabel)'"' ///
+ `"`macval(starlevelsdelimiter)'"'
+ }
+
+*Get coefficients/variances/statistics: _estout_getres
+* - prepare transform/eform
+ if `"`transform'"'=="" { // transform() overwrites eform()
+ if "`eform'"!="" {
+ local transform "exp(@) exp(@)"
+ if "`eform'"!="eform" {
+ local transformpattern "`eform'"
+ }
+ }
+ }
+ foreach m of local transformpattern {
+ if !( "`m'"=="1" | "`m'"=="0" ) {
+ di as error "invalid pattern in transform(,pattern()) or eform()"
+ exit 198
+ }
+ }
+* - handle pvalue() suboption
+ if `tablehasstars' {
+ local temp
+ foreach v of local values {
+ local temp: list temp | `v'_pvalue
+ }
+ foreach v of local temp {
+ if `"``v'_tname'"'=="" {
+ local `v'_tname "el`++elnum'"
+ local ``v'_tname'_ "`v'"
+ local values: list values | `v'_tname
+ }
+ }
+ }
+* - prepare list of results to get from e()-matrices
+ if "`ci_tname'"!="" {
+ local values: subinstr local values "`ci_tname'" "`ci_tname'_l `ci_tname'_u", word
+ local `ci_tname'_l_ "ci_l"
+ local ci_l_tname "`ci_tname'_l"
+ local `ci_tname'_u_ ci_u
+ local ci_u_tname "`ci_tname'_u"
+ }
+ foreach v of local values {
+ local temp = ("``v'_transpose'"!="")
+ local values1mrow `"`values1mrow' `"``v'_' `temp' ``v'_mrow'"'"'
+ }
+ tempname B D St
+ if `matrixmode'==0 {
+* - expand model names
+ if `"`anything'"'=="" {
+ capt est_expand $eststo
+ if !_rc {
+ local anything `"$eststo"'
+ }
+ }
+ if `"`anything'"'=="" local anything "."
+ capt est_expand `"`anything'"'
+ if _rc {
+ if _rc==301 { // add e(cmd)="." to current estimates if undefined
+ if `:list posof "." in anything' & `"`e(cmd)'"'=="" {
+ if `"`: e(scalars)'`: e(macros)'`: e(matrices)'`: e(functions)'"'!="" {
+ qui estadd local cmd "."
+ }
+ }
+ }
+ est_expand `"`anything'"'
+ }
+ local models `r(names)'
+ // could not happen, ...
+ if "`models'" == "" {
+ exit
+ }
+* - get results
+ local temp names(`models') coefs(`values1mrow') stats(`stats'`p') ///
+ `rename' margin(`margin') meqs(`meqs') dropped(`droppedison') level(`level') ///
+ transform(`transform') transformpattern(`transformpattern')
+ _estout_getres, `equations' `temp'
+ local ccols = r(ccols)
+ if `"`equations'"'=="" & "`unstack'"=="" & `ccols'>0 { // specify equations("") to deactivate
+ TableIsAMess
+ if `value' {
+ _estout_getres, equations(main=1) `temp'
+ }
+ }
+ mat `St' = r(stats)
+ }
+ else { // matrix mode
+ local models `r(names)'
+ // define `St' so that code does not break
+ if `"`stats'"'!="" {
+ mat `St' = J(`:list sizeof stats',1,.z)
+ mat coln `St' = `models'
+ mat rown `St' = `stats'
+ }
+ }
+ local nmodels = r(nmodels)
+ local ccols = r(ccols)
+ if `ccols'>0 {
+ mat `B' = r(coefs)
+ }
+ return add
+* - process order() option
+ if `"`order'"' != "" {
+ ExpandEqVarlist `"`order'"' `B' append
+ local order `"`value'"'
+ Order `B' `"`order'"'
+ }
+* - process indicate() option
+ local nindicate 0
+ foreach indi of local indicate {
+ local ++nindicate
+ ProcessIndicateGrp `nindicate' `B' `nmodels' "`unstack'" ///
+ `"`macval(indicatelabels)'"' `"`macval(indi)'"'
+ }
+* - process keep() option
+ if `"`keep'"' != "" {
+ ExpandEqVarlist `"`keep'"' `B'
+ DropOrKeep 1 `B' `"`value'"'
+ }
+* - process drop() option
+ if `"`drop'"' != "" {
+ ExpandEqVarlist `"`drop'"' `B'
+ DropOrKeep 0 `B' `"`value'"'
+ }
+
+* - names and equations of final set
+ capt confirm matrix `B'
+ if _rc {
+ return local coefs "" // erase r(coefs)
+ return local ccols ""
+ local R 0
+ local varlist ""
+ local eqlist ""
+ local eqs "_"
+ local fullvarlist ""
+ }
+ else {
+ return matrix coefs = `B', copy // replace r(coefs)
+ local R = rowsof(`B')
+ local C = colsof(`B')
+ QuotedRowNames `B'
+ local varlist `"`value'"'
+ local eqlist: roweq `B', q
+ local eqlist: list clean eqlist
+ UniqEqsAndDims `"`eqlist'"'
+ MakeQuotedFullnames `"`varlist'"' `"`eqlist'"'
+ local fullvarlist `"`value'"'
+* - dropped coefs
+ local droppedpos = `ccols'
+ if "`margin'"!="" {
+ local droppedpos `droppedpos' - 1
+ }
+* - 0/1-variable indicators (for marginals)
+ mat `D' = `B'[1...,1], J(`R',1,0) // so that row names are copied from `B'
+ mat `D' = `D'[1...,2]
+ if "`margin'"!="" {
+ forv i = 1/`R' { // last colum for each model contains _dummy info
+ forv j = `ccols'(`ccols')`C' {
+ if `B'[`i',`j']==1 {
+ mat `D'[`i',1] = 1
+ }
+ }
+ }
+ }
+ }
+
+*Prepare element specific keep/drop
+ local dash
+ tempname tmpmat
+ foreach v in star `values' {
+ local temp `"`fullvarlist'"'
+ if "`unstack'"!="" {
+ local temp2: list uniq eqs
+ local `v'`dash'eqdrop: list uniq eqs
+ }
+ if `"``v'`dash'keep'"'!="" {
+ capt mat `tmpmat' = `B'
+ ExpandEqVarlist `"``v'`dash'keep'"' `tmpmat'
+ DropOrKeep 1 `tmpmat' `"`value'"'
+ capt confirm matrix `tmpmat'
+ if _rc local temp
+ else {
+ QuotedRowNames `tmpmat'
+ MakeQuotedFullnames `"`value'"' `"`: roweq `tmpmat', q'"'
+ local temp: list temp & value
+ if "`unstack'"!="" {
+ local value: roweq `tmpmat', q
+ local value: list uniq value
+ local temp2: list temp2 & value
+ }
+ }
+ }
+ if `"``v'`dash'drop'"'!="" {
+ capt mat `tmpmat' = `B'
+ ExpandEqVarlist `"``v'`dash'drop'"' `tmpmat'
+ DropOrKeep 0 `tmpmat' `"`value'"'
+ capt confirm matrix `tmpmat'
+ if _rc local temp
+ else {
+ QuotedRowNames `tmpmat'
+ MakeQuotedFullnames `"`value'"' `"`: roweq `tmpmat', q'"'
+ local temp: list temp & value
+ if "`unstack'"!="" {
+ local value: roweq `tmpmat', q
+ local value: list uniq value
+ local temp2: list temp2 & value
+ }
+ }
+ }
+ local `v'`dash'drop: list fullvarlist - temp
+ if "`unstack'"!="" {
+ local `v'`dash'eqdrop: list `v'`dash'eqdrop - temp2
+ }
+ local dash "_"
+ }
+ capt mat drop `tmpmat'
+
+*Prepare unstack
+ if "`unstack'"!="" & `R'>0 {
+ local varlist: list uniq varlist
+ GetVarnamesFromOrder `"`order'"'
+ local temp: list value & varlist
+ local varlist: list temp | varlist
+ local cons _cons
+ if `:list cons in value'==0 {
+ if `:list cons in varlist' {
+ local varlist: list varlist - cons
+ local varlist: list varlist | cons
+ }
+ }
+ local R: word count `varlist'
+ local eqswide: list uniq eqs
+ forv i=1/`nindicate' {
+ ReorderEqsInIndicate `"`nmodels'"' `"`eqswide'"' ///
+ `"`indicate`i'eqs'"' `"`macval(indicate`i'lbls)'"'
+ local indicate`i'lbls `"`macval(value)'"'
+ }
+ }
+ else local eqswide "_"
+
+*Prepare coefs for tabulation
+ if `R'>0 {
+ local i 0
+ foreach v of local values {
+ local ++i
+ tempname _`v'
+ forv j = 1/`nmodels' {
+ mat `_`v'' = nullmat(`_`v''), `B'[1..., (`j'-1)*`ccols'+`i']
+ }
+ mat coln `_`v'' = `models'
+ mat coleq `_`v'' = `models'
+ if inlist("``v'_'", "t", "z") {
+ if `"``v'_abs'"'!="" { // absolute t-values
+ forv r = 1/`R' {
+ forv j = 1/`nmodels' {
+ if `_`v''[`r',`j']>=. continue
+ mat `_`v''[`r',`j'] = abs(`_`v''[`r',`j'])
+ }
+ }
+ }
+ }
+ }
+ }
+
+*Model labels
+ if "`nomlabelstitles'"=="" & "`label'"!="" local mlabelstitles titles
+ local tmp: list sizeof mlabels
+ local i 0
+ foreach model of local models {
+ local ++i
+ if `i'<=`tmp' continue
+ local lab
+ if "`mlabelsdepvars'"!="" {
+ local var `"`return(m`i'_depname)'"'
+ if "`label'"!="" {
+ local temp = index(`"`var'"',".")
+ local temp2 = substr(`"`var'"',`temp'+1,.)
+ capture local lab: var l `temp2'
+ if _rc | `"`lab'"'=="" {
+ local lab `"`temp2'"'
+ }
+ local temp2 = substr(`"`var'"',1,`temp')
+ local lab `"`temp2'`macval(lab)'"'
+ }
+ else local lab `"`var'"'
+ }
+ else if "`mlabelstitles'"!="" {
+ local lab `"`return(m`i'_estimates_title)'"'
+ if `"`lab'"'=="" local lab "`model'"
+ }
+ else {
+ local lab "`model'"
+ }
+ local mlabels `"`macval(mlabels)' `"`macval(lab)'"'"'
+ }
+ if "`mlabelsnumbers'"!="" {
+ NumberMlabels `nmodels' `"`macval(mlabels)'"'
+ }
+
+*Equations labels
+ local eqconssubok = (`"`macval(eqlabels)'"'!=`""""')
+ local numeqs: list sizeof eqs
+ local temp: list sizeof eqlabels
+ if `temp'<`numeqs' {
+ forv i = `=`temp'+1'/`numeqs' {
+ local eq: word `i' of `eqs'
+ local value
+ if "`label'"!="" {
+ capture confirm variable `eq'
+ if !_rc {
+ local value: var l `eq'
+ }
+ }
+ if `"`value'"'=="" local value "`eq'"
+ local eqlabels `"`macval(eqlabels)' `"`value'"'"'
+ }
+ }
+ if `eqconssubok' {
+ if "`eqlabelsnone'"!="" & `numeqs'>1 & "`unstack'"=="" {
+ EqReplaceCons `"`varlist'"' `"`eqlist'"' `"`eqlabels'"' `"`macval(varlabels)'"'
+ if `"`macval(value)'"'!="" {
+ local varlabels `"`macval(value)' `macval(varlabels)'"'
+ }
+ }
+ }
+
+*Column labels
+ if `"`macval(collabels)'"'=="" {
+ forv j = 1/`ncols' {
+ local temp
+ forv i = 1/`nrows' {
+ local v: word `i' of `cells'
+ local v: word `j' of `v'
+ local v: subinstr local v "&" " ", all
+ local v: subinstr local v "." "", all
+ local v: list retok v
+ foreach vi of local v {
+ if `"`macval(temp)'"'!="" {
+ local temp `"`macval(temp)'/"'
+ }
+ local temp `"`macval(temp)'`macval(`vi'_label)'"'
+ }
+ }
+ local collabels `"`macval(collabels)'`"`macval(temp)'"' "'
+ }
+ }
+
+*Prepare refcat()
+ if `"`macval(refcat)'"'!="" {
+ PrepareRefcat `"`macval(refcat)'"'
+ }
+
+*Determine table layout
+ local m 1
+ local starcol 0
+ foreach model of local models {
+ local e 0
+ foreach eq of local eqswide {
+ local stc 0
+ local ++e
+ if "`unstack'"!="" & `R'>0 {
+ ModelEqCheck `B' `"`eq'"' `m' `ccols'
+ if !`value' continue
+ }
+ local eqsrow "`eqsrow'`e' "
+ local modelsrow "`modelsrow'`m' "
+ local k 0
+ local something 0
+ forv j = 1/`ncols' {
+ local col
+ local nocol 1
+ local colhasstats 0
+ forv i = 1/`nrows' {
+ local row: word `i' of `cells'
+ local v: word `j' of `row'
+ local v: subinstr local v "&" " ", all
+ foreach vi in `v' {
+ if "`vi'"=="." continue
+ local colhasstats 1
+ if "`unstack'"!="" {
+ if `:list eq in `vi'_eqdrop' continue
+ }
+ if "`:word `m' of ``vi'_pattern''"=="0" {
+ local v: subinstr local v "`vi'" ".`vi'", word
+ }
+ else {
+ local nocol 0
+ if `"``vi'_star'"'!="" local starcol 1
+ }
+ }
+ local v: subinstr local v " " "&", all
+ if "`v'"=="" local v "."
+ local col "`col'`v' "
+ }
+ if `colhasstats'==0 local nocol 0
+ if !`nocol' {
+ local colsrow "`colsrow'`j' "
+ if `++k'>1 {
+ local modelsrow "`modelsrow'`m' "
+ local eqsrow "`eqsrow'`e' "
+ }
+ if `"`: word `++stc' of `statscolstar''"'=="1" local starcol 1
+ local starsrow "`starsrow'`starcol' "
+ local starcol 0
+ Add2Vblock `"`vblock'"' "`col'"
+ local something 1
+ }
+ }
+ if !`something' {
+ local col
+ forv i = 1/`nrows' {
+ local col "`col'. "
+ }
+ Add2Vblock `"`vblock'"' "`col'"
+ local colsrow "`colsrow'1 "
+ if `"`: word `++stc' of `statscolstar''"'=="1" local starcol 1
+ local starsrow "`starsrow'`starcol' "
+ local starcol 0
+ }
+ }
+ local ++m
+ }
+ CountNofEqs "`modelsrow'" "`eqsrow'"
+ local neqs `value'
+ if `"`extracols'"'!="" {
+ foreach row in model eq col star {
+ InsertAtCols `"`extracols'"' `"``row'srow'"'
+ local `row'srow `"`value'"'
+ }
+ foreach row of local vblock {
+ InsertAtCols `"`extracols'"' `"`row'"'
+ local nvblock `"`nvblock' `"`value'"'"'
+ }
+ local vblock: list clean nvblock
+ }
+ local ncols = `: word count `starsrow'' + 1 + `haslabcol2'
+
+*Modelwidth/varwidth/starwidth
+ if "`modelwidth'"=="" local modelwidth 0
+ if "`varwidth'"=="" local varwidth 0
+ local nmodelwidth: list sizeof modelwidth
+ local modelwidthzero: list uniq modelwidth
+ local modelwidthzero = ("`modelwidth'"=="0")
+ if "`labcol2width'"=="" local labcol2width `: word 1 of `modelwidth''
+ local starwidth 0
+ if `modelwidthzero'==0 {
+ if `tablehasstars' | `"`statsstar'"'!="" {
+ Starwidth `"`macval(starlevels)'"'
+ local starwidth `value'
+ }
+ }
+ if `varwidth'<2 local wrap
+
+* totcharwidth / hline
+ local totcharwidth `varwidth'
+ capture {
+ local delwidth = length(`macval(delimiter)')
+ }
+ if _rc {
+ local delwidth = length(`"`macval(delimiter)'"')
+ }
+ if `haslabcol2' {
+ local totcharwidth = `totcharwidth' + `delwidth' + `labcol2width'
+ }
+ local j 0
+ foreach i of local starsrow {
+ local modelwidthj: word `=1 + mod(`j++',`nmodelwidth')' of `modelwidth'
+ local totcharwidth = `totcharwidth' + `delwidth' + `modelwidthj'
+ if `i' {
+ if "`stardetach'"!="" {
+ local ++ncols
+ local totcharwidth = `totcharwidth' + `delwidth'
+ }
+ local totcharwidth = `totcharwidth' + `starwidth'
+ }
+ }
+ IsInString "@hline" `"`0'"' // sets local strcount
+ if `strcount' {
+ local hline `totcharwidth'
+ if `hline'>400 local hline 400 // _dup(400) is limit
+ if `"`macval(hlinechar)'"'=="" local hlinechar "-"
+ local hline: di _dup(`hline') `"`macval(hlinechar)'"'
+ }
+ else local hline
+
+* check begin, delimiter, end
+ tempfile tfile
+ tempname file
+ file open `file' using `"`tfile'"', write text
+ foreach opt in begin delimiter end {
+ capture file write `file' `macval(`opt')'
+ if _rc {
+ local `opt' `"`"`macval(`opt')'"'"'
+ }
+ }
+ file close `file'
+
+* RTF support: set macros rtfrowdef, rtfrowdefbrdrt, rtfrowdefbrdrb, rtfemptyrow
+ local hasrtfbrdr 0
+ local rtfbrdron 0
+ IsInString "@rtfrowdef" `"`begin'"' // sets local strcount
+ local hasrtf = `strcount'
+ if `hasrtf' {
+ MakeRtfRowdefs `"`macval(begin)'"' `"`starsrow'"' "`stardetach'" ///
+ `varwidth' "`modelwidth'" `haslabcol2' `labcol2width'
+ local varwidth 0
+ local wrap
+ local modelwidth 0
+ local nmodelwidth 1
+ local modelwidthzero 1
+ local starwidth 0
+ local labcol2width 0
+ IsInString "@rtfrowdefbrdr" `"`begin'"' // sets local strcount
+ if `strcount' {
+ local hasrtfbrdr 1
+ local rtfbeginbak `"`macval(begin)'"'
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrt'"'
+ local rtfbrdron 1
+ }
+ else {
+ local begin: subinstr local begin "@rtfrowdef" `"`rtfrowdef'"'
+ }
+ }
+
+* set widths
+ if `starwidth'>0 local fmt_stw "%-`starwidth's"
+ if `varwidth'>0 local fmt_v "%-`varwidth's"
+ if `labcol2width'>0 local fmt_l2 "%~`labcol2width's"
+ if "`mgroupsspan'`mlabelsspan'`eqlabelsspan'`collabelsspan'"!="" {
+ if `modelwidthzero'==0 {
+ file open `file' using `"`tfile'"', write text replace
+ file write `file' `macval(delimiter)'
+ file close `file'
+ file open `file' using `"`tfile'"', read text
+ file read `file' delwidth
+ file close `file'
+ local delwidth = length(`"`macval(delwidth)'"')
+ }
+ else local delwidth 0
+ }
+ local stardetachon = ("`stardetach'"!="")
+ if `stardetachon' {
+ local stardetach `"`macval(delimiter)'"'
+ }
+
+*Prepare @-Variables
+ local atvars2 `""`nmodels'" "`neqs'" "`totcharwidth'" `"`macval(hline)'"' `hasrtf' `"`rtfrowdefbrdrt'"' `"`rtfrowdefbrdrb'"' `"`rtfrowdef'"' `"`rtfemptyrow'"'"'
+ local atvars3 `"`"`macval(title)'"' `"`macval(note)'"' `"`macval(discrete)'`macval(discrete2)'"' `"`macval(starlegend)'"'"'
+
+*Open output file
+ file open `file' using `"`tfile'"', write text replace
+
+*Write prehead
+ if `"`macval(prehead)'"'!="" {
+ if index(`"`macval(prehead)'"',`"""')==0 {
+ local prehead `"`"`macval(prehead)'"'"'
+ }
+ }
+ foreach line of local prehead {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(line)'"' 0 "`ncols'" `macval(atvars2)' `macval(atvars3)'
+ file write `file' `"`macval(value)'"' _n
+ }
+ local hasheader 0
+ if "`smcltags'"!="" local thesmclrule "{txt}{hline `totcharwidth'}"
+ else local thesmclrule "{hline `totcharwidth'}"
+ if "`smclrules'"!="" {
+ file write `file' `"`thesmclrule'"' _n
+ }
+
+*Labcol2 - title
+ if `haslabcol2' {
+ IsInString `"""' `"`macval(labcol2title)'"' // sets local strcount
+ if `strcount'==0 {
+ local labcol2chunk `"`macval(labcol2title)'"'
+ local labcol2rest ""
+ }
+ else {
+ gettoken labcol2chunk labcol2rest : labcol2title
+ }
+ }
+
+*Write head: Models groups
+ if "`mgroupsnone'"=="" & `"`macval(mgroups)'"'!="" {
+ local hasheader 1
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(mgroupsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local mgroupsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(mgroupsend)'"' 2 "`ncols'" `macval(atvars2)'
+ local mgroupsend `"`macval(value)'"'
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`mgroupsreplace'"!="" {
+ if `"`macval(mgroupsbegin)'"'!="" local tmpbegin
+ if `"`macval(mgroupsend)'"'!="" local tmpend
+ }
+ MgroupsPattern "`modelsrow'" "`mgroupspattern'"
+ Abbrev `varwidth' `"`macval(mgroupslhs)'"' "`abbrev'"
+ WriteBegin `"`file'"' `"`macval(mgroupsbegin)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(value)'"')"'
+ if `haslabcol2' {
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ WriteCaption `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`mgroupspattern'" "`mgroupspattern'" ///
+ `"`macval(mgroups)'"' "`starsrow'" "`mgroupsspan'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'" ///
+ `"`macval(mgroupserepeat)'"' `"`macval(mgroupsprefix)'"' ///
+ `"`macval(mgroupssuffix)'"'
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(mgroupsend)'"' ///
+ `"`"`macval(value)'"'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ gettoken labcol2chunk labcol2rest : labcol2rest
+ }
+
+*Write head: Models numbers
+ if `"`macval(numbers)'"'!="" {
+ local hasheader 1
+ if "`smcltags'"!="" file write `file' "{txt}"
+ if `"`macval(numbers)'"'=="numbers" local numbers "( )"
+ file write `file' `macval(begin)' `fmt_v' (`""')
+ if `haslabcol2' {
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ tokenize `"`macval(numbers)'"'
+ numlist `"1/`nmodels'"'
+ WriteCaption `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`modelsrow'" "`modelsrow'" ///
+ "`r(numlist)'" "`starsrow'" "`mlabelsspan'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'" ///
+ `""' `"`macval(1)'"' `"`macval(2)'"'
+ file write `file' `macval(end)' _n
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ gettoken labcol2chunk labcol2rest : labcol2rest
+ }
+
+*Write head: Models captions
+ if "`nomlabelsnone'"=="" & "`models'"=="." & `"`macval(mlabels)'"'=="." local mlabelsnone "none"
+ if "`mlabelsnone'"=="" {
+ local hasheader 1
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(mlabelsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local mlabelsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(mlabelsend)'"' 2 "`ncols'" `macval(atvars2)''
+ local mlabelsend `"`macval(value)'"'
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`mlabelsreplace'"!="" {
+ if `"`macval(mlabelsbegin)'"'!="" local tmpbegin
+ if `"`macval(mlabelsend)'"'!="" local tmpend
+ }
+ Abbrev `varwidth' `"`macval(mlabelslhs)'"' "`abbrev'"
+ WriteBegin `"`file'"' `"`macval(mlabelsbegin)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(value)'"')"'
+ if `haslabcol2' {
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ WriteCaption `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`modelsrow'" "`modelsrow'" ///
+ `"`macval(mlabels)'"' "`starsrow'" "`mlabelsspan'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'" ///
+ `"`macval(mlabelserepeat)'"' `"`macval(mlabelsprefix)'"' ///
+ `"`macval(mlabelssuffix)'"'
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(mlabelsend)'"' ///
+ `"`"`macval(value)'"'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ gettoken labcol2chunk labcol2rest : labcol2rest
+ }
+
+*Write head: Equations captions
+ if "`eqlabelsnone'"=="" {
+ InsertAtVariables `"`macval(eqlabelsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local eqlabelsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(eqlabelsend)'"' 2 "`ncols'" `macval(atvars2)'
+ local eqlabelsend `"`macval(value)'"'
+ }
+ if `"`eqswide'"'!="_" & "`eqlabelsnone'"=="" {
+ local hasheader 1
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`eqlabelsreplace'"!="" {
+ if `"`macval(eqlabelsbegin)'"'!="" local tmpbegin
+ if `"`macval(eqlabelsend)'"'!="" local tmpend
+ }
+ if "`smcltags'"!="" file write `file' "{txt}"
+ Abbrev `varwidth' `"`macval(eqlabelslhs)'"' "`abbrev'"
+ WriteBegin `"`file'"' `"`macval(eqlabelsbegin)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(value)'"')"'
+ if `haslabcol2' {
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ WriteCaption `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`eqsrow'" "`modelsrow'" ///
+ `"`macval(eqlabels)'"' "`starsrow'" "`eqlabelsspan'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'" ///
+ `"`macval(eqlabelserepeat)'"' `"`macval(eqlabelsprefix)'"' ///
+ `"`macval(eqlabelssuffix)'"'
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(eqlabelsend)'"' ///
+ `"`"`macval(value)'"'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ gettoken labcol2chunk labcol2rest : labcol2rest
+ }
+
+*Write head: Columns captions
+ if `"`macval(collabels)'"'!="" & "`collabelsnone'"=="" {
+ local hasheader 1
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(collabelsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local collabelsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(collabelsend)'"' 2 "`ncols'" `macval(atvars2)'
+ local collabelsend `"`macval(value)'"'
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`collabelsreplace'"!="" {
+ if `"`macval(collabelsbegin)'"'!="" local tmpbegin
+ if `"`macval(collabelsend)'"'!="" local tmpend
+ }
+ Abbrev `varwidth' `"`macval(collabelslhs)'"' "`abbrev'"
+ WriteBegin `"`file'"' `"`macval(collabelsbegin)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(value)'"')"'
+ if `haslabcol2' {
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ WriteCaption `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`colsrow'" "" `"`macval(collabels)'"' ///
+ "`starsrow'" "`collabelsspan'" "`abbrev'" "`modelwidth'" ///
+ "`delwidth'" "`starwidth'" `"`macval(collabelserepeat)'"' ///
+ `"`macval(collabelsprefix)'"' `"`macval(collabelssuffix)'"'
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(collabelsend)'"' ///
+ `"`"`macval(value)'"'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ gettoken labcol2chunk labcol2rest : labcol2rest
+ }
+
+*Write posthead
+ if `hasheader' & "`smclmidrules'"!="" {
+ file write `file' `"`thesmclrule'"' _n
+ }
+ if `"`macval(posthead)'"'!="" {
+ if index(`"`macval(posthead)'"',`"""')==0 {
+ local posthead `"`"`macval(posthead)'"'"'
+ }
+ }
+ foreach line of local posthead {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(line)'"' 0 "`ncols'" `macval(atvars2)' `macval(atvars3)'
+ file write `file' `"`macval(value)'"' _n
+ }
+
+* Create mmd alignment/divider line
+ if `"`defaults'"'=="mmd" {
+ MakeMMDdef "`varwidth'" "`haslabcol2'" "`labcol2width'" ///
+ "`modelwidth'" "`starsrow'" "`stardetachon'" "`starwidth'"
+ file write `file' `"`macval(value)'"' _n
+ }
+
+*Write body of table
+*Loop over table rows
+ InsertAtVariables `"`macval(varlabelsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local varlabelsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(varlabelsend)'"' 2 "`ncols'" `macval(atvars2)'
+ local varlabelsend `"`macval(value)'"'
+ tempname first
+ if `"`vblock'"'!="" {
+ local RI = `R' + `nindicate'
+ local e 0
+ local eqdim = `R' + `nindicate'
+ local weqcnt 0
+ local theeqlabel
+ if `hasrtfbrdr' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrt'"'
+ local rtfbrdron 1
+ }
+ local varlabelsbegin0 `"`macval(varlabelsbegin)'"'
+ local eqlabelsbegin0 `"`macval(eqlabelsbegin)'"'
+ if "`eqlabelsfirst'"=="" local eqlabelsbegin0
+ forv r = 1/`R' {
+ local varlabelsend0 `"`macval(varlabelsend)'"'
+ local var: word `r' of `varlist'
+
+*Write equation name/label
+ if "`unstack'"=="" {
+ local eqvar: word `r' of `fullvarlist'
+ if `"`eqs'"'!="_" {
+ local eqrlast `"`eqr'"'
+ local eqr: word `r' of `eqlist'
+ if `"`eqr'"'!=`"`eqrlast'"' & "`eqlabelsnone'"=="" {
+ local value: word `++e' of `macval(eqlabels)'
+ local eqdim: word `e' of `macval(eqsdims)'
+ local weqcnt 0
+ if `e'==`numeqs' {
+ if "`eqlabelslast'"=="" local eqlabelsend
+ local eqdim = `eqdim' + `nindicate'
+ }
+ if "`eqlabelsmerge'"!="" {
+ local theeqlabel `"`macval(eqlabelsprefix)'`macval(value)'`macval(eqlabelssuffix)'"'
+ }
+ else {
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`eqlabelsreplace'"!="" {
+ if `"`macval(eqlabelsbegin0)'"'!="" local tmpbegin
+ if `"`macval(eqlabelsend)'"'!="" local tmpend
+ }
+ if `e'>1 & "`smcleqrules'"!="" {
+ file write `file' `"`thesmclrule'"' _n
+ }
+ WriteBegin `"`file'"' `"`macval(eqlabelsbegin0)'"' `"`macval(tmpbegin)'"'
+ if "`smcltags'"!="" file write `file' "{res}"
+ WriteEqrow `"`file'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' `"`macval(value)'"' "`starsrow'" ///
+ "`eqlabelsspan'" "`varwidth'" "`fmt_v'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'" ///
+ `"`macval(eqlabelsprefix)'"' `"`macval(eqlabelssuffix)'"' ///
+ "`haslabcol2'" "`labcol2width'" "`fmt_l2'"
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(eqlabelsend)'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ local eqlabelsbegin0 `"`macval(eqlabelsbegin)'"'
+ }
+ }
+ }
+ }
+ local ++weqcnt
+ if `weqcnt'==1 {
+ if "`varlabelsfirst'"=="" local varlabelsbegin0
+ }
+
+*Determine rows to be written
+ local rvblock
+ foreach row of local vblock {
+ local c 0
+ local skiprow 1
+ local rowhasstats 0
+ foreach v of local row {
+ local ++c
+ if "`unstack'"!="" {
+ local eqr: word `:word `c' of `eqsrow'' of `eqs'
+ if `"`eqr'"'!="" local eqvar `"`eqr':`var'"'
+ else local eqvar "`var'"
+ }
+ local v: subinstr local v "&" " ", all
+ foreach vi of local v {
+ if "`vi'"=="." continue
+ if rownumb(`B',`"`eqvar'"')<. {
+ local rowhasstats 1
+ if index("`vi'",".")==1 continue
+ if `: list eqvar in `vi'_drop' continue
+ local skiprow 0
+ continue, break
+ }
+ }
+ if `skiprow'==0 continue, break
+ }
+ if `rowhasstats'==0 local skiprow 0
+ if `"`ferest()'"'=="" & `"`rvblock'"'=="" local skiprow 0
+ if `skiprow' continue
+ local rvblock `"`rvblock'"`row'" "'
+ }
+ local nrvblock: list sizeof rvblock
+
+*Insert refcat() (unless refcatbelow)
+ if `"`macval(refcat)'"'!="" {
+ local isref: list posof "`var'" in refcatcoefs
+ if `isref' {
+ if "`unstack'"=="" {
+ local temp `"`eqr'"'
+ if `"`temp'"'=="" local temp "_"
+ }
+ else local temp `"`eqswide'"'
+ GenerateRefcatRow `B' `ccols' "`var'" `"`temp'"' `"`macval(refcatlabel)'"'
+ local refcatrow `"`macval(value)'"'
+ }
+ }
+ else local isref 0
+ if `isref' & `"`refcatbelow'"'=="" {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`varlabelsreplace'"!="" {
+ if `"`macval(varlabelsbegin0)'"'!="" local tmpbegin
+ if `"`macval(varlabelsend0)'"'!="" local tmpend
+ }
+ if "`varlabelsnone'"=="" {
+ local value: word `isref' of `macval(refcatnames)'
+ Abbrev `varwidth' `"`macval(value)'"' "`abbrev'"
+ }
+ else local value
+ WriteBegin `"`file'"' `"`macval(varlabelsbegin0)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(varlabelsprefix)'`macval(value)'`macval(varlabelssuffix)'"')"'
+ if `haslabcol2' {
+ gettoken labcol2chunk labcol2 : labcol2
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ if "`smcltags'"!="" file write `file' "{res}"
+ WriteStrRow `"`file'"' "`modelsrow'" `"`eqsrow'"' `"`: list sizeof eqswide'"' ///
+ `"`macval(refcatrow)'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`starsrow'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'"
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(varlabelsend0)'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ local varlabelsbegin0 `"`macval(varlabelsbegin)'"'
+ }
+
+*Write variable name/label
+ if "`smcltags'"!="" file write `file' "{txt}"
+ local tmpbegin `"`macval(begin)'"'
+ if "`varlabelsnone'"=="" {
+ VarInList `"`var'"' "`unstack'" `"`eqvar'"' ///
+ `"`eqr'"' `"`macval(varlabelsblist)'"'
+ if `"`macval(value)'"'!="" {
+ IsInString `"""' `"`value'"' // sets local strcount
+ if `strcount'==0 {
+ local value `"`"`macval(value)'"'"'
+ }
+ InsertAtVariables `"`macval(value)'"' 2 "`ncols'" `macval(atvars2)'
+ WriteStrLines `"`file'"' `"`macval(value)'"'
+ if "`varlabelsreplace'"!="" {
+ local tmpbegin
+ local varlabelsbegin0
+ }
+ }
+ if "`label'"!="" {
+ local temp = index("`var'",".")
+ local temp2 = substr(`"`var'"',`temp'+1,.)
+ capture local varl: var l `temp2'
+ if _rc | `"`varl'"'=="" {
+ local varl `"`temp2'"'
+ }
+ local temp2 = substr(`"`var'"',1,`temp')
+ local varl `"`temp2'`macval(varl)'"'
+ }
+ else local varl `var'
+ VarInList `"`var'"' "`unstack'" `"`eqvar'"' ///
+ `"`eqr'"' `"`macval(varlabels)'"'
+ if `"`macval(value)'"'!="" {
+ local varl `"`macval(value)'"'
+ }
+ if `"`macval(discrete)'"'!="" {
+ local temp 0
+ if "`unstack'"=="" {
+ if `D'[`r',1]==1 local temp 1
+ }
+ else {
+ foreach eqr of local eqswide {
+ if `D'[rownumb(`D',`"`eqr':`var'"'),1]==1 local temp 1
+ }
+ }
+ if `temp'==1 & `temp'<. {
+ local varl `"`macval(varl)'`macval(discrete)'"'
+ }
+ }
+ }
+ else local varl
+ if `hasrtfbrdr' & `r'==`RI' & !(`isref' & `"`refcatbelow'"'!="") {
+ if `nrvblock'==1 {
+ local tmpbegin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrb'"'
+ local rtfbrdron 1
+ }
+ }
+ if "`varlabelsreplace'"!="" {
+ if `"`macval(varlabelsbegin0)'"'!="" local tmpbegin
+ }
+ if "`wrap'"!="" & `nrvblock'>1 {
+ local wrap_i 1
+ local value: piece `wrap_i' `varwidth' of `"`macval(theeqlabel)'`macval(varl)'"', nobreak
+ Abbrev `varwidth' `"`macval(value)'"' "`abbrev'"
+ }
+ else {
+ Abbrev `varwidth' `"`macval(theeqlabel)'`macval(varl)'"' "`abbrev'"
+ }
+ WriteBegin `"`file'"' `"`macval(varlabelsbegin0)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(varlabelsprefix)'`macval(value)'`macval(varlabelssuffix)'"')"'
+ if `haslabcol2' {
+ gettoken labcol2chunk labcol2 : labcol2
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ local varlabelsbegin0 `"`macval(varlabelsbegin)'"'
+
+*Write table cells
+ if "`smcltags'"!="" file write `file' "{res}"
+ local newrow 0
+ mat `first'=J(1,`nmodels',1)
+ foreach row of local rvblock {
+ if `hasrtfbrdr' & `r'==`RI' & !(`isref' & `"`refcatbelow'"'!="") {
+ if `"`ferest()'"'=="" {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrb'"'
+ local rtfbrdron 1
+ }
+ }
+ local c 0
+ foreach v of local row {
+ local m: word `++c' of `modelsrow'
+ local unstackskipcoef 0
+ if "`unstack'"!="" {
+ capt local eqr: word `:word `c' of `eqsrow'' of `eqs'
+ local rr=rownumb(`B',`"`eqr':`var'"')
+ if `"`eqr'"'!="" local eqvar `"`eqr':`var'"'
+ else local eqvar "`var'"
+ if `rr'>=. local unstackskipcoef 1 // local v "."
+ }
+ else local rr `r'
+ if `newrow' & `c'==1 {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ if "`wrap'"!="" & `nrvblock'>1 {
+ local value
+ local space
+ while (1) {
+ local temp: piece `++wrap_i' `varwidth' of `"`macval(varl)'"', nobreak
+ if `"`macval(temp)'"'=="" continue, break
+ local value `"`macval(value)'`space'`macval(temp)'"'
+ if `wrap_i'<`nrvblock' continue, break
+ local space " "
+ }
+ Abbrev `varwidth' `"`macval(value)'"' "`abbrev'"
+ local value `"`fmt_v' (`"`macval(varlabelsprefix)'`macval(value)'`macval(varlabelssuffix)'"')"'
+ }
+ else local value "_skip(`varwidth')"
+ file write `file' `macval(end)' _n `macval(begin)' `value'
+ if `haslabcol2' {
+ file write `file' `macval(delimiter)' `fmt_l2' ("")
+ }
+ if "`smcltags'"!="" file write `file' "{res}"
+ }
+ local v: subinstr local v "&" " ", all
+ local modelwidthj: word `=1+mod(`c'-1,`nmodelwidth')' of `modelwidth'
+ if `modelwidthj'>0 local fmt_m "%`modelwidthj's"
+ else local fmt_m
+ local thevalue
+ foreach vi of local v {
+ if index("`vi'",".")!=1 {
+ if `: list eqvar in `vi'_drop' local vi "..`vi'"
+ else {
+ local vipar: subinstr local `vi'_par "@modelwidth" "`modelwidthj'", all
+ }
+ }
+ if index("`vi'",".")==1 {
+ local value
+ }
+ else if `unstackskipcoef' {
+ local value `"``vi'_vacant'"'
+ }
+ else if `B'[`rr',`m'*`droppedpos']==1 & `droppedison' {
+ if `first'[1,`m'] {
+ local value `"`macval(dropped)'"'
+ mat `first'[1,`m']=0
+ }
+ else local value
+ }
+ else if "``vi'_'"=="ci" {
+ if `_`vi'_l'[`rr',`m']>=.y local value `"``vi'_vacant'"'
+ else {
+ local format: word `r' of `ci_fmt'
+ if "`format'"=="" {
+ local format: word `:word count ``vi'_fmt'' of ``vi'_fmt'
+ }
+ local value = `_`vi'_l'[`rr',`m']
+ local vipar: subinstr local `vi'_l_par "@modelwidth" "`modelwidthj'", all
+ vFormat `value' `format' "`lz'" `"`macval(dmarker)'"' ///
+ `"`macval(msign)'"' `"`macval(vipar)'"'
+ local temp "`macval(value)'"
+ local value = `_`vi'_u'[`rr',`m']
+ local vipar: subinstr local `vi'_u_par "@modelwidth" "`modelwidthj'", all
+ vFormat `value' `format' "`lz'" `"`macval(dmarker)'"' ///
+ `"`macval(msign)'"' `"`macval(vipar)'"'
+ local value `"`macval(temp)'`macval(value)'"'
+ }
+ }
+ else if `_`vi''[`rr',`m']>=.y local value `"``vi'_vacant'"'
+ //else if `_`vi''[`rr',`m']>=. local value .
+ else if "``vi'_'"=="_star" {
+ CellStars `"`macval(starlevels)'"' `_```vi'_pvalue'_tname''[`rr',`m'] `"`macval(vipar)'"'
+ }
+ else if "``vi'_'"=="_sign" {
+ MakeSign `_`vi''[`rr',`m'] `"`macval(msign)'"' `"`macval(vipar)'"'
+ }
+ else if "``vi'_'"=="_sigsign" {
+ MakeSign `_`vi''[`rr',`m'] `"`macval(msign)'"' `"`macval(vipar)'"' ///
+ `"`macval(starlevels)'"' `_```vi'_pvalue'_tname''[`rr',`m']
+ }
+ else {
+ local format: word `r' of ``vi'_fmt'
+ if "`format'"=="" {
+ local format: word `:word count ``vi'_fmt'' of ``vi'_fmt'
+ }
+ local value = `_`vi''[`rr',`m']
+ vFormat `value' `format' "`lz'" `"`macval(dmarker)'"' ///
+ `"`macval(msign)'"' `"`macval(vipar)'"'
+ }
+ local thevalue `"`macval(thevalue)'`macval(value)'"'
+ if !`stardetachon' & `:word `c' of `starsrow''==1 {
+ if `modelwidthj'>0 | `starwidth'>0 local fmt_m "%`=`modelwidthj'+`starwidth''s"
+ local value
+ if index("`vi'",".")!=1 & `"``vi'_star'"'!="" {
+ if !`: list eqvar in stardrop' {
+ Stars `"`macval(starlevels)'"' `_```vi'_pvalue'_tname''[`rr',`m']
+ }
+ }
+ if "`ferest()'"=="" {
+ local value: di `fmt_stw' `"`macval(value)'"'
+ }
+ local thevalue `"`macval(thevalue)'`macval(value)'"'
+ }
+ if "`ferest()'"!="" & index("`vi'","..")!=1 {
+ local thevalue `"`macval(thevalue)'`macval(incelldelimiter)'"'
+ }
+ }
+ file write `file' `macval(delimiter)' `fmt_m' (`"`macval(thevalue)'"')
+ if `stardetachon' & `:word `c' of `starsrow''==1 {
+ local thevalue
+ foreach vi of local v {
+ if index("`vi'",".")!=1 {
+ if `: list eqvar in `vi'_drop' local vi "..`vi'"
+ }
+ if index("`vi'",".")!=1 & `"``vi'_star'"'!="" {
+ if `: list eqvar in stardrop' local value
+ else {
+ Stars `"`macval(starlevels)'"' `_```vi'_pvalue'_tname''[`rr',`m']
+ }
+ local thevalue `"`macval(thevalue)'`macval(value)'"'
+ }
+ if "`ferest()'"!="" & index("`vi'","..")!=1 {
+ local thevalue `"`macval(thevalue)'`macval(incelldelimiter)'"'
+ }
+ }
+ file write `file' `macval(stardetach)' `fmt_stw' (`"`macval(thevalue)'"')
+ }
+ }
+ local newrow 1
+ }
+
+*End of table row
+ if "`smcltags'"!="" file write `file' "{txt}"
+ if `weqcnt'==`eqdim' & "`varlabelslast'"=="" ///
+ & !(`isref' & `"`refcatbelow'"'!="") local varlabelsend0
+ local tmpend `"`macval(end)'"'
+ if "`varlabelsreplace'"!="" {
+ if `"`macval(varlabelsend0)'"'!="" local tmpend
+ }
+ VarInList `"`var'"' "`unstack'" `"`eqvar'"' `"`eqr'"' ///
+ `"`macval(varlabelselist)'"'
+ if `"`macval(value)'"'!="" {
+ IsInString `"""' `"`value'"' // sets local strcount
+ if `strcount'==0 {
+ local value `"`"`macval(value)'"'"'
+ }
+ InsertAtVariables `"`macval(value)'"' 2 "`ncols'" `macval(atvars2)'
+ if "`varlabelsreplace'"!="" local varlabelsend0
+ }
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(varlabelsend0)'"' ///
+ `"`macval(value)'"'
+* insert refcat() (if refcatbelow)
+ if `isref' & `"`refcatbelow'"'!="" {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ if `hasrtfbrdr' & `r'==`RI' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrb'"'
+ local rtfbrdron 1
+ }
+ if `weqcnt'==`eqdim' & "`varlabelslast'"=="" local varlabelsend0
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`varlabelsreplace'"!="" {
+ if `"`macval(varlabelsbegin0)'"'!="" local tmpbegin
+ if `"`macval(varlabelsend0)'"'!="" local tmpend
+ }
+ if "`varlabelsnone'"=="" {
+ local value: word `isref' of `macval(refcatnames)'
+ Abbrev `varwidth' `"`macval(value)'"' "`abbrev'"
+ }
+ else local value
+ WriteBegin `"`file'"' `"`macval(varlabelsbegin0)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(varlabelsprefix)'`macval(value)'`macval(varlabelssuffix)'"')"'
+ if `haslabcol2' {
+ gettoken labcol2chunk labcol2 : labcol2
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ if "`smcltags'"!="" file write `file' "{res}"
+ WriteStrRow `"`file'"' "`modelsrow'" `"`eqsrow'"' `"`: list sizeof eqswide'"' ///
+ `"`macval(refcatrow)'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`starsrow'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'"
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(varlabelsend0)'"'
+ }
+* end insert refcat()
+ }
+ }
+
+*Write indicator sets
+ forv i=1/`nindicate' {
+ if `hasrtfbrdr' & `i'==`nindicate' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrb'"'
+ local rtfbrdron 1
+ }
+ if `i'==`nindicate' & "`varlabelslast'"=="" local varlabelsend
+ local tmpbegin `"`macval(begin)'"'
+ local tmpend `"`macval(end)'"'
+ if "`varlabelsreplace'"!="" {
+ if `"`macval(varlabelsbegin0)'"'!="" local tmpbegin
+ if `"`macval(varlabelsend)'"'!="" local tmpend
+ }
+ if "`varlabelsnone'"=="" {
+ Abbrev `varwidth' `"`macval(indicate`i'name)'"' "`abbrev'"
+ }
+ else local value
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteBegin `"`file'"' `"`macval(varlabelsbegin0)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(varlabelsprefix)'`macval(value)'`macval(varlabelssuffix)'"')"'
+ if `haslabcol2' {
+ gettoken labcol2chunk labcol2 : labcol2
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ if "`smcltags'"!="" file write `file' "{res}"
+ WriteStrRow `"`file'"' "`modelsrow'" `"`eqsrow'"' `"`: list sizeof eqswide'"' ///
+ `"`macval(indicate`i'lbls)'"' `"`macval(delimiter)'"' ///
+ `"`macval(stardetach)'"' "`starsrow'" "`abbrev'" ///
+ "`modelwidth'" "`delwidth'" "`starwidth'"
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(varlabelsend)'"'
+ }
+
+*Write prefoot
+ if `"`macval(prefoot)'"'!="" {
+ if index(`"`macval(prefoot)'"',`"""')==0 {
+ local prefoot `"`"`macval(prefoot)'"'"'
+ }
+ }
+ foreach line of local prefoot {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(line)'"' 0 "`ncols'" `macval(atvars2)' `macval(atvars3)'
+ file write `file' `"`macval(value)'"' _n
+ }
+ if ((`"`vblock'"'!="" & `R'>0) | `nindicate'>0) & "`smclmidrules'"!="" {
+ if `"`macval(statsarray)'"'!="" {
+ file write `file' `"`thesmclrule'"' _n
+ }
+ }
+
+*Write foot of table (statistics)
+ InsertAtVariables `"`macval(statslabelsbegin)'"' 2 "`ncols'" `macval(atvars2)'
+ local statslabelsbegin `"`macval(value)'"'
+ InsertAtVariables `"`macval(statslabelsend)'"' 2 "`ncols'" `macval(atvars2)'
+ local statslabelsend `"`macval(value)'"'
+ local statslabelsbegin0 `"`macval(statslabelsbegin)'"'
+ local S: list sizeof statsarray
+ local eqr "_"
+ if `hasrtfbrdr' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrt'"'
+ local rtfbrdron 1
+ }
+ forv r = 1/`S' {
+ if `r'==`S' & `hasrtfbrdr' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdefbrdrb'"'
+ local rtfbrdron 1
+ }
+ local stat: word `r' of `macval(statslabels)'
+ if `"`stat'"'=="" local stat: word `r' of `statsrowlbls'
+ if "`statslabelsnone'"!="" local stat
+ if "`smcltags'"!="" file write `file' "{txt}"
+ if `r'==1 & "`statslabelsfirst'"=="" local statslabelsbegin0
+ local tmpbegin `"`macval(begin)'"'
+ if "`statslabelsreplace'"!="" {
+ if `"`macval(statslabelsbegin0)'"'!="" local tmpbegin
+ }
+ Abbrev `varwidth' `"`macval(stat)'"' "`abbrev'"
+ WriteBegin `"`file'"' `"`macval(statslabelsbegin0)'"' `"`macval(tmpbegin)'"' ///
+ `"`fmt_v' (`"`macval(statslabelsprefix)'`macval(value)'`macval(statslabelssuffix)'"')"'
+ if `r'==1 & "`statslabelsfirst'"=="" {
+ local statslabelsbegin0 `"`macval(statslabelsbegin)'"'
+ }
+ if `haslabcol2' {
+ gettoken labcol2chunk labcol2 : labcol2
+ Abbrev `labcol2width' `"`macval(labcol2chunk)'"' "`abbrev'"
+ file write `file' `macval(delimiter)' `fmt_l2' (`"`macval(value)'"')
+ }
+ if "`smcltags'"!="" file write `file' "{res}"
+ local strow: word `r' of `statsarray'
+ local strowlay: word `r' of `macval(statslayout)'
+ local strowfmt: word `r' of `statsrowfmt'
+ local strowstar: word `r' of `statsrowstar'
+ local lastm
+ local lasteq
+ local c 0
+ local mpos 0
+ foreach m of local modelsrow {
+ local ++c
+ local modelwidthj: word `=1+mod(`c'-1,`nmodelwidth')' of `modelwidth'
+ if `modelwidthj'>0 local fmt_m "%`modelwidthj's"
+ else local fmt_m
+ if "`m'"=="." {
+ file write `file' `macval(delimiter)' `fmt_m' (`""')
+ continue
+ }
+ local value
+ local eq: word `:word `c' of `eqsrow'' of `eqs'
+ if "`m'"!="`lastm'" {
+ local stc 0
+ local hasmestats 0
+ }
+ if "`m'"!="`lastm'" | `"`eq'"'!="`lasteq'" local stc_eq 0
+ local usemestats 0
+ local ++stc_eq
+ local stcell: word `++stc' of `strow'
+ local stcelllay: word `stc' of `macval(strowlay)'
+ local stcellfmt: word `stc' of `strowfmt'
+ local stcellstar: word `stc' of `strowstar'
+ local cellhasstat 0
+ foreach stat of local stcell {
+ gettoken format stcellfmt: stcellfmt
+ local rr = rownumb(`St',`"`stat'"')
+ local value = `St'[`rr',`m']
+ if `value'==.y {
+ local value `"`return(m`m'_`stat')'"'
+ if `"`value'"'!="" {
+ local cellhasstat 1
+ local stcelllay: subinstr local stcelllay `"`statspchar'"' ///
+ `"`value'"'
+ }
+ }
+ else if `value'==.x {
+ local hasmestats 1
+ }
+ else if `value'<.x {
+ local cellhasstat 1
+ vFormat `value' "`format'" "`lz'" `"`macval(dmarker)'"' ///
+ `"`macval(msign)'"'
+ local stcelllay: subinstr local stcelllay `"`statspchar'"' ///
+ `"`macval(value)'"'
+ }
+ }
+ if `cellhasstat'==0 & `hasmestats' {
+ local stcell: word `stc_eq' of `strow'
+ local stcelllay: word `stc_eq' of `macval(strowlay)'
+ local stcellfmt: word `stc_eq' of `strowfmt'
+ local stcellstar: word `stc_eq' of `strowstar'
+ local cellhasstat 0
+ foreach stat of local stcell {
+ gettoken format stcellfmt: stcellfmt
+ local rr = rownumb(`St',`"`eq':`stat'"')
+ if `rr'>=. local value .z
+ else local value = `St'[`rr',`m']
+ if `value'!=.z {
+ local cellhasstat 1
+ vFormat `value' "`format'" "`lz'" `"`macval(dmarker)'"' ///
+ `"`macval(msign)'"'
+ local stcelllay: subinstr local stcelllay `"`statspchar'"' `"`macval(value)'"'
+ }
+ }
+ if `cellhasstat' local usemestats 1
+ }
+ if `cellhasstat'==0 local stcelllay
+ file write `file' `macval(delimiter)' `fmt_m' (`"`macval(stcelllay)'"')
+ if `:word `c' of `starsrow''==1 {
+ if "`stcellstar'"=="1" & `cellhasstat' {
+ if `usemestats' {
+ local rr=rownumb(`St',`"`eq':p"')
+ }
+ else {
+ local rr=rownumb(`St',"p")
+ }
+ Stars `"`macval(starlevels)'"' `St'[`rr',`m']
+ file write `file' `macval(stardetach)' `fmt_stw' (`"`macval(value)'"')
+ }
+ else {
+ file write `file' `macval(stardetach)' _skip(`starwidth')
+ }
+ }
+ local lastm "`m'"
+ local lasteq `"`eq'"'
+ }
+ if `r'==`S' & "`statslabelslast'"=="" local statslabelsend
+ local tmpend `"`macval(end)'"'
+ if "`statslabelsreplace'"!="" {
+ if `"`macval(statslabelsend)'"'!="" local tmpend
+ }
+ if "`smcltags'"!="" file write `file' "{txt}"
+ WriteEnd `"`file'"' `"`macval(tmpend)'"' `"`macval(statslabelsend)'"'
+ if `hasrtfbrdr' & `rtfbrdron' {
+ local begin: subinstr local rtfbeginbak "@rtfrowdefbrdr" `"`rtfrowdef'"'
+ local rtfbrdron 0
+ }
+ }
+
+*Write postfoot
+ if "`smclrules'"!="" {
+ file write `file' `"`thesmclrule'"' _n
+ }
+ local discrete: list retok discrete
+ if `"`macval(postfoot)'"'!="" {
+ if index(`"`macval(postfoot)'"',`"""')==0 {
+ local postfoot `"`"`macval(postfoot)'"'"'
+ }
+ }
+ foreach line of local postfoot {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ InsertAtVariables `"`macval(line)'"' 0 "`ncols'" `macval(atvars2)' `macval(atvars3)'
+ file write `file' `"`macval(value)'"' _n
+ }
+
+*Write legend (starlevels, marginals)
+ if "`legend'"!="" {
+ if `"`macval(discrete2)'"'!="" {
+ mat `D' = `D''*`D'
+ if `D'[1,1]!=0 {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ file write `file' `"`macval(discrete)'`macval(discrete2)'"' _n
+ }
+ }
+ if `"`macval(starlegend)'"'!="" {
+ if "`smcltags'"!="" file write `file' "{txt}"
+ file write `file' `"`macval(starlegend)'"' _n
+ }
+ }
+
+*Finish: copy tempfile to user file / type to screen
+ file close `file'
+ local S: word count `macval(substitute)'
+ if `"`topfile'"'!="" {
+ confirm file `"`topfile'"'
+ }
+ if `"`bottomfile'"'!="" {
+ confirm file `"`bottomfile'"'
+ }
+ if `"`using'"'!="" {
+ tempname file2
+ file open `file2' `using', write text `replace' `append'
+ }
+ if "`type'"!="" di as res ""
+ if `"`topfile'"'!="" {
+ file open `file' using `"`topfile'"', read text
+ file read `file' temp
+ while r(eof)==0 {
+ if `"`using'"'!="" {
+ file write `file2' `"`macval(temp)'"' _n
+ }
+ if "`type'"!="" {
+ if "`showtabs'"!="" {
+ local temp: subinstr local temp "`=char(9)'" "", all
+ }
+ di `asis' `"`macval(temp)'"'
+ }
+ file read `file' temp
+ }
+ file close `file'
+ }
+ file open `file' using `"`tfile'"', read text
+ file read `file' temp
+ while r(eof)==0 {
+ forv s = 1(2)`S' {
+ local from: word `s' of `macval(substitute)'
+ local to: word `=`s'+1' of `macval(substitute)'
+ if `"`macval(from)'`macval(to)'"'!="" {
+ local temp: subinstr local temp `"`macval(from)'"' `"`macval(to)'"', all
+ }
+ }
+ if `"`using'"'!="" {
+ file write `file2' `"`macval(temp)'"' _n
+ }
+ if "`type'"!="" {
+ if "`showtabs'"!="" {
+ local temp: subinstr local temp "`=char(9)'" "", all
+ }
+ di `asis' `"`macval(temp)'"'
+ }
+ file read `file' temp
+ }
+ file close `file'
+ if `"`bottomfile'"'!="" {
+ file open `file' using `"`bottomfile'"', read text
+ file read `file' temp
+ while r(eof)==0 {
+ if `"`using'"'!="" {
+ file write `file2' `"`macval(temp)'"' _n
+ }
+ if "`type'"!="" {
+ if "`showtabs'"!="" {
+ local temp: subinstr local temp "`=char(9)'" "", all
+ }
+ di `asis' `"`macval(temp)'"'
+ }
+ file read `file' temp
+ }
+ file close `file'
+ }
+ if `"`using'"'!="" {
+ file close `file2'
+ gettoken junk using0 : using
+ return local fn `using0'
+ if "`outfilenoteoff'"=="" {
+ di as txt `"(output written to {browse `using0'})"'
+ }
+ }
+end
+
+program MoreOptions
+// estout has more options than -syntax- can handle; a subroutine is used
+// here (rather than a second syntax call) to preserve the 'using' macro
+// from the first syntax call
+// MoreOptions is intended for options without arguments only
+ local theoptions ///
+ NOReplace Replace ///
+ NOAppend Append ///
+ NOTYpe TYpe ///
+ NOSHOWTABS showtabs ///
+ NOASIS asis ///
+ NOWRAP wrap ///
+ NOSMCLTags SMCLTags ///
+ NOSMCLRules SMCLRules ///
+ NOSMCLMIDRules SMCLMIDRules ///
+ NOSMCLEQRules SMCLEQRules ///
+ NOOUTFILENOTEOFF outfilenoteoff
+ syntax [, `theoptions' ]
+ foreach opt of local theoptions {
+ local opt = lower("`opt'")
+ c_local `opt' "``opt''"
+ }
+ c_local options
+end
+
+program ParseValueSubopts
+ syntax anything [ , mrow(string asis) NOTranspose Transpose ///
+ NOStar Star PVALue(string) Fmt(string) Label(string) Vacant(string) ///
+ NOPAR par PAR2(string asis) Keep(string asis) Drop(string asis) ///
+ PATtern(string) NOABS abs ]
+ local el: word 1 of `anything'
+ local elname: word 2 of `anything'
+ CheckPattern `"`pattern'"' "`elname'"
+ if `"`macval(par2)'"'!="" {
+ local par `"`macval(par2)'"'
+ }
+ else if "`par'"!="" {
+ if "`elname'"=="ci" local par "[ , ]"
+ else if "`elname'"=="ci_l" local par `"[ """'
+ else if "`elname'"=="ci_u" local par `""" ]"'
+ else local par "( )"
+ }
+ if `"`mrow'"'!="" {
+ capt confirm integer number `mrow'
+ if _rc==0 {
+ if `mrow'>=1 {
+ if `"`macval(label)'"'=="" {
+ local label "`elname'[`mrow']"
+ }
+ }
+ else {
+ local mrow `""`mrow'""'
+ if `"`macval(label)'"'=="" {
+ local label `mrow'
+ }
+ }
+ }
+ else {
+ gettoken trash : mrow, qed(qed)
+ if `qed'==0 {
+ local mrow `"`"`mrow'"'"'
+ }
+ if `"`macval(label)'"'=="" {
+ local label `mrow'
+ }
+ }
+ }
+ foreach opt in transpose star par abs {
+ if "`no`opt''"!="" c_local no`el'_`opt' 1
+ else c_local `el'_`opt' "``opt''"
+ }
+ foreach opt in mrow pvalue fmt label vacant keep drop pattern {
+ c_local `el'_`opt' `"`macval(`opt')'"'
+ }
+end
+
+program CheckPattern
+ args pattern option
+ foreach p of local pattern {
+ if !( "`p'"=="1" | "`p'"=="0" ) {
+ di as error `""`pattern'" invalid in `option'(... pattern())"'
+ exit 198
+ }
+ }
+end
+
+program ParseStatsSubopts
+ syntax [anything] [ , Fmt(string) Labels(string asis) ///
+ NOStar Star Star2(string) LAYout(string asis) PChar(string) ]
+ foreach opt in fmt labels layout pchar {
+ c_local stats`opt' `"`macval(`opt')'"'
+ }
+ if "`nostar'"!="" c_local nostatsstar 1
+ else if "`star2'"!="" {
+ local anything: list anything | star2
+ c_local statsstar "`star2'"
+ }
+ else if "`star'"!="" {
+ local star2: word 1 of `anything'
+ c_local statsstar "`star2'"
+ }
+ c_local stats "`anything'"
+ c_local stats2
+end
+
+prog ProcessStatslayout // returns statsarray, -rowlbls, -rowfmt, -rowstar, -colstar, -layout
+ args stats statsfmt statsstar statslayout statspchar
+ local format "%9.0g"
+ if `"`statspchar'"'=="" {
+ local statspchar "@"
+ c_local statspchar "@"
+ }
+ local statsarray
+ local statsrowlbls
+ local statsrowfmt
+ local statsrowstar
+ local space1
+ local i 0
+ local wmax 0
+ foreach row of local statslayout {
+ local statsrow
+ local statsrowlbl
+ local statsrfmt
+ local statsrstar
+ local space2
+ local w = 0
+ foreach cell of local row {
+ local ++w
+ local statscell
+ local statsclbl `"`cell'"'
+ local statscfmt
+ local statscstar 0
+ local space3
+ local trash: subinstr local cell `"`statspchar'"' "", all count(local cnt)
+ forv j=1/`cnt' {
+ local stat: word `++i' of `stats'
+ local statscell `"`statscell'`space3'`stat'"'
+ local statsclbl: subinstr local statsclbl `"`statspchar'"' "`stat'"
+ local tmp: word `i' of `statsfmt'
+ if `"`tmp'"'!="" local format `"`tmp'"'
+ local statscfmt `"`statscfmt'`space3'`format'"'
+ if `:list stat in statsstar' {
+ local statscstar 1
+ local statscol_`w' 1
+ }
+ local space3 " "
+ }
+ local statsrow `"`statsrow'`space2'"`statscell'""'
+ local statsrowlbl `"`statsrowlbl'`space2'`statsclbl'"'
+ local statsrfmt `"`statsrfmt'`space2'"`statscfmt'""'
+ local statsrstar "`statsrstar'`space2'`statscstar'"
+ local space2 " "
+ }
+ local statsarray `"`statsarray'`space1'`"`statsrow'"'"'
+ local statsrowlbls `"`statsrowlbls'`space1'`"`statsrowlbl'"'"'
+ local statsrowfmt `"`statsrowfmt'`space1'`"`statsrfmt'"'"'
+ local statsrowstar `"`statsrowstar'`space1'`"`statsrstar'"'"'
+ local space1 " "
+ local wmax = max(`w',`wmax')
+ }
+ while (1) {
+ local stat: word `++i' of `stats'
+ if `"`stat'"'=="" continue, break
+ local tmp: word `i' of `statsfmt'
+ if `"`tmp'"'!="" local format `"`tmp'"'
+ local statscstar: list stat in statsstar
+ if `statscstar' local statscol_1 1
+ local statsarray `"`statsarray'`space1'`"`stat'"'"'
+ local statsrowlbls `"`statsrowlbls'`space1'`"`stat'"'"'
+ local statsrowfmt `"`statsrowfmt'`space1'`"`format'"'"'
+ local statsrowstar `"`statsrowstar'`space1'`"`statscstar'"'"'
+ local statslayout `"`statslayout'`space1'`statspchar'"'
+ local space1 " "
+ local wmax = max(1,`wmax')
+ }
+ local statscolstar
+ local space
+ forv w = 1/`wmax' {
+ if "`statscol_`w''"=="" local statscol_`w' 0
+ local statscolstar "`statscolstar'`space'`statscol_`w''"
+ local space " "
+ }
+ c_local statsarray `"`statsarray'"'
+ c_local statsrowlbls `"`statsrowlbls'"'
+ c_local statsrowfmt `"`statsrowfmt'"'
+ c_local statsrowstar `"`statsrowstar'"'
+ c_local statscolstar `"`statscolstar'"'
+ c_local statslayout `"`statslayout'"'
+end
+
+program ParseLabelsSubopts
+ gettoken type 0: 0
+ local lblsubopts
+ syntax [anything] [ , NONUMbers NUMbers NOTItles TItles NODEPvars DEPvars ///
+ NONONE NONE NOSPAN span Prefix(string) Suffix(string) Begin(string asis) ///
+ End(string asis) NOReplace Replace BList(string asis) EList(string asis) ///
+ ERepeat(string) NOFirst First NOLast Last lhs(string) PATtern(string) ///
+ NOMerge Merge ]
+ CheckPattern `"`pattern'"' "`type'"
+ if "`merge'"!="" & "`nomerge'`macval(suffix)'"=="" local suffix ":"
+ foreach opt in begin end {
+ if `"`macval(`opt')'"'!="" {
+ if index(`"`macval(`opt')'"', `"""')==0 {
+ local `opt' `"`"`macval(`opt')'"'"'
+ }
+ }
+ }
+ foreach opt in prefix suffix begin end blist elist erepeat lhs pattern {
+ c_local `type'`opt' `"`macval(`opt')'"'
+ }
+ foreach opt in numbers titles depvars span replace none first last merge {
+ if "`no`opt''"!="" c_local no`type'`opt' 1
+ else c_local `type'`opt' "``opt''"
+ }
+ c_local `type' `"`macval(anything)'"'
+end
+
+program ReadLine
+ args max file
+ local end 0
+ file read `file' temp1
+ local temp1: subinstr local temp1 "`=char(9)'" " ", all
+ while r(eof)==0 {
+ local j 1
+ local temp2
+ local temp3: piece `j++' `max' of `"`macval(temp1)'"'
+ if `"`temp3'"'=="" | index(`"`temp3'"',"*")==1 ///
+ | index(`"`temp3'"',"//")==1 {
+ file read `file' temp1
+ local temp1: subinstr local temp1 "`=char(9)'" " ", all
+ continue
+ }
+ while `"`temp3'"'!="" {
+ local comment=index(`"`macval(temp3)'"'," ///")
+ if `comment' {
+ local temp3=substr(`"`macval(temp3)'"',1,`comment')
+ local temp2 `"`macval(temp2)'`macval(temp3)'"'
+ local end 0
+ continue, break
+ }
+ local comment=index(`"`macval(temp3)'"'," //")
+ if `comment' {
+ local temp3=substr(`"`macval(temp3)'"',1,`comment')
+ local temp2 `"`macval(temp2)'`macval(temp3)'"'
+ local end 1
+ continue, break
+ }
+ local temp2 `"`macval(temp2)'`macval(temp3)'"'
+ local temp3: piece `j++' `max' of `"`macval(temp1)'"'
+ local end 1
+ }
+ if `end' {
+ local line `"`macval(line)'`macval(temp2)'"'
+ continue, break
+ }
+ else {
+ local line `"`macval(line)'`macval(temp2)'"'
+ file read `file' temp1
+ local temp1: subinstr local temp1 "`=char(9)'" " ", all
+ }
+ }
+ c_local line `"`macval(line)'"'
+end
+
+program CellsCheck
+ args cells
+ local ncols 0
+ local nrows 0
+ local cells: subinstr local cells "& " "&", all
+ local cells: subinstr local cells " &" "&", all
+ local cells: subinstr local cells `"&""' `"& ""', all
+ local cells: subinstr local cells `""&"' `"" &"', all
+ foreach row of local cells {
+ local newrow
+ foreach col of local row {
+ local vals: subinstr local col "&" " ", all
+ //local vals: list vals - values
+ local values: list values | vals
+ local vals: list retok vals
+ local vals: subinstr local vals " " "&", all
+ //local newrow: list newrow | vals
+ local newrow `"`newrow'`vals' "'
+ }
+ local newrow: list retok newrow
+ if "`newrow'"!="" {
+ local ncols = max(`ncols',`:list sizeof newrow')
+ local newcells `"`newcells'"`newrow'" "'
+ local ++nrows
+ }
+ }
+ local newcells: list retok newcells
+ c_local cells `"`newcells'"'
+ c_local ncols `ncols'
+ c_local nrows `nrows'
+ local dot "."
+ c_local values: list values - dot
+end
+
+program Star2Cells
+ args cells star
+ local newcells
+ foreach row of local cells {
+ local newrow
+ foreach col of local row {
+ if "`col'"=="`star'" {
+ local col "`col'star"
+ }
+ local newrow: list newrow | col
+ }
+ local newcells `"`newcells'"`newrow'" "'
+ }
+ local newcells: list retok newcells
+ c_local cells `"`newcells'"'
+end
+
+prog ParseStarlevels
+ syntax [anything(equalok)] [ , Label(str) Delimiter(str) ]
+ c_local starlevels `"`macval(anything)'"'
+ c_local starlevelslabel `"`macval(label)'"'
+ c_local starlevelsdelimiter `"`macval(delimiter)'"'
+end
+
+program CheckStarvals
+ args starlevels label del
+ if `"`macval(label)'"'=="" local label " p<"
+ if `"`macval(del)'"'=="" local del ", "
+ local nstar: word count `macval(starlevels)'
+ local nstar = `nstar'/2
+ capture confirm integer number `nstar'
+ if _rc {
+ di as error "unmatched list of significance symbols and levels"
+ exit 198
+ }
+ local istar 1
+ forv i = 1/`nstar' {
+ local iistar: word `=`i'*2' of `macval(starlevels)'
+ confirm number `iistar'
+ if `iistar'>`istar' | `iistar'<=0 {
+ di as error "significance levels out of order or out of range (0,1]"
+ exit 198
+ }
+ local istar `iistar'
+ local isym: word `=`i'*2-1' of `macval(starlevels)'
+ if `"`macval(legend)'"'!="" {
+ local legend `"`macval(legend)'`macval(del)'"'
+ }
+ local ilabel: subinstr local label "@" "`istar'", count(local hasat)
+ if `hasat'==0 {
+ local ilabel `"`macval(label)'`istar'"'
+ }
+ local legend `"`macval(legend)'`macval(isym)'`macval(ilabel)'"'
+ }
+ c_local starlegend `"`macval(legend)'"'
+end
+
+program Starwidth
+ args starlevels
+ local nstar: word count `macval(starlevels)'
+ forv i = 2(2)`nstar' {
+ local istar: word `=`i'-1' of `macval(starlevels)'
+ local width = max(length("`width'"),length(`"`macval(istar)'"'))
+ }
+ c_local value `width'
+end
+
+// Loosely based on Mkemat from est_table.ado, but with heavy modifications
+program _estout_getres, rclass
+ syntax, names(str) [ coefs(str asis) stats(str asis) equations(str) ///
+ rename(str asis) margin(str asis) meqs(str asis) ///
+ dropped(int 0) level(int 95) ///
+ transform(str asis) transformpattern(str asis) ]
+ // coefs: coef "coef O/1 #" `"coef O/1 "rowname""' etc...
+
+ tempname bc bbc bs bbs st
+
+ local nnames : word count `names'
+ local rename : subinstr local rename "," "", all
+ if `"`stats'"' != "" {
+ local stats : subinstr local stats "," "", all
+ confirm names `stats'
+ local stats : list uniq stats
+ local nstat : list sizeof stats
+ mat `bbs' = J(`nstat', `nnames', .z)
+ mat colnames `bbs' = `: subinstr local names "." "active", all word'
+ mat rownames `bbs' = `stats'
+ }
+
+ if "`equations'" != "" {
+ MatchNames "`equations'"
+ local eqspec `r(eqspec)'
+ local eqnames `r(eqnames)'
+ }
+
+ local ncoefs 0
+ foreach coefn of local coefs {
+ local ++ncoefs
+ gettoken coef : coefn
+ local coefnms `"`coefnms' `coef'"' // use more informative label? (coefn => error in Stata 8 and 10)
+ }
+ local bVs "b se var t z p ci_l ci_u _star _sign _sigsign"
+ local hasbVs = `"`: list coefnms & bVs'"'!=""
+ local hastransform = (`"`transform'"'!="") & `hasbVs'
+ local getbV = cond(`hasbVs' | `dropped', "b var ", "")
+
+ tempname hcurrent esample
+ local estcycle = ("`names'"!=".")
+ if `estcycle' {
+ _est hold `hcurrent', restore nullok estsystem
+ }
+
+ local ni 0
+ local hasbbc 0
+ local ccols = `ncoefs' + ("`margin'"!="") + `dropped'
+ foreach name of local names {
+ local ++ni
+ local hasbc 0
+ local hasmargin 0
+ nobreak {
+ if "`name'" != "." {
+ local eqname `name'
+ *est_unhold `name' `esample' // (why preserve missings in esample?)
+ capt confirm new var _est_`name' // fix e(sample) if obs have been added
+ if _rc qui replace _est_`name' = 0 if _est_`name' >=.
+ _est unhold `name'
+ }
+ else {
+ local eqname active
+ if `estcycle' {
+ _est unhold `hcurrent'
+ }
+ }
+
+ // get coefficients
+ capture noisily break {
+ CheckEqs `"`getbV'`coefs'"' // sets local seqmerge
+ GetCoefs `bc' `seqmerge' `"`getbV'`coefs'"' // sets local hasbc
+ if `hasbc' {
+ mat coln `bc' = `getbV'`coefnms'
+ }
+ }
+ local rc = _rc
+
+ // set equation names and get marginal effects
+ if `hasbc' & `rc'==0 {
+ capture noisily break {
+ if `dropped' {
+ DroppedCoefs `bc'
+ }
+ if "`equations'"!="" {
+ AdjustRowEq `bc' `ni' `nnames' "`eqspec'" "`eqnames'"
+ }
+ if "`margin'"!="" & `hasbVs' {
+ GetMarginals `bc' "`margin'" `"`meqs'"' // resets local hasmargin
+ }
+ if `hasbVs' {
+ ComputeCoefs `bc' `hasmargin' `"`coefnms'"' `level'
+ }
+ if `hastransform' & `hasbVs' {
+ if `"`transformpattern'"'!="" {
+ local transformthis: word `ni' of `transformpattern'
+ }
+ else local transformthis 1
+ if `"`transformthis'"'=="1" {
+ TransformCoefs `bc' `"`coefnms'"' `"`transform'"'
+ }
+ }
+ if "`getbV'"!="" {
+ mat `bc' = `bc'[1...,3...] // remove b and var
+ }
+ }
+ local rc = _rc
+ }
+
+ // get stats
+ if `rc'==0 {
+ capture noisily break {
+ if "`stats'" != "" {
+ GetStats "`stats'" `bbs' `ni'
+ if `hasbc'>0 & inlist(`"`e(cmd)'"', "reg3", "sureg", "mvreg") {
+ GetEQStats "`stats'" `bbs' `ni' `bc'
+ }
+ return add
+ }
+ }
+ local rc = _rc
+ }
+
+ local depname: word 1 of `e(depvar)'
+ return local m`ni'_depname "`depname'"
+
+ local title `"`e(estimates_title)'"'
+ if `"`title'"'=="" local title `"`e(_estimates_title)'"' // prior to Stata 10
+ return local m`ni'_estimates_title `"`title'"'
+
+ if "`name'" != "." {
+ *est_hold `name' `esample'
+ _est hold `name', estimates varname(_est_`name')
+ }
+ else {
+ if `estcycle' {
+ _est hold `hcurrent', restore nullok estsystem
+ }
+ }
+ }
+
+ if `rc' {
+ exit `rc'
+ }
+
+ if `hasbc'>0 {
+ mat coleq `bc' = `eqname'
+ if `"`rename'"'!="" {
+ RenameCoefs `bc' `"`rename'"'
+ }
+ if `hasbbc' {
+ mat_capp `bbc' : `bbc' `bc', miss(.z) cons ts
+ }
+ else {
+ mat `bbc' = `bc'
+ if `ni'>1 { // add previous empty models
+ mat `bc' = (1, `bc'[1,1...]) \ ( `bc'[1...,1], J(rowsof(`bc'), colsof(`bc'), .z))
+ mat `bc' = `bc'[2...,2...]
+ forv nj = 1/`ni' {
+ if `nj'==`ni' continue
+ local eqname: word `nj' of `names'
+ if `"`eqname'"'=="." {
+ local eqname active
+ }
+ mat coleq `bc' = `eqname'
+ mat `bbc' = `bc', `bbc'
+ }
+ }
+ }
+ local hasbbc 1
+ }
+ else {
+ if `hasbbc' { // add empty model if bbc exists
+ mat `bc' = `bbc'[1...,1..`ccols']
+ mat `bc' = (1, `bc'[1,1...]) \ ( `bc'[1...,1], J(rowsof(`bc'), colsof(`bc'), .z))
+ mat `bc' = `bc'[2...,2...]
+ mat coleq `bc' = `eqname'
+ mat `bbc' = `bbc', `bc'
+ }
+ }
+ }
+
+ if `hasbbc' {
+ return matrix coefs = `bbc'
+ return scalar ccols = `ccols'
+ }
+ else {
+ return scalar ccols = 0 // indicates that r(coefs) is missing
+ }
+ if "`stats'" != "" {
+ return matrix stats = `bbs'
+ }
+ return local names `names'
+ return scalar nmodels = `ni'
+end
+
+program DroppedCoefs // identify dropped coeffficients
+ args bc
+ tempname tmp
+ mat `tmp' = `bc'[1..., 1] * 0
+ mat coln `tmp' = "_dropped"
+ local r = rowsof(`bc')
+ forv i = 1/`r' {
+ if `bc'[`i',1]==0 & `bc'[`i',2]==0 { // b=0 and var=0
+ mat `tmp'[`i',1] = 1
+ }
+ }
+ mat `bc' = `bc', `tmp'
+end
+
+program RenameCoefs
+ args bc rename
+ local Stata11 = cond(c(stata_version)>=11, "version 11:", "")
+ tempname tmp
+ local eqs: roweq `bc', q
+ local eqs: list clean eqs
+ local eqs: list uniq eqs
+ local newnames
+ foreach eq of local eqs {
+ mat `tmp' = `bc'[`"`eq':"',1]
+ QuotedRowNames `tmp'
+ local vars `"`value'"'
+ gettoken from rest : rename
+ gettoken to rest : rest
+ while (`"`from'`to'"'!="") {
+ if index(`"`to'"',":") | `"`to'"'=="" {
+ di as err "invalid rename()"
+ exit 198
+ }
+ local hasfrom = rownumb(`tmp', `"`from'"')
+ if `hasfrom'<. {
+ local hasto = rownumb(`tmp', `"`to'"')
+ if `hasto'<. {
+ di as err `"`to' already exists in equation; cannot rename"'
+ exit 110
+ }
+ local colonpos = index(`"`from'"',":")
+ if index(`"`from'"',":") { // remove equation
+ gettoken chunk from : from, parse(":") // eq
+ gettoken chunk from : from, parse(":") // :
+ gettoken from : from
+ if `"`from'"'=="" {
+ di as err "invalid rename()"
+ exit 190
+ }
+ }
+ local vars: subinstr local vars `"`from'"' `"`"`to'"'"', word
+ `Stata11' mat rown `tmp' = `vars'
+ }
+ gettoken from rest : rest
+ gettoken to rest : rest
+ }
+ local newnames `"`newnames'`vars' "'
+ }
+ `Stata11' mat rown `bc' = `newnames'
+end
+
+// Source: est_table.ado version 1.1.4 09oct2008 (unmodified)
+program MatchNames, rclass
+ args eqspec
+
+ local eqspec : subinstr local eqspec ":" " ", all
+ local eqspec0 : subinstr local eqspec "#" "" , all
+
+ local iterm 0
+ gettoken term eqspec : eqspec0 , parse(",")
+ while "`term'" != "" {
+ local ++iterm
+
+ // term = [name =] { # | #-list }
+ gettoken eqname oprest: term, parse("=")
+ gettoken op rest : oprest, parse("=")
+ if trim(`"`op'"') == "=" {
+ confirm name `eqname'
+ local term `rest'
+ }
+ else {
+ local eqname #`iterm'
+ }
+ local eqnames `eqnames' `eqname'
+
+ if "`eqspec'" == "" {
+ continue, break
+ }
+ gettoken term eqspec: eqspec , parse(",")
+ assert "`term'" == ","
+ gettoken term eqspec: eqspec , parse(",")
+ }
+
+ if `"`:list dups eqnames'"' != "" {
+ dis as err "duplicate matched equation names"
+ exit 198
+ }
+
+ return local eqspec `eqspec0'
+ return local eqnames `eqnames'
+end
+
+// Source: est_table.ado version 1.1.4 09oct2008 (unmodified)
+program AdjustRowEq
+ args b ni nmodel eqspec eqnames
+
+ local beqn : roweq `b', quote
+ local beqn : list clean beqn
+ local beq : list uniq beqn
+
+ if `"`:list beq & eqnames'"' != "" {
+ dis as err "option equations() invalid"
+ dis as err "specified equation name already occurs in model `ni'"
+ exit 198
+ }
+
+ local iterm 0
+ gettoken term eqspec : eqspec , parse(",")
+ while "`term'" != "" {
+ // dis as txt "term:|`term'|"
+ local ++iterm
+
+ // term = [name =] { # | #-list }
+ gettoken eqname oprest: term, parse("=")
+ gettoken op rest : oprest, parse("=")
+ if trim(`"`op'"') == "=" {
+ local term `rest'
+ }
+ else {
+ local eqname #`iterm'
+ }
+
+ local nword : list sizeof term
+ if !inlist(`nword', 1, `nmodel') {
+ dis as err "option equations() invalid"
+ dis as err "a term should consist of either 1 or `nmodel' equation numbers"
+ exit 198
+ }
+ if `nword' > 1 {
+ local term : word `ni' of `term'
+ }
+
+ if trim("`term'") != "." {
+ capt confirm integer number `term'
+ if _rc {
+ dis as err "option equations() invalid"
+ dis as err "`term' was found, while an integer equation number was expected"
+ exit 198
+ }
+ if !inrange(`term',1,`:list sizeof beq') {
+ dis as err "option equations() invalid"
+ dis as err "equation number `term' for model `ni' out of range"
+ exit 198
+ }
+ if `:list posof "`eqname'" in beq' != 0 {
+ dis as err "impossible to name equation `eqname'"
+ dis as err "you should provide (another) equation name"
+ exit 198
+ }
+
+ local beqn : subinstr local beqn ///
+ `"`:word `term' of `beq''"' ///
+ "`eqname'" , word all
+ }
+
+ if "`eqspec'" == "" {
+ continue, break
+ }
+ gettoken term eqspec: eqspec , parse(",")
+ assert "`term'" == ","
+ gettoken term eqspec: eqspec , parse(",")
+ }
+ matrix roweq `b' = `beqn'
+end
+
+// Source: est_table.ado version 1.1.4 09oct2008 (modified)
+// Modification: returns string scalars in r(m`ni'_name) (and sets `bbs' = .y)
+program GetStats, rclass
+ args stats bbs ni
+ tempname rank st V
+ local escalars : e(scalars)
+ local emacros : e(macros)
+ local is 0
+ foreach stat of local stats {
+ local ++is
+ if inlist("`stat'", "aic", "bic", "rank") {
+ if "`hasrank'" == "" {
+ capt mat `V' = syminv(e(V))
+ local rc = _rc
+ if `rc' == 0 {
+ scalar `rank' = colsof(`V') - diag0cnt(`V')
+ }
+ else if `rc' == 111 {
+ scalar `rank' = 0
+ }
+ else {
+ // rc<>0; show error message
+ mat `V' = syminv(e(V))
+ }
+ local hasrank 1
+ }
+ if "`stat'" == "aic" {
+ scalar `st' = -2*e(ll) + 2*`rank'
+ }
+ else if "`stat'" == "bic" {
+ scalar `st' = -2*e(ll) + log(e(N)) * `rank'
+ }
+ else if "`stat'" == "rank" {
+ scalar `st' = `rank'
+ }
+ }
+ else {
+ if `:list stat in escalars' > 0 {
+ scalar `st' = e(`stat')
+ }
+ else if "`stat'"=="p" {
+ if e(F)<. {
+ scalar `st' = Ftail(e(df_m), e(df_r), e(F))
+ }
+ else if e(chi2)<. {
+ scalar `st' = chi2tail(e(df_m), e(chi2))
+ }
+ }
+ else if `:list stat in emacros' > 0 {
+ scalar `st' = .y
+ capt return local m`ni'_`stat' `"`e(`stat')'"' // name might be too long
+ }
+ else {
+ scalar `st' = .z
+ }
+ }
+ mat `bbs'[`is',`ni'] = `st'
+ }
+end
+
+program GetEQStats, rclass // eq-specific stats for reg3, sureg, and mvreg (sets `bbs' = .x)
+ args stats bbs ni bc
+ return add
+ tempname addrow
+ local ic "aic bic rank"
+ local eqs: roweq `bc', q
+ local eqs: list clean eqs
+ local eqs: list uniq eqs
+ local s 0
+ foreach stat of local stats {
+ local ++s
+ if inlist(`"`stat'"', "aic", "bic", "rank") continue
+ if `bbs'[`s',`ni']<.y continue
+ local e 0
+ local found 0
+ foreach eq of local eqs {
+ local ++e
+ if e(cmd)=="mvreg" {
+ if "`stat'"=="p" local value: word `e' of `e(p_F)'
+ else local value: word `e' of `e(`stat')'
+ }
+ else if "`stat'"=="df_m" {
+ local value `"`e(`stat'`e')'"'
+ }
+ else {
+ local value `"`e(`stat'_`e')'"'
+ }
+ capture confirm number `value'
+ if _rc==0 {
+ local found 1
+ local r = rownumb(`bbs', `"`eq':`stat'"')
+ if `r'>=. {
+ mat `addrow' = J(1, colsof(`bbs'), .z)
+ mat rown `addrow' = `"`eq':`stat'"'
+ mat `bbs' = `bbs' \ `addrow'
+ local r = rownumb(`bbs', `"`eq':`stat'"')
+ }
+ mat `bbs'[`r',`ni'] = `value'
+ }
+ }
+ if `found' {
+ if `bbs'[`s',`ni']==.y {
+ capt return local m`ni'_`stat' ""
+ }
+ mat `bbs'[`s',`ni'] = .x
+ }
+ }
+end
+
+program CheckEqs
+ args coefs
+ tempname tmp
+ local j 0
+ local bVs "b _star _sign _sigsign"
+ local seqmerge 0
+ local hasseqs 0
+ foreach coefn in `coefs' {
+ local ++j
+ gettoken coef row : coefn
+ gettoken transpose row : row
+ gettoken row : row, q
+ if `"`coef'"'=="b" & `j'==1 {
+ capt confirm mat e(`coef')
+ if _rc continue
+ mat `tmp' = e(`coef')
+ local eqs: coleq `tmp', q
+ if `:list posof "_" in eqs'==0 {
+ local seqmerge 1
+ }
+ else continue, break
+ }
+ if `:list coef in bVs' continue
+ capt confirm mat e(`coef')
+ if _rc continue
+ mat `tmp' = e(`coef')
+ if `transpose' {
+ mat `tmp' = `tmp''
+ }
+ if `"`row'"'=="" local row 1
+ capt confirm number `row'
+ if _rc {
+ local row = rownumb(`tmp',`row')
+ }
+ if `row'>rowsof(`tmp') continue
+ local eqs: coleq `tmp', q
+ if `:list posof "_" in eqs' {
+ local eqs: list uniq eqs
+ local eqs: list clean eqs
+ if `"`eqs'"'!="_" { // => contains "_" but also others
+ local local seqmerge 0
+ continue, break
+ }
+ else local hasseqs 1
+ }
+ else {
+ local seqmerge 1
+ }
+ }
+ if `hasseqs'==0 local seqmerge 0
+ c_local seqmerge `seqmerge'
+end
+
+program GetCoefs
+ args bc seqmerge coefs
+ tempname tmp
+ local hasbc 0
+ local j 0
+ local bVs "b _star _sign _sigsign"
+ foreach coefn of local coefs {
+ local ++j
+ gettoken coef row : coefn
+ gettoken transpose row : row
+ gettoken row : row, q
+ local isinbVs: list coef in bVs
+ if `isinbVs' & `j'>2 {
+ if `hasbc'==0 continue
+ mat `bc' = `bc', J(rowsof(`bc'),1, .y)
+ continue
+ }
+ if `j'==2 & `"`coef'"'=="var" {
+ local isinbVs 1
+ capt mat `tmp' = vecdiag(e(V))
+ if _rc {
+ capt confirm mat e(se)
+ if _rc==0 {
+ mat `tmp' = e(se)
+ forv i = 1/`=colsof(`tmp')' {
+ mat `tmp'[1, `i'] = `tmp'[1, `i']^2
+ }
+ }
+ }
+ }
+ else {
+ capt confirm mat e(`coef')
+ if _rc==0 {
+ mat `tmp' = e(`coef')
+ }
+ }
+ if _rc {
+ if `hasbc'==0 continue
+ mat `bc' = `bc', J(rowsof(`bc'),1, .y)
+ continue
+ }
+ if `isinbVs'==0 { // => not b or var
+ if `transpose' {
+ mat `tmp' = `tmp''
+ }
+ if `"`row'"'=="" local row 1
+ capt confirm number `row'
+ if _rc {
+ local row = rownumb(`tmp',`row')
+ }
+ if `row'>rowsof(`tmp') {
+ if `hasbc'==0 continue
+ mat `bc' = `bc', J(rowsof(`bc'),1, .y)
+ continue
+ }
+ mat `tmp' = `tmp'[`row', 1...]
+ }
+ local bcols = colsof(`tmp')
+ if `bcols'==0 {
+ if `hasbc'==0 continue
+ mat `bc' = `bc', J(rowsof(`bc'),1, .y)
+ continue
+ }
+ mat `tmp' = `tmp''
+ if `seqmerge' & `isinbVs'==0 {
+ local eqs: roweq `tmp', q
+ local eqs: list uniq eqs
+ local eqs: list clean eqs
+ if `"`eqs'"'=="_" {
+ local seqmergejs `seqmergejs' `j'
+ local seqmergecoefs `"`seqmergecoefs'`"`coefn'"' "'
+ if `hasbc'==0 continue
+ mat `bc' = `bc', J(rowsof(`bc'),1, .y)
+ continue
+ }
+ }
+ if `hasbc'==0 {
+ mat `bc' = `tmp'
+ local hasbc 1
+ if `j'>1 {
+ mat `bc' = `bc', J(`bcols',`j'-1, .y), `bc'
+ mat `bc' = `bc'[1...,2...]
+ }
+ }
+ else {
+ mat_capp `bc' : `bc' `tmp', miss(.y) cons ts
+ }
+ }
+ foreach coefn of local seqmergecoefs {
+ gettoken j seqmergejs : seqmergejs
+ gettoken coef row : coefn
+ gettoken transpose row : row
+ gettoken row : row, q
+ mat `tmp' = e(`coef')
+ if `transpose' {
+ mat `tmp' = `tmp''
+ }
+ if `"`row'"'=="" local row 1
+ capt confirm number `row'
+ if _rc {
+ local row = rownumb(`tmp',`row')
+ }
+ mat `tmp' = `tmp'[`row', 1...]
+ SEQMerge `bc' `j' `tmp'
+ }
+ c_local hasbc `hasbc'
+end
+
+program SEQMerge
+ args bc j x
+ tempname tmp
+ local r = rowsof(`bc')
+ forv i = 1/`r' {
+ mat `tmp' = `bc'[`i',1...]
+ local v: rown `tmp'
+ local c = colnumb(`x', `"`v'"')
+ if `c'<. {
+ mat `bc'[`i',`j'] = `x'[1,`c']
+ }
+ }
+end
+
+program ComputeCoefs
+ args bc hasmargin coefs level
+ local bVs1 "b _star _sign _sigsign"
+ local bVs2 "se var t z p ci_l ci_u"
+ local c = colsof(`bc')
+ forv j = 3/`c' {
+ gettoken v coefs : coefs
+ if `"`v'"'=="" continue, break
+ if `: list v in bVs1' {
+ ComputeCoefs_`v' `bc' `j' `level'
+ continue
+ }
+ if `: list v in bVs2' {
+ if `hasmargin' {
+ ComputeCoefs_`v' `bc' `j' `level'
+ continue
+ }
+ capt confirm matrix e(`v')
+ if _rc {
+ ComputeCoefs_`v' `bc' `j' `level'
+ }
+ }
+ }
+end
+
+program CopyColFromTo
+ args m from to cname
+ tempname tmp
+ mat `tmp' = `m'[1...,`from']
+ mat coln `tmp' = `cname'
+ local c = colsof(`m')
+ if `to'==`c' {
+ mat `m' = `m'[1...,1..`c'-1], `tmp'
+ exit
+ }
+ mat `m' = `m'[1...,1..`to'-1], `tmp', `m'[1...,`to'+1..`c']
+end
+
+program ComputeCoefs_b
+ args bc j
+ CopyColFromTo `bc' 1 `j' "b"
+end
+
+program ComputeCoefs_se
+ args bc j
+ local r = rowsof(`bc')
+ forv i = 1/`r' {
+ local var `bc'[`i',2]
+ local res `bc'[`i',`j']
+ if `var'>=. mat `res' = `var'
+ else if `var'==0 mat `res' = .
+ else mat `res' = sqrt(`var')
+ }
+end
+
+program ComputeCoefs_var
+ args bc j
+ CopyColFromTo `bc' 2 `j' "var"
+end
+
+program ComputeCoefs_t
+ args bc j
+ local r = rowsof(`bc')
+ forv i = 1/`r' {
+ local b `bc'[`i',1]
+ local var `bc'[`i',2]
+ local res `bc'[`i',`j']
+ if `b'>=. mat `res' = `b'
+ else if `var'>=. mat `res' = `var'
+ else mat `res' = `b'/sqrt(`var')
+ }
+end
+
+program ComputeCoefs_z
+ ComputeCoefs_t `0'
+end
+
+program ComputeCoefs_p
+ args bc j
+ local r = rowsof(`bc')
+ local df_r = e(df_r)
+ forv i = 1/`r' {
+ local b `bc'[`i',1]
+ local var `bc'[`i',2]
+ local res `bc'[`i',`j']
+ if `b'>=. mat `res' = `b'
+ else if `var'>=. mat `res' = `var'
+ else if `df_r'<. mat `res' = ttail(`df_r',abs(`b'/sqrt(`var'))) * 2
+ else mat `res' = (1 - norm(abs(`b'/sqrt(`var')))) * 2
+ }
+end
+
+program ComputeCoefs_ci_l
+ args bc j
+ ComputeCoefs_ci - `0'
+end
+
+program ComputeCoefs_ci_u
+ args bc j
+ ComputeCoefs_ci + `0'
+end
+
+program ComputeCoefs_ci
+ args sign bc j level
+ local r = rowsof(`bc')
+ local df_r = e(df_r)
+ forv i = 1/`r' {
+ local b `bc'[`i',1]
+ local var `bc'[`i',2]
+ local res `bc'[`i',`j']
+ if `b'>=. mat `res' = `b'
+ else if `var'>=. mat `res' = `var'
+ else if `df_r'<. mat `res' = `b' `sign' ///
+ invttail(`df_r',(100-`level')/200) * sqrt(`var')
+ else mat `res' = `b' `sign' ///
+ invnorm(1-(100-`level')/200) * sqrt(`var')
+ }
+end
+
+program ComputeCoefs__star
+ args bc j
+ CopyColFromTo `bc' 1 `j' "_star"
+end
+
+program ComputeCoefs__sign
+ args bc j
+ CopyColFromTo `bc' 1 `j' "_sign"
+end
+
+program ComputeCoefs__sigsign
+ args bc j
+ CopyColFromTo `bc' 1 `j' "_sigsign"
+end
+
+program GetMarginals
+ args bc margin meqs
+ tempname D dfdx
+ mat `D' = `bc'[1...,1]*0
+ mat coln `D' = "_dummy"
+ local type `e(Xmfx_type)'
+ if "`type'"!="" {
+ mat `dfdx' = e(Xmfx_`type')
+ capture confirm matrix e(Xmfx_se_`type')
+ if _rc==0 {
+ mat `dfdx' = `dfdx' \ e(Xmfx_se_`type')
+ }
+ if "`e(Xmfx_discrete)'"=="discrete" local dummy `e(Xmfx_dummy)'
+ }
+ else if "`e(cmd)'"=="dprobit" {
+ mat `dfdx' = e(dfdx) \ e(se_dfdx)
+ local dummy `e(dummy)'
+ }
+ else if "`e(cmd)'"=="tobit" & inlist("`margin'","u","c","p") {
+ capture confirm matrix e(dfdx_`margin')
+ if _rc==0 {
+ mat `dfdx' = e(dfdx_`margin') \ e(se_`margin')
+ }
+ local dummy `e(dummy)'
+ }
+ else if "`e(cmd)'"=="truncreg" {
+ capture confirm matrix e(dfdx)
+ if _rc==0 {
+ tempname V se
+ mat `V' = e(V_dfdx)
+ forv k= 1/`=rowsof(`V')' {
+ mat `se' = nullmat(`se') , sqrt(`V'[`k',`k'])
+ }
+ mat `dfdx' = e(dfdx) \ `se'
+ }
+ }
+ capture confirm matrix `dfdx'
+ if _rc==0 {
+ QuotedRowNames `bc'
+ local rnames `"`value'"'
+ if `"`meqs'"'!="" local reqs: roweq `bc', q
+ local i 1
+ foreach row of loc rnames {
+ if `"`meqs'"'!="" {
+ local eq: word `i' of `reqs'
+ }
+ local col = colnumb(`dfdx',"`row'")
+ if `col'>=. | !`:list eq in meqs' {
+ mat `bc'[`i',1] = .y
+ mat `bc'[`i',2] = .y
+ }
+ else {
+ mat `bc'[`i',1] =`dfdx'[1,`col']
+ mat `bc'[`i',2] = (`dfdx'[2,`col'])^2
+ if "`:word `col' of `dummy''"=="1" mat `D'[`i',1] = 1
+ }
+ local ++i
+ }
+ c_local hasmargin 1
+ }
+ mat `bc' = `bc', `D'
+end
+
+program TransformCoefs
+ args bc coefs transform
+ local c = colsof(`bc')
+ forv j = 3/`c' {
+ gettoken v coefs : coefs
+ if inlist("`v'", "b", "ci_l", "ci_u") {
+ _TransformCoefs `bc' `j' 0 "" "" `"`transform'"'
+ }
+ else if "`v'"=="se" {
+ _TransformCoefs `bc' `j' 1 "abs" "" `"`transform'"'
+ }
+ else if "`v'"=="var" {
+ _TransformCoefs `bc' `j' 1 "" "^2" `"`transform'"'
+ }
+ }
+end
+
+program _TransformCoefs
+ args bc j usedf abs sq transform
+ local r = rowsof(`bc')
+ gettoken coef rest : transform
+ gettoken f rest : rest
+ gettoken df rest : rest
+ while `"`coef'`f'`df'"'!="" {
+ if `"`df'`rest'"'=="" { // last element of list may be without coef
+ local df `"`f'"'
+ local f `"`coef'"'
+ local coef ""
+ }
+ local trcoefs `"`trcoefs'`"`coef'"' "'
+ if `usedf' {
+ local trs `"`trs'`"`df'"' "'
+ }
+ else {
+ local trs `"`trs'`"`f'"' "'
+ }
+ gettoken coef rest : rest
+ gettoken f rest : rest
+ gettoken df rest : rest
+ }
+ local trs : subinstr local trs "@" "\`b'", all
+ forv i = 1/`r' {
+ gettoken coef coefrest : trcoefs
+ gettoken tr trrest : trs
+ while `"`coef'`tr'"'!="" {
+ MatchCoef `"`coef'"' `bc' `i'
+ if `match' {
+ if `usedf' {
+ local b `bc'[`i',1]
+ local res `bc'[`i',`j']
+ if `res'<. {
+ mat `res' = `res' * `abs'(`tr')`sq'
+ }
+ }
+ else {
+ local b `bc'[`i',`j']
+ if `b'<. {
+ mat `b' = (`tr')
+ }
+ }
+ continue, break
+ }
+ gettoken coef coefrest : coefrest
+ gettoken tr trrest : trrest
+ }
+ }
+end
+
+program MatchCoef
+ args eqx b i
+ if inlist(trim(`"`eqx'"'),"","*") {
+ c_local match 1
+ exit
+ }
+ tempname tmp
+ mat `tmp' = `b'[`i',1...]
+ local eqi: roweq `tmp'
+ local xi: rown `tmp'
+ gettoken eq x : eqx, parse(:)
+ local eq: list clean eq
+ if `"`eq'"'==":" { // case 1: ":[varname]"
+ local eq
+ }
+ else if `"`x'"'=="" { // case 2: "varname"
+ local x `"`eq'"'
+ local eq
+ }
+ else { // case 3. "eqname:[varname]"
+ gettoken colon x : x, parse(:)
+ local x: list clean x
+ }
+ if `"`eq'"'=="" local eq "*"
+ if `"`x'"'=="" local x "*"
+ c_local match = match(`"`eqi'"', `"`eq'"') & match(`"`xi'"', `"`x'"')
+end
+
+program NumberMlabels
+ args M mlabels
+ forv m = 1/`M' {
+ local num "(`m')"
+ local lab: word `m' of `macval(mlabels)'
+ if `"`macval(lab)'"'!="" {
+ local lab `"`num' `macval(lab)'"'
+ }
+ else local lab `num'
+ local labels `"`macval(labels)'`"`macval(lab)'"' "'
+ }
+ c_local mlabels `"`macval(labels)'"'
+end
+
+program ModelEqCheck
+ args B eq m ccols
+ tempname Bsub
+ mat `Bsub' = `B'["`eq':",(`m'-1)*`ccols'+1]
+ local R = rowsof(`Bsub')
+ local value 0
+ forv r = 1/`R' {
+ if `Bsub'[`r',1]<. {
+ local value 1
+ continue, break
+ }
+ }
+ c_local value `value'
+end
+
+program Add2Vblock
+ args block col
+ foreach v of local col {
+ gettoken row block: block
+ local row "`row' `v'"
+ local row: list retok row
+ local vblock `"`vblock'"`row'" "'
+ }
+ c_local vblock `"`vblock'"'
+end
+
+program CountNofEqs
+ args ms es
+ local m0 0
+ local e0 0
+ local i 0
+ local eqs 0
+ foreach m of local ms {
+ local ++i
+ local e: word `i' of `es'
+ if `m'!=`m0' | `e'!=`e0' {
+ local ++eqs
+ }
+ local m0 `m'
+ local e0 `e'
+ }
+ c_local value `eqs'
+end
+
+program InsertAtVariables
+ args value type span M E width hline rtf rtfrowdefbrdrt rtfrowdefbrdrb rtfrowdef rtfemptyrow ///
+ title note discrete starlegend
+ if `type'==1 local atvars span
+ else {
+ local atvars span M E width hline
+ if `rtf' local atvars `atvars' rtfrowdefbrdrt rtfrowdefbrdrb rtfrowdef rtfemptyrow
+ if `type'!=2 local atvars `atvars' title note discrete starlegend
+ }
+ foreach atvar of local atvars {
+ capt local value: subinstr local value "@`atvar'" `"`macval(`atvar')'"', all
+ // note: returns error if length of is more than 502 characters
+ }
+ c_local value `"`macval(value)'"'
+end
+
+program Abbrev
+ args width value abbrev
+ if "`abbrev'"!="" {
+ if `width'>32 {
+ local value = substr(`"`macval(value)'"',1,`width')
+ }
+ else if `width'>0 {
+ if length(`"`macval(value)'"')>`width' {
+ local value = abbrev(`"`macval(value)'"',`width')
+ }
+ }
+ }
+ c_local value `"`macval(value)'"'
+end
+
+program MgroupsPattern
+ args mrow pattern
+ local i 0
+ local m0 0
+ local j 0
+ foreach m of local mrow {
+ if `m'>=. {
+ local newpattern `newpattern' .
+ continue
+ }
+ if `m'!=`m0' {
+ local p: word `++i' of `pattern'
+ if `i'==1 local p 1
+ if "`p'"=="1" local j = `j' + 1
+ }
+ local newpattern `newpattern' `j'
+ local m0 `m'
+ }
+ c_local mgroupspattern `newpattern'
+end
+
+program WriteCaption
+ args file delimiter stardetach row rowtwo labels starsrow span ///
+ abbrev colwidth delwidth starwidth repeat prefix suffix
+ local c 0
+ local nspan 0
+ local c0 2
+ local spanwidth -`delwidth'
+ local spanfmt
+ local ncolwidth: list sizeof colwidth
+ foreach r of local row {
+ local rtwo: word `++c' of `rowtwo'
+ local colwidthj: word `=1+mod(`c'-1,`ncolwidth')' of `colwidth'
+ if `colwidthj'>0 local colfmt "%`colwidthj's"
+ else local colfmt
+ if "`r'"=="." {
+ local ++c0
+ file write `file' `macval(delimiter)' `colfmt' (`""')
+ }
+ else if `"`span'"'=="" {
+ if ( "`r'"!="`lastr'" | "`rtwo'"!="`lastrtwo'" | `"`rowtwo'"'=="" ) {
+ local value: word `r' of `macval(labels)'
+ Abbrev `colwidthj' `"`macval(value)'"' "`abbrev'"
+ local value `"`macval(prefix)'`macval(value)'`macval(suffix)'"'
+ InsertAtVariables `"`macval(value)'"' 1 "1"
+ }
+ else local value
+ file write `file' `macval(delimiter)' `colfmt' (`"`macval(value)'"')
+ if `:word `c' of `starsrow''==1 {
+ file write `file' `macval(stardetach)' _skip(`starwidth')
+ }
+ local lastr "`r'"
+ local lastrtwo "`rtwo'"
+ }
+ else {
+ local ++nspan
+ local spanwidth=`spanwidth'+`colwidthj'+`delwidth'
+ if `:word `c' of `starsrow''==1 {
+ local spanwidth = `spanwidth' + `starwidth'
+ if `"`macval(stardetach)'"'!="" {
+ local ++nspan
+ local spanwidth = `spanwidth' + `delwidth'
+ }
+ }
+ local nextrtwo: word `=`c'+1' of `rowtwo'
+ local nextr: word `=`c'+1' of `row'
+ if "`r'"!="." & ///
+ ("`r'"!="`nextr'" | "`rtwo'"!="`nextrtwo'" | `"`rowtwo'"'=="") {
+ local value: word `r' of `macval(labels)'
+ Abbrev `spanwidth' `"`macval(value)'"' "`abbrev'"
+ local value `"`macval(prefix)'`macval(value)'`macval(suffix)'"'
+ InsertAtVariables `"`macval(value)'"' 1 "`nspan'"
+ if `spanwidth'>0 local spanfmt "%-`spanwidth's"
+ file write `file' `macval(delimiter)' `spanfmt' (`"`macval(value)'"')
+ InsertAtVariables `"`macval(repeat)'"' 1 "`c0'-`=`c0'+`nspan'-1'"
+ local repeatlist `"`macval(repeatlist)'`macval(value)'"'
+ local c0 = `c0' + `nspan'
+ local nspan 0
+ local spanwidth -`delwidth'
+ }
+ }
+ }
+ c_local value `"`macval(repeatlist)'"'
+end
+
+program WriteBegin
+ args file pre begin post
+ foreach line of local pre {
+ file write `file' `newline' `"`macval(line)'"'
+ local newline _n
+ }
+ file write `file' `macval(begin)' `macval(post)'
+end
+
+program WriteEnd
+ args file end post post2
+ file write `file' `macval(end)'
+ WriteStrLines `"`file'"' `"`macval(post)'"'
+ WriteStrLines `"`file'"' `"`macval(post2)'"'
+ file write `file' _n
+end
+
+program WriteStrLines
+ args file lines
+ foreach line of local lines {
+ file write `file' `newline' `"`macval(line)'"'
+ local newline _n
+ }
+end
+
+program WriteEqrow
+ args file delimiter stardetach value row span vwidth fmt_v ///
+ abbrev mwidth delwidth starwidth prefix suffix ///
+ haslabcol2 labcolwidth fmt_l2
+ local nspan 1
+ local spanwidth `vwidth'
+ local spanfmt
+ local c 0
+ local nmwidth: list sizeof mwidth
+ if `"`span'"'=="" {
+ Abbrev `vwidth' `"`macval(value)'"' "`abbrev'"
+ local value `"`macval(prefix)'`macval(value)'`macval(suffix)'"'
+ InsertAtVariables `"`macval(value)'"' 1 "1"
+ file write `file' `fmt_v' (`"`macval(value)'"')
+ if `haslabcol2' {
+ file write `file' `macval(delimiter)' `fmt_l2' ("")
+ }
+ foreach r of local row {
+ local mwidthj: word `=1+mod(`c++',`nmwidth')' of `mwidth'
+ if `mwidthj'>0 local fmt_m "%`mwidthj's"
+ else local fmt_m
+ file write `file' `macval(delimiter)' `fmt_m' ("")
+ if `r'==1 {
+ file write `file' `macval(stardetach)' _skip(`starwidth')
+ }
+ }
+ }
+ else {
+ if `haslabcol2' {
+ local ++nspan
+ local spanwidth = `spanwidth' + `delwidth' + `labcolwidth'
+ }
+ foreach r of local row {
+ local mwidthj: word `=1+mod(`c++',`nmwidth')' of `mwidth'
+ local ++nspan
+ local spanwidth = `spanwidth' + `delwidth' + `mwidthj'
+ if `r'==1 {
+ local spanwidth = `spanwidth' + `starwidth'
+ if `"`macval(stardetach)'"'!="" {
+ local ++nspan
+ local spanwidth = `spanwidth' + `delwidth'
+ }
+ }
+ }
+ Abbrev `spanwidth' `"`macval(value)'"' "`abbrev'"
+ local value `"`macval(prefix)'`macval(value)'`macval(suffix)'"'
+ InsertAtVariables `"`macval(value)'"' 1 "`nspan'"
+ if `spanwidth'>0 local spanfmt "%-`spanwidth's"
+ file write `file' `spanfmt' (`"`macval(value)'"')
+ }
+end
+
+prog WriteStrRow
+ args file mrow eqrow neq labels delimiter stardetach starsrow ///
+ abbrev colwidth delwidth starwidth
+ local c 0
+ local ncolwidth: list sizeof colwidth
+ foreach mnum of local mrow {
+ local eqnum: word `++c' of `eqrow'
+ local colwidthj: word `=1+mod(`c'-1,`ncolwidth')' of `colwidth'
+ if `colwidthj'>0 local colfmt "%`colwidthj's"
+ else local colfmt
+ if "`mnum'"=="." {
+ file write `file' `macval(delimiter)' `colfmt' (`""')
+ continue
+ }
+ if ( "`mnum'"!="`lastmnum'" | "`eqnum'"!="`lasteqnum'" ) {
+ local value: word `=(`mnum'-1)*`neq'+`eqnum'' of `macval(labels)'
+ Abbrev `colwidthj' `"`macval(value)'"' "`abbrev'"
+ }
+ else local value
+ file write `file' `macval(delimiter)' `colfmt' (`"`macval(value)'"')
+ if `:word `c' of `starsrow''==1 {
+ file write `file' `macval(stardetach)' _skip(`starwidth')
+ }
+ local lastmnum "`mnum'"
+ local lasteqnum "`eqnum'"
+ }
+end
+
+program VarInList
+ args var unstack eqvar eq list
+ local value
+ local L: word count `macval(list)'
+ forv l = 1(2)`L' {
+ local lvar: word `l' of `macval(list)'
+ local lab: word `=`l'+1' of `macval(list)'
+ if "`unstack'"!="" {
+ if `"`var'"'==`"`lvar'"' {
+ local value `"`macval(lab)'"'
+ continue, break
+ }
+ }
+ else {
+ if inlist(`"`lvar'"',`"`var'"',`"`eqvar'"',`"`eq':"') {
+ local value `"`macval(lab)'"'
+ continue, break
+ }
+ }
+ }
+ c_local value `"`macval(value)'"'
+end
+
+program vFormat
+ args value fmt lz dmarker msign par
+ if substr(`"`fmt'"',1,1)=="a" {
+ SignificantDigits `fmt' `value'
+ }
+ else {
+ capt confirm integer number `fmt'
+ if !_rc {
+ local fmt %`=`fmt'+9'.`fmt'f
+ }
+ }
+ else if `"`fmt'"'=="%g" | `"`fmt'"'=="g" local fmt "%9.0g"
+ else if substr(`"`fmt'"',1,1)!="%" {
+ di as err `"`fmt': invalid format"'
+ exit 198
+ }
+ local value: di `fmt' `value'
+ local value: list retok value
+ if "`lz'"=="" {
+ if index("`value'","0.")==1 | index("`value'","-0.") {
+ local value: subinstr local value "0." "."
+ }
+ }
+ if `"`macval(dmarker)'"'!="" {
+ if "`: set dp'"=="comma" local dp ,
+ else local dp .
+ local val: subinstr local value "`dp'" `"`macval(dmarker)'"'
+ }
+ else local val `"`value'"'
+ if `"`msign'"'!="" {
+ if index("`value'","-")==1 {
+ local val: subinstr local val "-" `"`macval(msign)'"'
+ }
+ }
+ if `"`par'"'!="" {
+ tokenize `"`macval(par)'"'
+ local val `"`macval(1)'`macval(val)'`macval(2)'"'
+ }
+ c_local value `"`macval(val)'"'
+end
+
+program SignificantDigits // idea stolen from outreg2.ado
+ args fmt value
+ local d = substr("`fmt'", 2, .)
+ if `"`d'"'=="" local d 3
+ capt confirm integer number `d'
+ if _rc {
+ di as err `"`fmt': invalid format"'
+ exit 198
+ }
+// missing: format does not matter
+ if `value'>=. local fmt "%9.0g"
+// integer: print no decimal places
+ else if (`value'-int(`value'))==0 {
+ local fmt "%12.0f"
+ }
+// value in (-1,1): display up to 9 decimal places with d significant
+// digits, then switch to e-format with d-1 decimal places
+ else if abs(`value')<1 {
+ local right = -int(log10(abs(`value'-int(`value')))) // zeros after dp
+ local dec = max(1,`d' + `right')
+ if `dec'<=9 {
+ local fmt "%12.`dec'f"
+ }
+ else {
+ local fmt "%12.`=min(9,`d'-1)'e"
+ }
+ }
+// |values|>=1: display d+1 significant digits or more with at least one
+// decimal place and up to nine digits before the decimal point, then
+// switch to e-format
+ else {
+ local left = int(log10(abs(`value'))+1) // digits before dp
+ if `left'<=9 {
+ local fmt "%12.`=max(1,`d' - `left' + 1)'f"
+ }
+ else {
+ local fmt "%12.0e" // alternatively: "%12.`=min(9,`d'-1)'e"
+ }
+ }
+ c_local fmt "`fmt'"
+end
+
+program Stars
+ args starlevels P
+ if inrange(`P',0,1) {
+ local nstar: word count `macval(starlevels)'
+ forv i=1(2)`nstar' {
+ local istarsym: word `i' of `macval(starlevels)'
+ local istar: word `=`i'+1' of `macval(starlevels)'
+ if `istar'<=`P' continue, break
+ local value "`macval(istarsym)'"
+ }
+ }
+ c_local value `"`macval(value)'"'
+end
+
+program CellStars
+ args starlevels P par
+ Stars `"`macval(starlevels)'"' `P'
+ if `"`par'"'!="" {
+ tokenize `"`macval(par)'"'
+ local value `"`macval(1)'`macval(value)'`macval(2)'"'
+ }
+ c_local value `"`macval(value)'"'
+end
+
+prog MakeSign
+ args value msign par starlevels P
+ if "`P'"!="" {
+ local factor = 0
+ while 1 {
+ gettoken istar starlevels : starlevels
+ gettoken istar starlevels : starlevels
+ if `"`istar'"'=="" continue, break
+ if `P'<`istar' local factor = `factor' + 1
+ else if `istar'==1 local factor = 1
+ }
+ }
+ else local factor 1
+ if `"`macval(msign)'"'=="" local msign "-"
+ if `value'<0 {
+ local val: di _dup(`factor') `"`macval(msign)'"'
+ }
+ else if `value'==0 local val: di _dup(`factor') "0"
+ else if `value'>0 & `value'<. local val: di _dup(`factor') "+"
+ else local val `value'
+ if `"`par'"'!="" {
+ tokenize `"`macval(par)'"'
+ local val `"`macval(1)'`macval(val)'`macval(2)'"'
+ }
+ c_local value `"`macval(val)'"'
+end
+
+program DropOrKeep
+ args type b spec // type=0: drop; type=1: keep
+ capt confirm matrix `b'
+ if _rc {
+ exit
+ }
+ tempname res bt
+ local R = rowsof(`b')
+ forv i=1/`R' {
+ local hit 0
+ mat `bt' = `b'[`i',1...]
+ foreach sp of local spec {
+ if rownumb(`bt', `"`sp'"')==1 {
+ local hit 1
+ continue, break
+ }
+ }
+ if `hit'==`type' mat `res' = nullmat(`res') \ `bt'
+ }
+ capt mat drop `b'
+ capt mat rename `res' `b'
+end
+
+program Order
+ args b spec
+ capt confirm matrix `b'
+ if _rc {
+ exit
+ }
+ tempname bt res
+ local eqlist: roweq `b', q
+ local eqlist: list uniq eqlist
+ mat `bt' = `b'
+ gettoken spi rest : spec
+ while `"`spi'"'!="" {
+ gettoken spinext rest : rest
+ if !index(`"`spi'"',":") {
+ local vars `"`vars'`"`spi'"' "'
+ if `"`spinext'"'!="" & !index(`"`spinext'"',":") {
+ local spi `"`spinext'"'
+ continue
+ }
+ foreach eq of local eqlist {
+ foreach var of local vars {
+ local splist `"`splist'`"`eq':`var'"' "'
+ }
+ local splist `"`splist'`"`eq':"' "' // rest
+ }
+ local vars
+ }
+ else local splist `"`spi'"'
+ gettoken sp splist : splist
+ while `"`sp'"'!="" {
+ local isp = rownumb(`bt', "`sp'")
+ if `isp' >= . {
+ gettoken sp splist : splist
+ continue
+ }
+ while `isp' < . {
+ mat `res' = nullmat(`res') \ `bt'[`isp',1...]
+ local nb = rowsof(`bt')
+ if `nb' == 1 { // no rows left in `bt'
+ capt mat drop `b'
+ capt mat rename `res' `b'
+ exit
+ }
+ if `isp' == 1 {
+ mat `bt' = `bt'[2...,1...]
+ }
+ else if `isp' == `nb' {
+ mat `bt' = `bt'[1..`=`nb'-1',1...]
+ }
+ else {
+ mat `bt' = `bt'[1..`=`isp'-1',1...] \ `bt'[`=`isp'+1'...,1...]
+ }
+ local isp = rownumb(`bt', "`sp'")
+ }
+ gettoken sp splist : splist
+ }
+ local spi `"`spinext'"'
+ }
+ capt mat `res' = nullmat(`res') \ `bt'
+ capt mat drop `b'
+ capt mat rename `res' `b'
+end
+
+prog MakeQuotedFullnames
+ args names eqs
+ foreach name of local names {
+ gettoken eq eqs : eqs
+ local value `"`value'`"`eq':`name'"' "'
+ }
+ c_local value: list clean value
+end
+
+program define QuotedRowNames
+ args matrix
+ capt confirm matrix `matrix'
+ if _rc {
+ c_local value ""
+ exit
+ }
+ tempname extract
+ if substr(`"`matrix'"',1,2)=="r(" {
+ local matrix0 `"`matrix'"'
+ tempname matrix
+ mat `matrix' = `matrix0'
+ }
+ local R = rowsof(`matrix')
+ forv r = 1/`R' {
+ mat `extract' = `matrix'[`r',1...]
+ local name: rownames `extract'
+ local value `"`value'`"`name'"' "'
+ }
+ c_local value: list clean value
+end
+
+prog EqReplaceCons
+ args names eqlist eqlabels varlabels
+ local skip 0
+ foreach v of local varlabels {
+ if `skip' {
+ local skip 0
+ continue
+ }
+ local vlabv `"`vlabv'`"`v'"' "'
+ local skip 1
+ }
+ local deqs: list dups eqlist
+ local deqs: list uniq deqs
+ local i 0
+ foreach eq of local eqlist {
+ local ++i
+ if `"`eq'"'!=`"`last'"' {
+ gettoken eqlab eqlabels : eqlabels
+ }
+ local last `"`eq'"'
+ if `:list eq in deqs' | `"`eq'"'=="_" continue
+ local name: word `i' of `names'
+ local isinvlabv: list posof `"`eq':`name'"' in vlabv
+ if `"`name'"'=="_cons" & `isinvlabv'==0 {
+ local value `"`value'`space'`"`eq':`name'"' `"`eqlab'"'"'
+ local space " "
+ }
+ }
+ c_local value `"`value'"'
+end
+
+prog UniqEqsAndDims
+ local n 0
+ foreach el of local 1 {
+ if `"`macval(el)'"'!=`"`macval(last)'"' {
+ if `n'>0 local eqsdims "`eqsdims' `n'"
+ local eqs `"`macval(eqs)' `"`macval(el)'"'"'
+ local n 0
+ }
+ local ++n
+ local last `"`macval(el)'"'
+ }
+ local eqsdims "`eqsdims' `n'"
+ c_local eqsdims: list clean eqsdims
+ c_local eqs: list clean eqs
+end
+
+prog InsertAtCols
+ args colnums row symb
+ if `"`symb'"'=="" local symb .
+ gettoken c rest : colnums
+ local i 0
+ foreach r of local row {
+ local ++i
+ while `"`c'"'!="" {
+ if `c'<=`i' {
+ local value `"`value' `symb'"'
+ gettoken c rest : rest
+ }
+ else continue, break
+ }
+ local value `"`value' `"`r'"'"'
+ }
+ while `"`c'"'!="" {
+ local value `"`value' `symb'"'
+ gettoken c rest : rest
+ }
+ c_local value: list clean value
+end
+
+prog GetVarnamesFromOrder
+ foreach sp of local 1 {
+ if index(`"`sp'"', ":") {
+ gettoken trash sp: sp, parse(:)
+ if `"`trash'"'!=":" {
+ gettoken trash sp: sp, parse(:)
+ }
+ }
+ local value `"`value'`space'`sp'"'
+ local space " "
+ }
+ c_local value `"`value'"'
+end
+
+prog ParseIndicateOpts
+ syntax [anything(equalok)] [, Labels(str asis) ]
+ gettoken tok rest : anything, parse(" =")
+ while `"`macval(tok)'"'!="" {
+ if `"`macval(tok)'"'=="=" {
+ local anything `"`"`macval(anything)'"'"'
+ continue, break
+ }
+ gettoken tok rest : rest, parse(" =")
+ }
+ c_local indicate `"`macval(anything)'"'
+ c_local indicatelabels `"`macval(labels)'"'
+end
+
+prog ProcessIndicateGrp
+ args i B nmodels unstack yesno indicate
+ gettoken yes no : yesno
+ gettoken no : no
+ gettoken tok rest : indicate, parse(=)
+ while `"`macval(tok)'"'!="" {
+ if `"`macval(rest)'"'=="" {
+ local vars `"`indicate'"'
+ continue, break
+ }
+ if `"`macval(tok)'"'=="=" {
+ local vars `"`rest'"'
+ continue, break
+ }
+ local name `"`macval(name)'`space'`macval(tok)'"'
+ local space " "
+ gettoken tok rest : rest, parse(=)
+ }
+ if `"`macval(name)'"'=="" {
+ local name: word 1 of `"`vars'"'
+ }
+ ExpandEqVarlist `"`vars'"' `B'
+ local evars `"`value'"'
+ IsInModels `B' `nmodels' "`unstack'" `"`macval(yes)'"' `"`macval(no)'"' `"`evars'"'
+ local lbls `"`macval(value)'"'
+ DropOrKeep 0 `B' `"`evars'"'
+ c_local indicate`i'name `"`macval(name)'"'
+ c_local indicate`i'lbls `"`macval(lbls)'"'
+ c_local indicate`i'eqs `"`eqs'"'
+end
+
+prog IsInModels
+ args B nmodels unstack yes no vars
+ capt confirm matrix `B'
+ if _rc {
+ forv i = 1/`nmodels' {
+ local lbls `"`macval(lbls)' `"`macval(no)'"'"'
+ }
+ c_local value `"`macval(lbls)'"'
+ if `"`unstack'"'!="" {
+ c_local eqs "_"
+ }
+ exit
+ }
+ local models: coleq `B', q
+ local models: list uniq models
+ local eqs: roweq `B', q
+ local eqs: list uniq eqs
+ tempname Bt Btt Bttt
+ foreach model of local models {
+ local stop 0
+ mat `Bt' = `B'[1...,"`model':"]
+ foreach eq of local eqs {
+ mat `Btt' = `Bt'[`"`eq':"',1]
+ if `"`unstack'"'!="" local stop 0
+ foreach var of local vars {
+ if !index(`"`var'"',":") {
+ local var `"`eq':`var'"'
+ }
+ capt mat `Bttt' = `Btt'["`var'",1]
+ if _rc continue
+ forv i = 1/`= rowsof(`Bttt')' {
+ if `Bttt'[`i',1]<.z {
+ local lbls `"`macval(lbls)' `"`macval(yes)'"'"'
+ local stop 1
+ continue, break
+ }
+ }
+ if `stop' continue, break
+ }
+ if `"`unstack'"'!="" {
+ if `stop'==0 {
+ local lbls `"`macval(lbls)' `"`macval(no)'"'"'
+ }
+ }
+ else if `stop' continue, break
+ }
+ if `"`unstack'"'=="" & `stop'==0 {
+ local lbls `"`macval(lbls)' `"`macval(no)'"'"'
+ }
+ }
+ c_local value `"`macval(lbls)'"'
+ if `"`unstack'"'!="" {
+ c_local eqs `"`eqs'"'
+ }
+end
+
+prog ReorderEqsInIndicate
+ args nmodels eqs ieqs lbls
+ local neq: list sizeof ieqs
+ foreach eq of local eqs {
+ local i: list posof `"`eq'"' in ieqs
+ if `i' {
+ local pos `pos' `i'
+ }
+ }
+ forv m=1/`nmodels' {
+ foreach i of local pos {
+ local mi = (`m'-1)*`neq' + `i'
+ local lbl: word `mi' of `macval(lbls)'
+ local value `"`macval(value)'`"`macval(lbl)'"' "'
+ }
+ }
+ c_local value `"`macval(value)'"'
+end
+
+prog ParseRefcatOpts
+ syntax [anything(equalok)] [, NOLabel Label(str) Below ]
+ c_local refcatbelow "`below'"
+ c_local norefcatlabel "`nolabel'"
+ c_local refcatlabel `"`macval(label)'"'
+ c_local refcat `"`macval(anything)'"'
+end
+
+prog PrepareRefcat
+ gettoken coef rest : 1
+ gettoken name rest : rest
+ while `"`macval(coef)'"'!="" {
+ local coefs `"`coefs'`coef' "'
+ local names `"`macval(names)'`"`macval(name)'"' "'
+ gettoken coef rest : rest
+ gettoken name rest : rest
+ }
+ c_local refcatcoefs `"`coefs'"'
+ c_local refcatnames `"`macval(names)'"'
+end
+
+prog GenerateRefcatRow
+ args B ccols var eqs label
+ local models: coleq `B', q
+ local models: list uniq models
+ local col 1
+ foreach model of local models {
+ foreach eq of local eqs {
+ local eqvar `"`eq':`var'"'
+ local row = rownumb(`B',"`eqvar'")
+ if `B'[`row', `col']<.z {
+ local value `"`macval(value)'`"`macval(label)'"' "'
+ }
+ else {
+ local value `"`macval(value)'`""' "'
+ }
+ }
+ local col = `col' + `ccols'
+ }
+ c_local value `"`macval(value)'"'
+end
+
+prog ParseTransformSubopts
+ syntax anything(equalok) [, Pattern(string) ]
+ c_local transform `"`anything'"'
+ c_local transformpattern "`pattern'"
+end
+
+prog MakeTransformList
+ args B transform
+ local R = rowsof(`B')
+ if `:list sizeof transform'<=2 {
+ gettoken f rest : transform
+ gettoken df : rest
+ forv i = 1/`R' {
+ local valuef `"`valuef'`f' "'
+ local valuedf `"`valuedf'`df' "'
+ }
+ c_local valuef: list retok valuef
+ c_local valuedf: list retok valuedf
+ exit
+ }
+ gettoken coef rest : transform
+ gettoken f rest : rest
+ gettoken df rest : rest
+ while (`"`coef'"'!="") {
+ if (`"`df'`rest'"'!="") { // last element of list may be without coef
+ ExpandEqVarlist `"`coef'"' `B'
+ local coef `"`value'"'
+ }
+ local coefs `"`coefs'`"`coef'"' "'
+ local fs `"`fs'`"`f'"' "'
+ local dfs `"`dfs'`"`df'"' "'
+ gettoken coef rest : rest
+ gettoken f rest : rest
+ gettoken df rest : rest
+ }
+ tempname b
+ local value
+ forv i = 1/`R' {
+ mat `b' = `B'[`i',1...]
+ local i 0
+ local hit 0
+ foreach coef of local coefs {
+ local f: word `++i' of `fs'
+ local df: word `i' of `dfs'
+ if (`"`df'`rest'"'=="") {
+ local valuef `"`valuef'`"`coef'"' "' // sic! (see above)
+ local valuedf `"`valuedf'`"`f'"' "'
+ local hit 1
+ continue, break
+ }
+ foreach c of local coef {
+ if rownumb(`b', `"`c'"')==1 {
+ local valuef `"`valuef'`"`f'"' "'
+ local valuedf `"`valuedf'`"`df'"' "'
+ local hit 1
+ continue, break
+ }
+ }
+ if `hit' continue, break
+ }
+ if `hit'==0 {
+ local valuef `"`valuef'"" "'
+ local valuedf `"`valuedf'"" "'
+ }
+ }
+ c_local valuef: list retok valuef
+ c_local valuedf: list retok valuedf
+end
+
+prog TableIsAMess
+ local ccols = r(ccols)
+ local eq: roweq r(coefs), q
+ local eq: list uniq eq
+ if `: list sizeof eq'<=1 {
+ c_local value 0
+ exit
+ }
+ tempname b bt
+ mat `b' = r(coefs)
+ gettoken eq : eq
+ mat `b' = `b'[`"`eq':"', 1...]
+ local R = rowsof(`b')
+ local models: coleq `b', q
+ local models: list uniq models
+ local value 0
+ local i = 1 - `ccols'
+ foreach model of local models {
+ local i = `i' + `ccols'
+ if `i'==1 continue // skip first model
+ mat `bt' = `b'[1...,`i']
+ local allz 1
+ forv r = 1/`R' {
+ if `bt'[`r',1]<.z {
+ local allz 0
+ continue, break
+ }
+ }
+ if `allz' {
+ local value 1
+ continue, break
+ }
+ }
+ c_local value `value'
+end
+
+prog ExpandEqVarlist
+ args list B append
+ ParseEqVarlistRelax `list'
+ QuotedRowNames `B'
+ local coefs `"`value'"'
+ local value
+ local ucoefs: list uniq coefs
+ capt confirm matrix `B'
+ if _rc==0 {
+ local eqs: roweq `B', q
+ }
+ else local eqs "_"
+ local ueqs: list uniq eqs
+ while `"`list'"'!="" {
+// get next element
+ gettoken eqx list : list
+// separate eq and x
+ gettoken eq x : eqx, parse(:)
+ local eq: list clean eq
+ if `"`eq'"'==":" { // case 1: ":[varname]"
+ local eq
+ }
+ else if `"`x'"'=="" { // case 2: "varname"
+ local x `"`eq'"'
+ local eq
+ }
+ else { // case 3. "eqname:[varname]"
+ gettoken colon x : x, parse(:)
+ local x: list clean x
+ }
+// match equations
+ local eqmatch
+ if `:list eq in ueqs' { // (note: evaluates to 1 if eq empty)
+ local eqmatch `"`eq'"'
+ }
+ else {
+ foreach e of local ueqs {
+ if match(`"`e'"', `"`eq'"') {
+ local eqmatch `"`eqmatch' `"`e'"'"'
+ }
+ }
+ if `"`eqmatch'"'=="" & "`relax'"=="" {
+ if !("`append'"!="" & `"`x'"'!="") {
+ di as err `"equation `eq' not found"'
+ exit 111
+ }
+ }
+ local eqmatch: list clean eqmatch
+ }
+ if `"`x'"'=="" {
+ foreach e of local eqmatch {
+ local value `"`value' `"`e':"'"'
+ }
+ continue
+ }
+// match coefficients
+ local vlist
+// - without equation
+ if `"`eq'"'=="" {
+ if `:list x in ucoefs' {
+ local value `"`value' `"`x'"'"'
+ continue
+ }
+ foreach coef of local ucoefs {
+ if match(`"`coef'"', `"`x'"') {
+ local vlist `"`vlist' `"`coef'"'"'
+ }
+ }
+ if `"`vlist'"'=="" {
+ if "`append'"!="" {
+ local appendlist `"`appendlist' `"`x'"'"'
+ local value `"`value' `"`x'"'"'
+ }
+ else if "`relax'"=="" {
+ di as err `"coefficient `x' not found"'
+ exit 111
+ }
+ }
+ else {
+ local value `"`value' `vlist'"'
+ }
+ continue
+ }
+// - within equations
+ local rest `"`eqs'"'
+ foreach coef of local coefs {
+ gettoken e rest : rest
+ if !`:list e in eqmatch' {
+ continue
+ }
+ if match(`"`coef'"', `"`x'"') {
+ local vlist `"`vlist' `"`e':`coef'"'"'
+ }
+ }
+ if `"`vlist'"'=="" {
+ if "`append'"!="" {
+ local appendlist `"`appendlist' `"`eq':`x'"'"'
+ local value `"`value' `"`eq':`x'"'"'
+ }
+ else if "`relax'"=="" {
+ di as err `"coefficient `eq':`x' not found"'
+ exit 111
+ }
+ }
+ else {
+ local value `"`value' `vlist'"'
+ }
+ }
+ if "`append'"!="" {
+ local nappend : list sizeof appendlist
+ if `nappend'>0 {
+ capt confirm matrix `B'
+ if _rc==0 {
+ tempname tmp
+ mat `tmp' = J(`nappend', colsof(`B'), .z)
+ mat rown `tmp' = `appendlist'
+ matrix `B' = `B' \ `tmp'
+ }
+ }
+ }
+ c_local value: list clean value
+end
+
+program ParseEqVarlistRelax
+ syntax [anything] [, Relax ]
+ c_local list `"`anything'"'
+ c_local relax `relax'
+end
+
+program IsInString //, rclass
+ args needle haystack
+ local trash: subinstr local haystack `"`needle'"' "", count(local count)
+ c_local strcount = `count'
+end
+
+program MakeRtfRowdefs
+ args str srow sdetach vwidth mwidth haslc2 lc2width
+ local factor 120
+ ParseRtfcmdNum `"`str'"' "trgaph" 0
+ ParseRtfcmdNum `"`str'"' "trleft" 0
+ if `vwidth'<=0 local vwidth 12
+ if real(`"`trgaph'"')>=. local trgaph 0
+ if real(`"`trleft'"')>=. local trleft 0
+ local swidth = 3
+ local vtwips = `vwidth'*`factor'
+ local stwips = `swidth'*`factor'
+ local ipos = `vtwips' + 2*`trgaph' + (`trleft')
+ local brdrt "\clbrdrt\brdrw10\brdrs"
+ local brdrb "\clbrdrb\brdrw10\brdrs"
+ local emptycell "\pard\intbl\ql\cell"
+ local rtfdef "\cellx`ipos'"
+ local rtfdefbrdrt "`brdrt'\cellx`ipos'"
+ local rtfdefbrdrb "`brdrb'\cellx`ipos'"
+ local rtfrow "`emptycell'"
+ if `haslc2' {
+ if `lc2width'<=0 local lc2width 12
+ local lc2twips = `lc2width'*`factor'
+ local ipos = `ipos' + `lc2twips' + 2*`trgaph'
+ local rtfdef "`rtfdef'\cellx`ipos'"
+ local rtfdefbrdrt "`rtfdefbrdrt'`brdrt'\cellx`ipos'"
+ local rtfdefbrdrb "`rtfdefbrdrb'`brdrb'\cellx`ipos'"
+ local rtfrow "`rtfrow'`emptycell'"
+ }
+ local j 0
+ local nmwidth: list sizeof mwidth
+ foreach i of local srow {
+ local mwidthj: word `=1 + mod(`j++',`nmwidth')' of `mwidth'
+ if `mwidthj'<=0 local mwidthj 12
+ local mtwips = `mwidthj'*`factor'
+ local ipos = `ipos' + `mtwips' + 2*`trgaph'
+ if `i' & "`sdetach'"=="" local ipos = `ipos' + `stwips'
+ local rtfdef "`rtfdef'\cellx`ipos'"
+ local rtfdefbrdrt "`rtfdefbrdrt'`brdrt'\cellx`ipos'"
+ local rtfdefbrdrb "`rtfdefbrdrb'`brdrb'\cellx`ipos'"
+ local rtfrow "`rtfrow'`emptycell'"
+ if `i' & "`sdetach'"!="" {
+ local ipos = `ipos' + `stwips' + 2*`trgaph'
+ local rtfdef "`rtfdef'\cellx`ipos'"
+ local rtfdefbrdrt "`rtfdefbrdrt'`brdrt'\cellx`ipos'"
+ local rtfdefbrdrb "`rtfdefbrdrb'`brdrb'\cellx`ipos'"
+ local rtfrow "`rtfrow'`emptycell'"
+ }
+ }
+ c_local rtfrowdef "`rtfdef'"
+ c_local rtfrowdefbrdrt "`rtfdefbrdrt'"
+ c_local rtfrowdefbrdrb "`rtfdefbrdrb'"
+ c_local rtfemptyrow "`rtfdef'`rtfrow'"
+end
+
+prog ParseRtfcmdNum
+ args str cmd default
+ local pos = index(`"`str'"', `"\\`cmd'"')
+ if `pos' {
+ local pos = `pos' + strlen(`"`cmd'"') + 1
+ local digit = substr(`"`str'"',`pos',1)
+ if `"`digit'"'=="-" {
+ local value "`digit'"
+ local digit = substr(`"`str'"',`++pos',1)
+ }
+ while real(`"`digit'"')<. {
+ local value "`value'`digit'"
+ local digit = substr(`"`str'"',`++pos',1)
+ }
+ }
+ local value = real(`"`value'"')
+ if `value'>=. local value = `default'
+ c_local `cmd' `"`value'"'
+end
+
+prog ParseLabCol2
+ syntax [anything(equalok)] [ , Title(str asis) Width(numlist max=1 int >=0) ]
+ c_local labcol2 `"`macval(anything)'"'
+ c_local labcol2title `"`macval(title)'"'
+ c_local labcol2width `"`width'"'
+end
+
+prog MakeMMDdef
+ args varw labcol2 labcol2w modelw starsrow stardetachon starw
+ if "`varw'"=="0" | "`varw'"=="" local varw 1
+ if "`labcol2w'"=="0" | "`labcol2w'"=="" local labcol2w 1
+ if "`modelw'"=="0" | "`modelw'"=="" local modelw 1
+ if "`starw'"=="0" | "`starw'"=="" local starw 1
+ local varw = max(1,`varw')
+ local labcol2w = max(1,`labcol2w'-2)
+ if "`stardetachon'"=="1" local starw = max(1,`starw'-2)
+ else local starw = max(1,`starw')
+
+ local mmddef `"| `:di _dup(`varw') "-"'"'
+ if "`labcol2'"=="1" {
+ local mmddef `"`mmddef' | :`:di _dup(`labcol2w') "-"':"'
+ }
+ local nmodelw: list sizeof modelw
+ local c 0
+ foreach col of local starsrow {
+ local modelwj: word `=1+mod(`c++',`nmodelw')' of `modelw'
+ local modelwj = max(1,`modelwj'-2)
+ local mmddef `"`mmddef' | :`:di _dup(`modelwj') "-"'"'
+ if "`col'"=="1" {
+ if "`stardetachon'"=="1" {
+ local mmddef `"`mmddef': | :"'
+ }
+ local mmddef `"`mmddef'`:di _dup(`starw') "-"'"'
+ }
+ local mmddef `"`mmddef':"'
+ }
+ c_local value `"`mmddef' |"'
+end
+
+program MatrixMode, rclass
+ capt syntax [, Matrix(str asis) e(str asis) r(str asis) rename(str asis) ]
+ if _rc | `"`matrix'`e'`r'"'=="" {
+ c_local matrixmode 0
+ exit
+ }
+ if ((`"`matrix'"'!="") + (`"`e'"'!="") + (`"`r'"'!=""))>1 {
+ di as err "only one of matrix(), e(), or r() allowed"
+ exit 198
+ }
+ ParseMatrixOpt `matrix'`e'`r'
+ if `"`e'"'!="" {
+ local name "e(`name')"
+ }
+ else if `"`r'"'!="" {
+ local name "r(`name')"
+ }
+ confirm matrix `name'
+ tempname bc
+ if "`transpose'"=="" {
+ mat `bc' = `name''
+ }
+ else {
+ mat `bc' = `name'
+ }
+ QuotedRowNames `bc'
+ local rnames `"`value'"'
+ local eqs: roweq `bc', q
+ mat `bc' = `bc''
+ local cols = colsof(`bc')
+ local cells
+ local space
+ gettoken fmti fmtrest : fmt, match(par)
+ gettoken rname rnames : rnames
+ gettoken eq eqs : eqs
+ forv i = 1/`cols' {
+ if `"`fmti'"'!="" {
+ local fmtopt `"f(`fmti') "'
+ gettoken fmti fmtrest : fmtrest, match(par)
+ if `"`fmti'"'=="" & `"`fmtrest'"'=="" { // recycle
+ gettoken fmti fmtrest : fmt, match(par)
+ }
+ }
+ else local fmtopt
+ if `"`eq'"'=="_" {
+ local lbl `"l(`"`rname'"')"'
+ }
+ else {
+ local lbl `"l(`"`eq':`rname'"')"'
+ }
+ local cells `"`cells'`space'c`i'(`fmtopt'`lbl')"'
+ local space " "
+ gettoken rname rnames : rnames
+ gettoken eq eqs : eqs
+ }
+ if `"`rename'"'!="" {
+ local rename : subinstr local rename "," "", all
+ RenameCoefs `bc' `"`rename'"'
+ }
+ return local names "`name'"
+ return scalar nmodels = 1
+ return scalar ccols = `cols'
+ return matrix coefs = `bc'
+ c_local matrixmode 1
+ c_local cells (`cells')
+end
+
+program ParseMatrixOpt
+ syntax name [, Fmt(str asis) Transpose ]
+ c_local name `"`namelist'"'
+ c_local fmt `"`fmt'"'
+ c_local transpose `"`transpose'"'
+end
diff --git a/Modules/ado/plus/e/estout.hlp b/Modules/ado/plus/e/estout.hlp
new file mode 100644
index 0000000..eba9543
--- /dev/null
+++ b/Modules/ado/plus/e/estout.hlp
@@ -0,0 +1,2438 @@
+{smcl}
+{* 09mar2009}{...}
+{cmd:help estout}{right:also see: {helpb esttab}, {helpb eststo}, {helpb estadd}, {helpb estpost}}
+{right: {browse "http://repec.org/bocode/e/estout"}}
+{hline}
+
+{title:Title}
+
+{p 4 4 2}{hi:estout} {hline 2} Making regression tables from stored estimates
+
+
+{title:Table of contents}
+
+ {help estout##syn:Syntax}
+ {help estout##des:Description}
+ {help estout##opt:Options}
+ {help estout##exa:Examples}
+ {help estout##rem:Remarks}
+ {help estout##ret:Saved results}
+ {help estout##ref:Backmatter}
+
+{marker syn}
+{title:Syntax}
+
+{p 8 15 2}
+{cmd:estout} [ {help estout##what:{it:what}} ]
+ [ {cmd:using} {it:filename} ]
+ [ {cmd:,} {help estout##opt0:{it:options}} ]
+
+{marker what}
+ {it:what}{col 30}description
+ {hline 70}
+ {it:namelist}{col 30}{...}
+tabulate stored estimation sets; {it:namelist} is
+{col 32}a name, a list of names, or {cmd:_all}; the {cmd:*} and
+{col 32}{cmd:?} wildcards are allowed; a name may also be
+{col 32}{cmd:.}, meaning the current (active) estimates
+
+ {cmdab:m:atrix:(}{it:name}[{cmd:,} {it:subopts}]{cmd:)}{col 30}{...}
+tabulate matrix {it:name}
+ {cmd:e(}{it:name}[{cmd:,} {it:subopts}]{cmd:)}{col 30}{...}
+tabulate matrix {cmd:e(}{it:name}{cmd:)}
+ {cmd:r(}{it:name}[{cmd:,} {it:subopts}]{cmd:)}{col 30}{...}
+tabulate matrix {cmd:r(}{it:name}{cmd:)}
+ {it:subopts}:
+ {helpb estout##mfmt:{ul:f}mt}{cmd:(}{it:fmtlist}{cmd:)}{col 30}{...}
+set the display format(s)
+ {helpb estout##mtranspose:{ul:t}ranspose}{col 30}{...}
+tabulate transposed matrix
+ {hline 70}
+
+{marker opt0}
+ {it:options}{col 38}description
+ {hline 70}
+ Parameter statistics
+ {helpb estout##cells:{ul:c}ells}{cmd:(}{it:elements and subopts}{cmd:)}{col 38}{...}
+contents of the table cells, where
+{col 40}an {it:element}'s {it:subopts} are in paren-
+{col 40}theses, i.e. {it:element}[{cmd:(}{it:subopts}{cmd:)}]
+ {it:elements}:
+ {cmd:b}{col 38}raw coefficient (point estimate)
+ {cmd:se}{col 38}standard error
+ {cmd:var}{col 38}variance
+ {cmd:t}{col 38}t or z statistic
+ {cmd:z}{col 38}t or z statistic (synonym for {cmd:t})
+ {cmd:p}{col 38}p-value
+ {cmd:ci}{col 38}confidence interval
+ {cmd:ci_l}{col 38}lower bound of confidence interval
+ {cmd:ci_u}{col 38}upper bound of confidence interval
+ {cmd:_star}{col 38}"significance stars"
+ {cmd:_sign}{col 38}sign of point estimate
+ {cmd:_sigsign}{col 38}sign and significance of estimate
+ {cmd:.}{col 38}null element (empty cell)
+ {cmd:&}{col 38}combine elements in single cell
+ {it:myel}{col 38}results from {cmd:e(}{it:myel}{cmd:)}
+ {it:myel}{cmd:[}{it:#}{cmd:]}{col 38}results from row {it:#} in {cmd:e(}{it:myel}{cmd:)}
+ {it:myel}{cmd:[}{it:rowname}{cmd:]}{col 38}results from row {it:rowname} in {cmd:e(}{it:myel}{cmd:)}
+
+
+ {it:subopts} (for each {it:element},
+ except for {cmd:.} and {cmd:&}):
+ [{cmdab:no:}]{helpb estout##cstar:{ul:s}tar}{col 38}{...}
+attach "significance stars"
+ {helpb estout##cfmt:{ul:f}mt}{cmd:(}{it:{help estout##fmt:fmt}} [{it:{help estout##fmt:fmt}} ...]{cmd:)}{col 38}{...}
+set the display format(s)
+ {helpb estout##clabel:{ul:l}abel}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+define a label for {it:element}
+ {helpb estout##cpar:par}[{cmd:(}{it:l} {it:r}{cmd:)}] | {cmd:nopar}{col 38}{...}
+place results in parentheses
+ {helpb estout##cvacant:{ul:v}acant}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+print {it:string} if coefficient is absent
+ {helpb estout##cdrop:{ul:d}rop}{cmd:(}{it:droplist}{cmd:)}{col 38}{...}
+drop certain individual results
+ {helpb estout##ckeep:{ul:k}eep}{cmd:(}{it:keeplist}{cmd:)}{col 38}{...}
+keep certain individual results
+ {helpb estout##cpattern:{ul:pat}tern}{cmd:(}{it:pattern}{cmd:)}{col 38}{...}
+model selection
+ {helpb estout##cpvalue:{ul:pval}ue}{cmd:(}{it:name}{cmd:)}{col 38}{...}
+set p-values for {cmd:star} (default: {cmd:p})
+ [{cmd:no}]{helpb estout##cabs:abs}{col 38}{...}
+use absolute t-statistics
+ [{cmdab:no:}]{helpb estout##ctranspose:{ul:t}ranspose}{col 38}{...}
+transpose {cmd:e(}{it:myel}{cmd:)} for tabulation
+
+ {helpb estout##drop:{ul:d}rop}{cmd:(}{it:droplist}{cmd:)}{col 38}{...}
+drop individual coefficients
+ {helpb estout##keep:{ul:k}eep}{cmd:(}{it:keeplist}{cmd:)}{col 38}{...}
+keep individual coefficients
+ {helpb estout##order:{ul:o}rder}{cmd:(}{it:orderlist}{cmd:)}{col 38}{...}
+change order of coefficients
+ {helpb estout##indicate:{ul:i}ndicate}{cmd:(}{it:groups} [{cmd:,} {it:subopt}]{cmd:)}{col 38}{...}
+indicate presence of parameters
+ {it:subopt}: {cmdab:l:abels(}{it:yes} {it:no}{cmd:)}{col 38}{...}
+redefine "Yes" and "No" labels
+ {helpb estout##rename:{ul:ren}ame}{cmd:(}{it:old} {it:new} [{it:old} {it:new} ...]{cmd:)}{col 38}{...}
+rename individual coefficients
+ {helpb estout##equations:{ul:eq}uations}{cmd:(}{it:eqmatchlist}{cmd:)}{col 38}{...}
+match the models' equations
+ {helpb estout##eform:eform}[{cmd:(}{it:pattern}{cmd:)}] | {cmd:noeform}{col 38}{...}
+report exponentiated coefficients
+ {helpb estout##transform:{ul:tr}ansform}{cmd:(}{it:list} [{cmd:,} {it:subopt}]{cmd:)}{col 38}{...}
+apply transformations to coefficients
+ {it:subopt}: {cmdab:p:attern:(}{it:pattern}{cmd:)}]{cmd:)}{col 38}{...}
+select models
+ {helpb estout##margin:{ul:m}argin}[{cmd:(}{cmd:u}|{cmd:c}|{cmd:p}{cmd:)}] | {cmdab:nom:argin}{col 38}{...}
+report marginal effects/elasticities
+ {helpb estout##discrete:{ul:di}screte}{cmd:(}{it:string}{cmd:)} | {cmdab:nodi:screte}{col 38}{...}
+identify 0/1 variables (if {cmd:margin})
+ {helpb estout##meqs:{ul:meq}s}{cmd:(}{it:eq_list}{cmd:)}{col 38}{...}
+select equations for marginal effects
+ {helpb estout##dropped:dropped}[{cmd:(}{it:string}{cmd:)}] | {cmd:nodropped}{col 38}{...}
+indicate null coefficients as dropped
+ {helpb estout##level:level}{cmd:(}{it:#}{cmd:)}{col 38}{...}
+set level for confidence intervals
+
+ Summary statistics
+ {helpb estout##stats:{ul:s}tats}{cmd:(}{it:scalarlist}[{cmd:,} {it:subopts}]{cmd:)}{col 38}{...}
+display summary statistics at the
+{col 38}bottom of the table
+ {it:subopts}:
+ {helpb estout##statsfmt:{ul:f}mt}{cmd:(}{it:{help estout##fmt:fmt}} [{it:{help estout##fmt:fmt}} ...]{cmd:)}{col 38}{...}
+set the display formats
+ {helpb estout##statslabels:{ul:l}abels}{cmd:(}{it:strlist}[{cmd:,} {col 38}{...}
+label the summary statistics
+ {it:{help estout##lsub0:label_subopts}}]{cmd:)}
+ {helpb estout##statsstar:{ul:s}tar}[{cmd:(}{it:sca'list}{cmd:)}] | {cmdab:nos:tar}{col 38}{...}
+denote the model significance
+ {helpb estout##statslayout:{ul:lay}out}{cmd:(}{it:array}{cmd:)}{col 38}{...}
+arrange the summary statistics
+ {helpb estout##statspchar:{ul:pc}har}{cmd:(}{it:symbol}{cmd:)}{col 38}{...}
+placeholder in {cmdab:layout()}; default is {cmd:@}
+
+ Significance stars
+ {helpb estout##starlevels:{ul:starl}evels}{cmd:(}{it:levelslist}{cmd:)}{col 38}{...}
+define thresholds and symbols,
+{col 40}where '{it:levelslist}' is '{it:symbol} {it:#}
+{col 40}[{it:symbol} {it:#} ...]' with {it:#} in (0,1] and
+{col 40}listed in descending order
+ {helpb estout##stardrop:{ul:stard}rop}{cmd:(}{it:droplist}{cmd:)}{col 38}{...}
+drop stars for individual coefs
+ {helpb estout##starkeep:{ul:stark}eep}{cmd:(}{it:keeplist}{cmd:)}{col 38}{...}
+keep stars for individual coefs
+ [{cmdab:no:}]{helpb estout##stardetach:{ul:stard}etach}{col 38}{...}
+display the stars in their own column
+
+ Layout
+ {helpb estout##varwidth:{ul:var}width}{cmd:(}{it:#}{cmd:)}{col 38}{...}
+set width of the table's left stub
+ {helpb estout##modelwidth:{ul:model}width}{cmd:(}{it:#} [{it:#} ...]{cmd:)}{col 38}{...}
+set width of the results columns
+ [{cmdab:no:}]{helpb estout##unstack:{ul:uns}tack}{col 38}{...}
+place equations from multiple-
+{col 40}equation models in separate columns
+ {helpb estout##begin:{ul:beg}in}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify the beginning of the rows
+ {helpb estout##delimiter:{ul:del}imiter}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify the column delimiter
+ {helpb estout##end:end}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify the ending of the table rows
+ {helpb estout##incelldel:{ul:incell}delimiter}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify delimiter within cell
+ {helpb estout##dmarker:{ul:dm}arker}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+define the decimal marker
+ {helpb estout##msign:{ul:ms}ign}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+define the minus sign
+ [{cmd:no}]{helpb estout##lz:lz}{col 38}{...}
+print the leading zero of fixed
+{col 40}format numbers in (-1,1)
+ {helpb estout##extracols:{ul:extra}cols}{cmd:(}{it:numlist}{cmd:)}{col 38}{...}
+add empty column to the table
+ {helpb estout##substitute:{ul:sub}stitute}{cmd:(}{it:subst}{cmd:)}{col 38}{...}
+apply end-of-pipe substitutions, where
+{col 40}'{it:subst}' is '{it:from} {it:to} [{it:from} {it:to} ... ]'
+
+ Labeling
+ [{cmdab:no:}]{helpb estout##label:{ul:l}abel}{col 38}{...}
+make use of variable labels
+ [{cmdab:no:}]{helpb estout##abbrev:{ul:ab}brev}{col 38}{...}
+abbreviate long names and labels
+ [{cmdab:no:}]{helpb estout##wrap:wrap}{col 38}{...}
+wrap long labels (if space permits)
+ {helpb estout##title:{ul:ti}tle}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify a title for the table
+ {helpb estout##note:note}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify a note for the table
+ [{cmdab:no:}]{helpb estout##legend:{ul:le}gend}{col 38}{...}
+add a significance symbols legend
+ {helpb estout##prehead:{ul:preh}ead}{cmd:(}{it:strlist}{cmd:)}{col 38}{...}
+add text before the table heading
+ {helpb estout##prehead:{ul:posth}ead}{cmd:(}{it:strlist}{cmd:)}{col 38}{...}
+add text after the table heading
+ {helpb estout##prehead:{ul:pref}oot}{cmd:(}{it:strlist}{cmd:)}{col 38}{...}
+add text before the table footer
+ {helpb estout##prehead:{ul:postf}oot}{cmd:(}{it:strlist}{cmd:)}{col 38}{...}
+add text after the table footer
+ {helpb estout##hlinechar:{ul:hl}inechar}{cmd:(}{it:string}{cmd:)}{col 38}{...}
+specify look of {cmd:@hline}
+ {helpb estout##varlabels:{ul:varl}abels}{cmd:(}{it:matchlist}[{cmd:,} {it:sub.}]{cmd:)} {col 38}{...}
+relabel the parameters
+ {it:subopts}:
+ {cmdab:bl:ist:(}{it:matchlist}{cmd:)}{col 38}{...}
+assign prefixes to certain rows
+ {cmdab:el:ist:(}{it:matchlist}{cmd:)}{col 38}{...}
+assign suffixes to certain rows
+ {it:{help estout##lsub0:label_subopts}}
+ {helpb estout##labcol2:{ul:labcol}2}{cmd:(}{it:strlist}[{cmd:,} {it:subopts}]{cmd:)} {col 38}{...}
+add a second labeling column
+ {it:subopts}:
+ {cmdab:t:itle:(}{it:strlist}{cmd:)}{col 38}{...}
+add column title in table header
+ {cmdab:w:idth:(}{it:#}{cmd:)}{col 38}{...}
+set width of column
+ {helpb estout##refcat:{ul:ref}cat}{cmd:(}{it:matchlist}[{cmd:,} {it:subopts}]{cmd:)} {col 38}{...}
+add reference category information
+ {it:subopts}:
+ {cmdab:l:abel:(}{it:string}{cmd:)} | {cmdab:nol:abel}{col 38}{...}
+redefine the "ref." label
+ {cmdab:b:elow}{col 38}{...}
+change positioning of refcat
+ {helpb estout##mlabels:{ul:ml}abels}{cmd:(}{it:strlist}[{cmd:,} {it:subopts}]{cmd:)}{col 38}{...}
+label the models
+ {it:subopts}:
+ [{cmdab:no:}]{cmdab:dep:vars}{col 38}{...}
+use the name/label of the dependent
+{col 42}variable as model label
+ [{cmdab:no:}]{cmdab:ti:tles}{col 38}{...}
+use estimates title as model label
+ [{cmdab:no:}]{cmdab:num:bers}{col 38}{...}
+number models labels consecutively
+ {it:{help estout##lsub0:label_subopts}}
+ {helpb estout##collabels:{ul:coll}abels}{cmd:(}{it:strlist}[{cmd:,} {col 38}{...}
+label the columns within models
+ {it:{help estout##lsub0:label_subopts}}]{cmd:)}
+ {helpb estout##eqlabels:{ul:eql}abels}{cmd:(}{it:strlist}[{cmd:,} {it:subopts}]{cmd:)}{col 38}{...}
+label the equations
+ {it:subopts}:
+ [{cmdab:no:}]{cmdab:m:erge}{col 38}{...}
+merge equation and parameter labels
+ {it:{help estout##lsub0:label_subopts}}
+ {helpb estout##mgroups:{ul:mgr}oups}{cmd:(}{it:strlist}[{cmd:,} {it:subopts}]{cmd:)}{col 38}{...}
+define and label groups of models
+ {it:subopts}:
+ {cmdab:pat:tern:(}{it:pattern}{cmd:)}{col 38}{...}
+define the grouping of the models
+ {it:{help estout##lsub0:label_subopts}}
+ {helpb estout##numbers:{ul:num}bers}[{cmd:(}{it:l} {it:r}{cmd:)}] | {cmdab:nonum:bers}{col 38}{...}
+add a row containing model numbers
+
+ Output
+ [{cmdab:no:}]{helpb estout##replace:{ul:r}eplace}{col 38}{...}
+overwrite an existing file
+ [{cmdab:no:}]{helpb estout##append:{ul:a}ppend}{col 38}{...}
+append the output to an existing file
+ [{cmdab:no:}]{helpb estout##type:{ul:ty}pe}{col 38}{...}
+print the table in the results window
+ [{cmd:no}]{helpb estout##showtabs:showtabs}{col 38}{...}
+display tabs as {cmd:}s
+ {helpb estout##topfile:{ul:top}file}{cmd:(}{it:filename}{cmd:)}{col 38}{...}
+insert file contents above table
+ {helpb estout##topfile:{ul:bot}tomfile}{cmd:(}{it:filename}{cmd:)}{col 38}{...}
+insert file contents below table
+
+ Defaults
+ {helpb estout##style:{ul:sty}le}{cmd:(}{it:style}{cmd:)}{col 38}{...}
+specify a style for the output table
+
+ {it:styles}:
+ {cmd:smcl}{col 38}SMCL formatted table (screen default)
+ {cmd:tab}{col 38}tab delimited table (export default)
+ {cmd:fixed}{col 38}fixed format table
+ {cmd:tex}{col 38}table for use with LaTeX
+ {cmd:html}{col 38}table for use with HTML
+ {it:mystyle}{col 38}user defined addition
+ {hline 70}
+
+{marker lsub0}
+ {it:{help estout##lsub:label_subopts}}{col 38}Description
+ {hline 70}
+ [{cmd:no}]{cmd:none}{col 38}{...}
+suppress the labels
+ {cmdab:p:refix:(}{it:string}{cmd:)}{col 38}{...}
+add a common prefix
+ {cmdab:s:uffix:(}{it:string}{cmd:)}{col 38}{...}
+add a common suffix
+ {cmdab:b:egin:(}{it:strlist}{cmd:)}{col 38}{...}
+add an overall prefix
+ [{cmdab:no:}]{cmdab:f:irst}{col 38}{...}
+print the first occurrence of {cmd:begin()}
+ {cmdab:e:nd:(}{it:strlist}{cmd:)}{col 38}{...}
+add an overall suffix
+ [{cmdab:no:}]{cmdab:l:ast}{col 38}{...}
+print the last occurrence of {cmd:end()}
+ {cmdab:r:eplace}{col 38}{...}
+replace global {cmd:begin()}/{cmd:end()}
+ [{cmd:no}]{cmd:span}{col 38}{...}
+span columns if appropriate
+ {cmdab:er:epeat:(}{it:string}{cmd:)}{col 38}{...}
+add a "span" suffix
+ {cmd:lhs(}{it:string}{cmd:)}{col 38}{...}
+label the table's left stub
+ {hline 70}
+
+{marker des}
+{title:Description}
+
+{p 4 4 2}
+ {cmd:estout} assembles a table of coefficients, "significance
+ stars", summary statistics, standard errors, t- or z-statistics, p-values,
+ confidence intervals, and other statistics for one or more models
+ previously fitted and stored by {helpb estimates store} or {helpb eststo}.
+ It then displays the table in Stata's results window or writes it to a text
+ file specified by {cmd:using}. The default is to use {help smcl:SMCL}
+ formatting tags and horizontal lines to structure the table. However,
+ if {cmd:using} is specified, a tab-delimited table without lines
+ is produced.
+
+{p 4 4 2}
+ {it:namelist} provides the names of the stored estimation
+ sets to be tabulated. You may use the {cmd:*} and {cmd:?} wildcards in
+ {it:namelist}. The results estimated last may be indicated by a period
+ ({cmd:.}), even if they have not yet been stored. If no model is
+ specified, {cmd:estout} tabulates the estimation sets stored by
+ {cmd:eststo} (see help {helpb eststo}) or, if no such estimates are
+ present, the currently active estimates (i.e. the model fit last).
+ {cmd:estout} may be used after any estimation command that
+ returns its results in {cmd:e()}.
+
+{p 4 4 2}
+ See the {help estout##intro:Introduction} in the
+ {help estout##exa:Examples} section for an introduction on using
+ {cmd:estout}. See help {helpb estimates} for general information
+ about managing estimation results. Furthermore, see help {helpb eststo}
+ for an alternative to the {cmd:estimates store} command.
+
+{p 4 4 2}
+ The default for {cmd:estout} is to produce a plain
+ table containing point estimates. Producing a fully formatted
+ end-product may involve specifying many options. However, note that a
+ simple-to-use {cmd:estout} wrapper producing pre-formatted
+ publication style tables is available as {helpb esttab}. Furthermore,
+ use {helpb estadd} to make additional results available for
+ tabulation (such as the standardized coefficients or the means and
+ standard deviations of the regressors) and {helpb estpost} to
+ tabulate results from non-estimation commands such as {helpb summarize}
+ or {helpb tabulate}.
+
+{p 4 4 2}
+ {cmd:estout} can also be used to tabulate the contents of a Stata
+ matrix (see help {helpb matrix}). Type {cmd:estout marix(}{it:name}{cmd:)},
+ where {it:name} is the name of the matrix, instead of providing a
+ {it:namelist} of stored estimation sets. See the
+ {help estout##ex7:examples} below. Alternatively, you may also specify
+ {cmd:e(}{it:name}{cmd:)} or {cmd:r(}{it:name}{cmd:)} to tabulate an
+ {cmd:e()}-matrix or an {cmd:r()}-matrix. The {cmd:cells()} option is
+ disabled if tabulating a matrix.
+
+{p 4 4 2}
+ Programms similar to {cmd:estout} include {cmd:outreg} by John Luke
+ Gallup, {cmd:outreg2} by Roy Wada, {cmd:modltbl} by John H. Tyler,
+ {cmd:mktab} by Nicholas Winter, {cmd:outtex} by Antoine Terracol, or
+ {cmd:est2tex} by Marc Muendler. Also see Newson (2003) for a very
+ appealing approach.
+
+{marker opt}
+{title:Options}
+
+ Contents
+
+ {help estout##par:Parameter statistics}
+ {help estout##sum:Summary statistics}
+ {help estout##sig:Significance stars}
+ {help estout##lay:Layout}
+ {help estout##lab:Labeling}
+ {help estout##out:Output}
+ {help estout##def:Defaults}
+ {it:{help estout##lsub:label_subopts}}
+ {it:{help estout##msub:matrix_subopts}}
+{marker par}
+{dlgtab:Parameter statistics}
+{marker cells}
+{p 4 8 2}
+ {cmd:cells(}{it:array}{cmd:)} specifies the parameter statistics to be
+ reported and how they are to be arranged. The default is for cells to
+ report point estimates only, i.e. {cmd:cells(b)}. {cmd:cells(none)} may
+ be used to completely suppress the printing of parameter statistics.
+ Alternatively, {cmd:cells(b se)} would result in the reporting of point
+ estimates and standard errors. Multiple statistics are placed in
+ separate rows beneath one another by default. However, elements of
+ {it:array} that are listed in quotes or in parentheses, e.g.
+ {bind:{cmd:"b se"}} or {bind:{cmd:`"b se"'}} or {bind:{cmd:(b se)}},
+ are placed beside one another. For example, {bind:{cmd:cells("b p" se)}}
+ or, equivalently, {bind:{cmd:cells((b p) se)}} would produce a
+ table with point estimates and p-values beside one another in first row
+ and standard errors in the second row beneath the point estimates.
+
+{p 8 8 2}
+ The parameter statistics available are {cmd:b} (point estimates),
+ {cmd:se} (standard errors), {cmd:var} (variance), {cmd:t}
+ (t/z-statistics), {cmd:z} (synonym for {cmd:t}), {cmd:p} (p-values), and
+ {cmd:ci} (confidence
+ intervals; to display the lower and upper bounds in separate cells use
+ {cmd:ci_l} and {cmd:ci_u}). Any additional parameter statistics
+ included in the {cmd:e()}-returns for the models can be tabulated as
+ well. If, for example, {cmd:e(beta)} contains the standardized
+ coefficients, type {cmd:cells(beta)} to tabulate them (use
+ {helpb estadd} to add statistics such as the standardized coefficients to the
+ {cmd:e()}-returns of a model). The syntax {it:name}{cmd:[}{it:#}{cmd:]}
+ or {it:name}{cmd:[}{it:rowname}{cmd:]} can be used to refer to specific
+ rows in {cmd:e(}{it:name}{cmd:)}. For example, type {cmd:cell(ci_bc[1] ci_bc[2])}
+ or {cmd:cell(ci_bc[ll] ci_bc[ul])} to tabulate the lower and upper
+ bounds of the bias-corrected confidence intervals after {helpb bootstrap}.
+ The default is to report the results from the first row.
+ Also see the {cmd:eform} and {cmd:margin} options for more information
+ on the kinds of statistics that can be displayed.
+
+{p 8 8 2}
+ Further available elements in {it:array} are {cmd:_star},
+ {cmd:_sign}, and {cmd:_sigsign}. {cmd:_star} causes stars denoting the
+ significance of the coefficients to be printed (* for p<.05, ** for p<.01,
+ and *** for p<.001; customizable via the {cmd:starlevels()} option below).
+ {cmd:_star} places the significance stars in their own cells. See the
+ {cmd:star} suboption below if you want to attach the stars to another
+ element. {cmd:_sign} prints the signs of the coefficients ("+", "-", or
+ "0"). {cmd:_sigsign}, a combination of {cmd:_star} and {cmd:_sign}, repeats
+ the signs of the coefficients where the number of repetitions reflects the
+ level of significance (non-significant coefficients are left empty;
+ however, you may set the first level to 1 in the {cmd:starlevels()}
+ option).
+
+{p 8 8 2}
+ Finally, {cmd:.} and {cmd:&} may be used in {it:array}. {cmd:.} inserts a
+ "null" element. Use this to add empty cells. For example,
+ {cmd:cells("b p" ". se")} would produce a table with point estimates in the
+ first column and p-values and standard errors beneath one another in the
+ second column. {cmd:&} is used to combine elements in the same cell. Use
+ the {helpb estout##incelldel:incelldelimiter()} option to specify the text to
+ be printed between the combined elements (the default is to print a
+ single blank). For example, in HTML, use {cmd:cell(b & se)} and
+ {cmd:incelldelimiter(
)} to include point estimates and standard
+ errors in a single cell and insert a line break between them.
+
+{p 8 8 2}
+ A set of suboptions may be specified in parentheses for each
+ element named in {it:array} (except for {cmd:.} and {cmd:&}). For example,
+ to add significance stars to the coefficients and place the standard errors
+ in parentheses, specify {bind:{cmd:cells(b(star) se(par))}}. The following
+ suboptions are available. Use:
+ {p_end}
+{marker cstar}
+{p 12 16 2}
+ {cmd:star} to specify that stars denoting the significance of the
+ coefficients be attached to the statistic: {cmd:*} for p<.05,
+ {cmd:**} for p<.01, and {cmd:***} for p<.001. The symbols and the
+ values for the thresholds and the number of levels are fully customizable
+ (see the {help estout##sig:Significance stars} options).
+ {p_end}
+{marker cfmt}
+{p 12 16 2}
+ {cmd:fmt(}{it:{help estout##fmt:fmt}} [{it:{help estout##fmt:fmt}} ...]{cmd:)}
+ to specify the display format(s) of a statistic. It
+ defaults to {cmd:%9.0g} or the format for the first statistic in
+ {cmd:cells()}. If only one format is specified, it is used for all
+ occurrences of the statistic. For example, type
+
+{p 20 20 2}
+ {inp:. estout} {it:...}{inp:, cells("b(fmt(3)) t(fmt(2))")}
+
+{p 16 16 2}
+ to print coefficients and t-values beside one another using three
+ decimal places for coefficients and two decimal places for
+ t-values. If multiple formats are specified, the first format is
+ used for the first regressor in the estimates table, the second
+ format for the second regressor, and so on. The last format is used
+ for the remaining regressors if the number of regressors in the
+ table is greater than the number of specified formats. For
+ instance, type
+
+{p 20 20 2}
+ {inp:. estout} {it:...}{inp:, cells(b(fmt(3 4 2)))}
+
+{p 16 16 2}
+ to use three decimal places for the first coefficient, four decimal
+ places for the second, and two decimal places for all remaining
+ coefficients. Note that, regardless of the display format chosen,
+ leading and trailing blanks are removed from the numbers. White
+ space can be added by specifying a {cmd:modelwidth()} (see the
+ {help estout##lay:Layout} options). {it:{help estout##fmt:fmt}} may
+ be any of Stata's numerical display formats, e.g., {cmd:%9.0g} or
+ {cmd:%8.2f}, an integer {it:#} such as {cmd:1} or {cmd:3} to use a
+ fixed format with {it:#} decimal places, or {cmd:a}{it:#} such as
+ {cmd:a1} or {cmd:a3} to use {cmd:estout}'s adaptive display format
+ (see {help estout##fmt:Numerical formats} in the
+ {help estout##rem:Remarks} section for details).
+ {p_end}
+{marker clabel}
+{p 12 16 2}
+ {cmd:label(}{it:string}{cmd:)} to specify a label to appear in the
+ column heading. The default is the name of the statistic.
+ {p_end}
+{marker cpar}
+{p 12 16 2}
+ {cmd:par}[{cmd:(}{it:l} {it:r}{cmd:)}] to specify that the
+ statistic in question be placed in parentheses. It is also possible
+ to specify custom "parentheses". For example, {cmd:se(par({ }))}
+ would display the standard errors in curly brackets. Or,
+ {cmd:se(par(`"="("' `")""'))} will write parentheses in a way that
+ Excel can recognize. For {cmd:ci} the syntax is:
+
+{p 20 20 2}
+ {cmd:ci(par}[{cmd:(}{it:l} {it:m} {it:r}{cmd:)}]{cmd:)}
+ {p_end}
+{marker cvacant}
+{p 12 16 2}
+ {cmd:vacant(}{it:string}{cmd:)} to print {it:string} if a
+ coefficient is not in the model. The default is to leave such cells
+ empty.
+ {p_end}
+{marker cdrop}
+{p 12 16 2}
+ {cmd:drop(}{it:droplist} [{cmd:, relax}]{cmd:)} to cause certain
+ individual statistics to be dropped. For example, specifying
+ {cmd:t(drop(_cons))} suppresses the t-statistics for the constants.
+ {it:droplist} is specified as in the global
+ {helpb estout##drop:drop()} option (see below).
+ {p_end}
+{marker ckeep}
+{p 12 16 2}
+ {cmd:keep(}{it:keeplist} [{cmd:, relax}]{cmd:)} to cause certain
+ individual statistics to be kept. For example, the specification
+ {cmd:t(keep(mpg))} would display the t-statistics exclusively for
+ the variable {cmd:mpg}. {it:keeplist} is specified analogous to
+ {it:droplist} in {helpb estout##drop:drop()} (see below).
+ {p_end}
+{marker cpattern}
+{p 12 16 2}
+ {cmd:pattern(}{it:pattern}{cmd:)} to designate a pattern of models
+ for which the statistics are to be reported, where the {it:pattern}
+ consists of zeros and ones. A {cmd:1} indicates that the statistic
+ be printed; {cmd:0} indicates that it be suppressed. For example
+ {cmd:beta(pattern(1 0 1))} would result in {cmd:beta} being
+ reported for the first and third models, but not for the second.
+ {p_end}
+{marker cpvalue}
+{p 12 16 2}
+ {cmd:pvalue(}{it:name}{cmd:)} to specify the p-values used to
+ determine the significance stars (see {cmd:star} above). The
+ default is {cmd:pvalue(p)}, indicating that the standard p-values
+ are to be used (i.e. the p-values computed form the coefficients
+ vector and the variance matrix). Alternatively, specify
+ {cmd:pvalue(}{it:mypvalue}{cmd:)}, in which case the significance
+ stars will be determined from the values in
+ {cmd:e(}{it:mypvalue}{cmd:)}. Values outside [0,1] will be ignored.
+ {p_end}
+{marker cabs}
+{p 12 16 2}
+ {cmd:abs} to specify that absolute t-statistics be used instead of
+ regular t-statistics (relevant only if used with {cmd:t()}).
+ {p_end}
+{marker ctranspose}
+{p 12 16 2}
+ {cmd:transpose} to specify that {cmd:e(}{it:myel}{cmd:)} be transposed
+ for tabulation.
+ {p_end}
+{marker drop}
+{p 4 8 2}
+ {cmd:drop(}{it:droplist} [{cmd:, relax}]{cmd:)} identifies the coefficients
+ to be dropped from the table. A {it:droplist} comprises one or more
+ specifications, separated by white space. A specification can be either a
+ parameter name (e.g. {cmd:price}), an equation name followed by a colon
+ (e.g. {cmd:mean:}), or a full name (e.g. {cmd:mean:price}). You may use the
+ {cmd:*} and {cmd:?} wildcards in equation names and parameter names. Be sure
+ to refer to the matched equation names, and not to the original equation names
+ in the models, when using the {cmd:equations()} option to match equations.
+ Specify the {cmd:relax} suboption to allow {it:droplist} to contain elements
+ for which no match can be found.
+ {p_end}
+{marker keep}
+{p 4 8 2}
+ {cmd:keep(}{it:keeplist} [{cmd:, relax}]{cmd:)} selects the coefficients to
+ be included in the table. {it:keeplist} is specified analogous to {it:droplist} in
+ {helpb estout##drop:drop()} (see above). Note that {cmd:keep()} does {it:not} change the
+ the order of the coefficients. Use {cmd:order()} to change the order
+ of coefficients.
+ {p_end}
+{marker order}
+{p 4 8 2}
+ {cmd:order(}{it:orderlist}{cmd:)} changes the order of the
+ coefficients and equations within the table. {it:orderlist} is specified
+ analogous to {it:droplist} in {cmd:drop()} (see above). Reordering of
+ coefficients is performed equation by equation, unless equations are
+ explicitly specified. Coefficients and equations that do not appear in
+ {it:orderlist} are placed last (in their original order). Extra table rows
+ are inserted for elements in {it:orderlist} that are not found in the
+ table.
+ {p_end}
+{marker indicate}
+{p 4 8 2}
+ {cmd:indicate(}{it:groups} [{cmd:,} {cmdab:l:abels(}{it:yes}
+ {it:no}{cmd:)}]{cmd:)} indicates for each model (or, if {cmd:unstack}
+ is specified, for each equation) the presence of certain groups of
+ coefficients at the end of the table body. The syntax for {it:groups}
+ is
+
+ {it:group} [ {it:group} {it:...} ]
+
+{p 8 8 2}
+ where a {it:group} is
+
+ [{it:name} = ] {it:list}
+
+{p 8 8 2}
+ and {it:list} is a list of coefficient specifications as defined in
+ {cmd:drop()} above. The single groups should be enclosed in quotes
+ unless there is only one group and "{it:name} =" is specified. If
+ "{it:name} =" is omitted, the first element of {it:list} is used as
+ name. Note that {it:name} may contain spaces.
+
+{p 8 8 2}
+ For example, if some of the models contain a set of year
+ dummies, say {cmd:y1 y2 y3}, specify
+
+ {com}estout{txt} {it:...}{com}, indicate(year effects = y1 y2 y3){txt}
+
+{p 8 8 2}
+ to drop the dummies from the table and add a "year effects" row
+ containing "Yes" for models in which {it:at least one} of the dummies
+ is present, and "No" for the other models.
+
+{p 8 8 2}
+ Use the {cmd:labels()} suboption to redefine the indication labels to
+ be printed in the table. The default is {cmd:labels(Yes No)}. Use
+ quotes if the labels include spaces,
+ e.g. {bind:{cmd:labels("in model" "not in model")}}.
+ {p_end}
+{marker rename}
+{p 4 8 2}
+ {cmd:rename(}{it:matchlist}{cmd:)} changes the names of individual
+ coefficients, where {it:matchlist} is
+
+{p 12 12 2}
+ {it:oldname} {it:newname} [{it:oldname} {it:newname} ...]
+
+{p 8 8 2}
+ {it:oldname} can be a parameter name (e.g. {cmd:price}) or a full
+ name including an equation specification (e.g. {cmd:mean:price})
+ (abbreviation and wildcards not allowed); {it:newname} is a name without
+ equation specification and must not already occur in a model's equation.
+ {cmd:rename()} is applied before matching the models and equations and can
+ therefore be used to merge different coefficients across models (or
+ equations if {cmd:unstack} is specified) into a single table row. See the
+ {cmd:varlabels()} option if you are interested in relabeling coefficients
+ after matching models and equations.
+ {p_end}
+{marker equations}
+{p 4 8 2}
+ {cmd:equations(}{it:matchlist}{cmd:)} specifies how the models' equations are
+ to be matched. The default is to match all first equations into one equation
+ (named {cmd:main}, if the equations have different names) and match the remaining
+ equations by name. Specify {cmd:equations("")} to match all equations by
+ name. Alternatively, specify {it:matchlist}, which has the syntax
+
+ {it:term} [{cmd:,} {it:term} ... ]
+
+{p 8 8 2}
+ where {it:term} is
+
+ [{it:eqname} {cmd:=}] {it:#}{cmd::}{it:#}...{cmd::}{it:#}{col 50}(syntax 1)
+
+ [{it:eqname} {cmd:=}] {it:#}{col 50}(syntax 2)
+
+{p 8 8 2}
+ In syntax 1, each {it:#} is a number or a period ({cmd:.}). If a number, it
+ specifies the position of the equation in the corresponding model;
+ {cmd:1:3:1} would indicate that equation 1 in the first model matches equation
+ 3 in the second, which matches equation 1 in the third. A period indicates
+ that there is no corresponding equation in the model; {cmd:1:.:1} indicates
+ that equation 1 in the first matches equation 1 in the third.
+
+{p 8 8 2}
+ In syntax 2, you specify just one number, say, {cmd:1} or {cmd:2}, and that
+ is shorthand for {cmd:1:1}...{cmd::1} or {cmd:2:2}...{cmd::2}, meaning that
+ equation 1 matches across all models specified or that equation 2 matches
+ across all models specified.
+
+{p 8 8 2}
+ {it:eqname} is used to name the matched equations. If it is suppressed,
+ a name such as {cmd:#1} or {cmd:#2} etc. is used, depending on the position
+ of the {it:term}. For example, {cmd:equations(1)}
+ indicates that all first equations are to be matched into one equation
+ named {cmd:#1}. All equations not matched by position are
+ matched by name.
+ {p_end}
+{marker eform}
+{p 4 8 2}
+ {cmd:eform}[{cmd:(}{it:pattern}{cmd:)}] displays the coefficient table in
+ exponentiated form. The exponent of {cmd:b} is displayed in lieu of the
+ untransformed coefficient; standard errors and confidence intervals are
+ transformed as well. Specify a {it:pattern} if the exponentiation is to be
+ applied only for certain models. For instance, {cmd:eform(1 0 1)} would
+ transform the statistics for Models 1 and 3, but not for Model 2. Note that,
+ unlike {cmd:regress} and {cmd:estimates table}, {cmd:estout} in
+ eform-mode does not suppress the display of the intercept. To drop the
+ intercept in eform-mode, specify {cmd:drop(_cons)}. Note: {cmd:eform} is
+ implemented via the {cmd:transform()} option. If both options are specified,
+ {cmd:transform()} takes precedence over {cmd:eform}.
+ {p_end}
+{marker transform}
+{p 4 8 2}
+ {cmd:transform(}{it:list} [, {cmd:pattern(}{it:pattern}{cmd:)}]{cmd:)}
+ displays transformed coefficients, standard errors and
+ confidence intervals. {it:list} may be
+
+ {it:fx} {it:dfx}
+
+{p 8 8 2}
+ where {it:fx} is the transformation function and {it:dfx} is its first
+ derivative. {it:fx} is applied to coefficients and confidence
+ intervals, that is, {it:fx}({cmd:b}) and {it:fx}({cmd:ci}) is displayed
+ instead of {cmd:b} and {cmd:ci}. {it:dfx} is used to delta transform
+ standard errors, i.e. {cmd:se}*{it:dfx}({cmd:b}) is displayed instead
+ of {cmd:se}. Use {cmd:@} as a placeholder for the function's argument
+ in {it:fx} and {it:dfx}. For example, type
+
+ {com}estout{txt} {it:...}{com}, transform(exp(@) exp(@)){txt}
+
+{p 8 8 2}
+ to report exponentiated results (this is equivalent to specifying
+ the {cmd:eform} option).
+
+{p 8 8 2}
+ Alternatively, {it:list} may be specified as
+
+{p 12 12 2}
+ {it:coefs} {it:fx} {it:dfx} [ {it:...} [{it:coefs}] {it:fx} {it:dfx} ]
+
+{p 8 8 2}
+ where {it:coefs} identifies the coefficients
+ to be transformed. Syntax for {it:coefs} is as explained above in the
+ description of the {cmd:drop()} option (however, include {it:coefs}
+ in quotes if it contains multiple elements). Say, a model has
+ two equations, {cmd:price} and {cmd:select}, and you want to
+ exponentiate the {cmd:price} equation but not the {cmd:select}
+ equation. You could then type
+
+ {com}estout{txt} {it:...}{com}, transform(price: exp(@) exp(@)){txt}
+
+{p 8 8 2}
+ Note that omitting {it:coef} in the last transformation
+ specification causes the last transformation to be applied to
+ all remaining coefficients.
+
+{p 8 8 2}
+ Specify the {cmd:pattern()} suboption if the transformations are to be
+ applied only for certain models. For instance, {cmd:pattern(1 0 1)} would
+ apply the transformation to Models 1 and 3, but not Model 2.
+ {p_end}
+{marker margin}
+{p 4 8 2}
+ {cmd:margin}[{cmd:(}{cmd:u}|{cmd:c}|{cmd:p}{cmd:)}] indicates that the
+ marginal effects or elasticities be reported instead of the raw
+ coefficients. This option has an effect only if {cmd:mfx} has been
+ applied to a model before its results were stored (see help {helpb mfx}) or if a
+ {cmd:dprobit} (see help {helpb probit}), {cmd:truncreg,marginal}
+ (help {helpb truncreg}), or {cmd:dtobit} (Cong 2000) model is estimated. One
+ of the parameters {cmd:u}, {cmd:c}, or {cmd:p}, corresponding to the
+ unconditional, conditional, and probability marginal effects, respectively,
+ is required for {cmd:dtobit}. Note that the standard errors, confidence
+ intervals, t-statistics, and p-values are transformed as well.
+
+{p 8 8 2}
+ Using the {cmd:margin} option with multiple-equation models can be tricky.
+ The marginal effects of variables that are used in several equations are
+ printed repeatedly for each equation because the equations per se are
+ meaningless for {cmd:mfx}. To display the effects for certain equations only,
+ specify the {cmd:meqs()} option. Alternatively, use the {cmd:keep()} and
+ {cmd:drop()} options to eliminate redundant rows. The {cmd:equations()}
+ option might also be of help here.
+ {p_end}
+{marker discrete}
+{p 4 8 2}
+ {cmd:discrete(}{it:string}{cmd:)} may be used to override the default symbol and
+ explanatory text used to identify dummy variables when reporting marginal
+ effects. The first token in {it:string} is used as the symbol. The default is:
+
+{p 12 12 2}
+ {inp:discrete(" (d)" for discrete change of dummy variable from 0 to 1)}
+
+{p 8 8 2}
+ To display explanatory text, specify either the {cmd:legend} option or use
+ the {cmd:@discrete} variable (see the
+ {help estout##atvar:Remarks on using @-variables}).
+
+{p 8 8 2}
+ Use {cmd:nodiscrete} to disable the identification of dummy variables as
+ such. The default is to indicate the dummy variables unless they have been
+ interpreted as continuous variables in all of the models for which results are
+ reported (for {cmd:dprobit} and {cmd:dtobit}, however, dummy variables will
+ always be listed as discrete variables unless {cmd:nodiscrete} is specified).
+ {p_end}
+{marker meqs}
+{p 4 8 2}
+ {cmd:meqs(}{it:eq_list}{cmd:)} specifies that marginals be printed only for the
+ equations in {it:eq_list}. Specifying this option does not affect how the
+ marginals are calculated. An {it:eq_list} comprises one or more equation
+ names (without colons) separated by white space. If you use the
+ {cmd:equations()} option to match equations, be sure to refer to the matched
+ equation names and not to the original equation names in the models.
+ {p_end}
+{marker dropped}
+{p 4 8 2}
+ {cmd:dropped}[{cmd:(}{it:string}{cmd:)}] causes null coefficients
+ (coefficients for which {cmd:e(b)} and {cmd:e(V)} is zero) to be indicated
+ as dropped. {it:string} specifies the text to be printed in place of
+ the estimates. The default text is "(dropped)".
+ {p_end}
+{marker level}
+{p 4 8 2}
+ {cmd:level(}{it:#}{cmd:)} assigns the confidence level, in percent, for
+ the confidence intervals of the coefficients (see help {help level}).
+
+{marker sum}
+{dlgtab:Summary statistics}
+{marker stats}
+{p 4 8 2}
+ {cmd:stats(}{it:scalarlist}[{cmd:,} {it:stats_subopts}]{cmd:)} specifies
+ one or more scalar statistics - separated by white space - to be displayed
+ at the bottom of the table. The {it:scalarlist} may contain numeric
+ {cmd:e()}-scalars such as, e.g., {cmd:N}, {cmd:r2}, or {cmd:chi2}, but also
+ string {cmd:e()}-macros such as {cmd:cmd} or {cmd:depvar}. In
+ addition, the following statistics are available:
+
+{p 12 24 2}
+ {cmd:aic}{space 5}Akaike's information criterion{p_end}
+{p 12 24 2}
+ {cmd:bic}{space 5}Schwarz's information criterion{p_end}
+{p 12 24 2}
+ {cmd:rank}{space 4}rank of {cmd:e(V)}, i.e. the number of free
+ parameters in model{p_end}
+{p 12 24 2}
+ {cmd:p}{space 7}the p-value of the model (overall model significance)
+
+{p 8 8 2}
+ See {bf:[R] estimates table} for details on the {cmd:aic} and {cmd:bic} statistics.
+ The rules for the determination of {cmd:p} are as follows (note that although
+ the procedure outlined below is appropriate for most models, there might be
+ some models for which it is not):
+
+{p 12 15 2}
+ 1) p-value provided: If the {cmd:e(p)} scalar is provided by the
+ estimation command, it will be interpreted as indicating the p-value
+ of the model.
+
+{p 12 15 2}
+ 2) F test: If {cmd:e(p)} is not provided, {cmd:estout} checks for the
+ presence of the {cmd:e(df_m)}, {cmd:e(df_r)}, and {cmd:e(F)}
+ scalars and, if they are present, the p-value of the model will be
+ calculated as {cmd:Ftail(df_m,df_r,F)}. This p-value corresponds to
+ the standard overall F test of linear regression.
+
+{p 12 15 2}
+ 3) chi2 test: Otherwise, if neither {cmd:e(p)} nor {cmd:e(F)} is
+ provided, {cmd:estout} checks for the presence of {cmd:e(df_m)} and
+ {cmd:e(chi2)} and, if they are present, calculates the p-value as
+ {cmd:chi2tail(df_m,chi2)}. This p-value corresponds to the
+ Likelihood-Ratio or Wald chi2 test.
+
+{p 12 15 2}
+ 4) If neither {cmd:e(p)}, {cmd:e(F)}, nor {cmd:e(chi2)}
+ is available, no p-value will be reported.
+
+{p 8 8 2}
+ Type {cmd:ereturn list} after estimating a model to see a list of
+ the returned {cmd:e()}-scalars and macros (see help {helpb ereturn}). Use
+ the {helpb estadd} command to add extra statistics and
+ other information to the {cmd:e()}-returns.
+
+{p 8 8 2}
+ The following {it:stats_subopts} are available. Use:
+ {p_end}
+{marker statsfmt}
+{p 12 16 2}
+ {cmd:fmt(}{it:{help estout##fmt:fmt}} [{it:{help estout##fmt:fmt}} {it:...}]{cmd:)}
+ to set the display formats for the scalars statistics in {it:scalarlist}.
+ {it:{help estout##fmt:fmt}} may be any of Stata's numerical display
+ formats, e.g., {cmd:%9.0g} or {cmd:%8.2f}, an integer {it:#} such as
+ {cmd:1} or {cmd:3} to use a fixed format with {it:#} decimal places, or
+ {cmd:a}{it:#} such as {cmd:a1} or {cmd:a3} to use {cmd:estout}'s adaptive
+ display format (see {help estout##fmt:Numerical formats} in the {help
+ estout##rem:Remarks} section for details). For example, {cmd:fmt(3 0)}
+ would be suitable for {cmd:stats(r2_a N)}. Note that the last specified
+ format is used for the remaining scalars if the list of scalars is longer
+ than the list of formats. Thus, only one format needs to be specified if
+ all scalars are to be displayed in the same format. If no format is
+ specified, the default format is the display format of the coefficients.
+ {p_end}
+{marker statslabels}
+{p 12 16 2}
+ {cmd:labels(}{it:strlist}[{cmd:,} {it:{help estout##lsub:label_subopts}}]{cmd:)}
+ to specify labels for rows containing the scalar statistics. If
+ specified, the labels are used instead of the scalar names. For example:
+
+{p 20 20 2}
+ {inp:. estout} {it:...}{inp:, stats(r2_a N, labels("Adj. R-Square" "Number of Cases"))}
+
+{p 16 16 2}
+ Note that names like {cmd:r2_a} produce an error in LaTeX because the
+ underscore character has a special meaning in LaTeX (to print the
+ underscore in LaTeX, type {cmd:\_}). Use the {cmd:label()} suboption to
+ rename such statistics, e.g. {cmd:stats(r2_a, labels(r2\_a))}. An alternative
+ approach is to use {cmd:estout}'s {cmd:substitute()} option (see the
+ {help estout##lay:Layout} options).
+ {p_end}
+{marker statsstar}
+{p 12 16 2}
+ {cmd:star}[{cmd:(}{it:scalarlist}{cmd:)}] to specify that the overall
+ significance of the model be denoted by stars. The stars are attached to
+ the scalar statistics specified in {it:scalarlist}. If
+ {it:scalarlist} is omitted, the stars are attached to the first
+ reported scalar statistic. The printing of the stars is suppressed in
+ empty results cells (i.e. if the scalar statistic in question is missing
+ for a certain model). The determination of the model significance is
+ based on the p-value of the model (see above).
+
+{p 16 16 2}
+ Hint: It is possible to attach the stars to different scalar statistics
+ within the same table. For example, specify
+ {cmd:stats(,star(r2_a r2_p))}
+ when tabulating OLS estimates and, say, probit estimates. For
+ the OLS models, the F test will be carried out and the significance
+ stars will be attached to the {cmd:r2_a}; for the probit models, the
+ chi2 test will be used and the stars will appear next to the
+ {cmd:r2_p}.
+ {p_end}
+{marker statslayout}
+{p 12 16 2}
+ {cmd:layout(}{it:array}{cmd:)} to rearrange the summary statistics. The default
+ is to print the statistics in separate rows beneath one another (in
+ each model's first column). The syntax for {it:array} is
+
+ <{it:row}> [ <{it:row}> ... ]
+
+{p 16 16 2}
+ where {it:row} is
+
+ <{it:cell}> [ <{it:cell}> ... ]
+
+{p 16 16 2}
+ and {cmd:@} is used as a placeholder for the statistics, one
+ after another. Rows and cells that contain blanks
+ have to be embraced in quotes. For example,
+
+ {com} ... stats(chi2 df_m N, layout("@ @" @)){txt}
+
+{p 16 16 2}
+ prints for each model in row 1/column 1 the chi-squared, in
+ row1/column 2 the degrees of freedom, and in row 2/column 1 the number of
+ observations. Cells may contain multiple statistics and text other than
+ the placeholder symbol is printed as is (provided the cells' statistics are part
+ of the model). For example,
+
+ {com} ... stats(chi2 df_m N, layout(`""@ (@)""' @)){txt}
+
+{p 16 16 2}
+ prints a cell containing "chi2 (df_m)" in the first row and the
+ number of observations in the second row. Note that the number of columns
+ in the table only depends on the {cmd:cells()} option (see above) and not
+ on the {cmd:layout()} suboption. If, for example, the table has two columns
+ per model and you specify three columns of summary statistics, the summary statistics
+ in the third column are not printed.
+ {p_end}
+{marker statspchar}
+{p 12 16 2}
+ {cmd:pchar(}{it:symbol}{cmd:)} to specify the placeholder symbol
+ used in {cmdab:layout()}. The default placeholder is {cmd:@}.
+
+{marker sig}
+{dlgtab:Significance stars}
+{marker starlevels}
+{p 4 8 2}
+ {cmd:starlevels(}{it:levelslist}{cmd:)} overrides the default thresholds and
+ symbols for "significance stars". For instance,
+ {bind:{cmd:starlevels(+ 0.10 * 0.05)}}
+ sets the following thresholds: {cmd:+} for p<.10 and {cmd:*} for
+ p<.05. Note that the thresholds must lie in the (0,1] interval and must be
+ specified in descending order. To, for example, denote insignificant
+ results, type {bind:{cmd:starlevels(* 1 "" 0.05)}}.
+ {p_end}
+{marker stardrop}
+{p 4 8 2}
+ {cmd:stardrop(}{it:droplist} [{cmd:, relax}]{cmd:)}
+ identifies the coefficients for which the significance stars be
+ suppressed. {it:droplist} is specified as in
+ {helpb estout##drop:drop()} (see above).
+ {p_end}
+{marker starkeep}
+{p 4 8 2}
+ {cmd:starkeep(}{it:keeplist} [{cmd:, relax}]{cmd:)} selects the coefficients
+ for which the significance stars, if requested, be printed. {it:keeplist}
+ is specified analogous to {it:droplist} in
+ {helpb estout##drop:drop()} (see above).
+ {p_end}
+{marker stardetach}
+{p 4 8 2}
+ {cmd:stardetach} specifies that a delimiter be placed between the statistics
+ and the significance stars (i.e. that the stars are to be displayed in their
+ own column).
+
+{marker lay}
+{dlgtab:Layout}
+{marker varwidth}
+{p 4 8 2}
+ {cmd:varwidth(}{it:#}{cmd:)} specifies the number of characters used to display
+ the names (labels) of regressors and statistics (i.e. {cmd:varwidth}
+ specifies the width of the table's left stub). Long names (labels) are
+ abbreviated (depending on the {cmd:abbrev} option) and short or empty
+ cells are padded out with blanks to fit the width specified by the user.
+ {cmd:varwidth} set to 0 means that the names are not
+ abbreviated and no white space is added. Specifying low values may cause
+ misalignment.
+ {p_end}
+{marker modelwidth}
+{p 4 8 2}
+ {cmd:modelwidth(}{it:#} [{it:#} ...]{cmd:)} designates the number of characters
+ used to display the results columns. If a non-zero {cmd:modelwidth} is
+ specified, model names are abbreviated if necessary (depending on the
+ {cmd:abbrev} option) and short or empty results cells are padded out
+ with blanks. In contrast, {cmd:modelwidth} does not shorten or truncate
+ the display of the results themselves (coefficients, t-statistics,
+ summary statistics, etc.) although it may add blanks if needed.
+ {cmd:modelwidth} set to 0 means that the model names are not
+ abbreviated and no white space is added. Specifying low values may
+ cause misalignment. Specify a list of numbers in {cmd:modelwidth()} to
+ assign individual widths to the different results columns (the list is
+ recycled if there are more columns than numbers).
+
+{p 8 8 2}
+ The purpose of {cmd:modelwidth} is to be able to construct a fixed-format
+ table and thus make the raw table more readable. Be aware, however, that the
+ added blanks may cause problems with the conversion to a table in word
+ processors or spreadsheets.
+ {p_end}
+{marker unstack}
+{p 4 8 2}
+ {cmd:unstack} specifies that the individual equations from multiple-equation
+ models (e.g. {cmd:mlogit}, {cmd:reg3}, {cmd:heckman}) be placed in
+ separate columns. The default is to place the equations below one another in a
+ single column. Summary statistics will be reported for each equation if
+ {cmd:unstack} is specified and the estimation command is either {cmd:reg3},
+ {cmd:sureg}, or {cmd:mvreg} (see help {helpb reg3}, help {helpb sureg},
+ help {helpb mvreg}).
+ {p_end}
+{marker begin}
+{p 4 8 2}
+ {cmd:begin(}{it:string}{cmd:)} specifies a string to be printed at the
+ beginning of every table row. It is possible to
+ use special functions such as {cmd:_tab} or {cmd:_skip} in
+ {cmd:begin()}. For more information on using such functions, see the
+ description of the functions in help {helpb file}.
+ {p_end}
+{marker delimiter}
+{p 4 8 2}
+ {cmd:delimiter(}{it:string}{cmd:)} designates the delimiter used between the
+ table columns. See the {cmd:begin} option above for further details.
+ {p_end}
+{marker end}
+{p 4 8 2}
+ {cmd:end(}{it:string}{cmd:)} specifies a string to be printed at the end of
+ every table row. See the {cmd:begin} option above for further details.
+ {p_end}
+{marker incelldel}
+{p 4 8 2}
+ {cmd:incelldelimiter(}{it:string}{cmd:)} specifies text to be printed
+ between parameter statistics that have been combined in a single cell
+ by the {cmd:&} operator. See the {helpb estout##par:cells()} option
+ for details. The default string is a single blank.
+ {p_end}
+{marker dmarker}
+{p 4 8 2}
+ {cmd:dmarker(}{it:string}{cmd:)} specifies the form of the decimal marker. The
+ standard decimal symbol (a period or a comma, depending on the input provided
+ to {cmd:set dp}; see help {help format}) is replaced by {it:string}.
+ {p_end}
+{marker msign}
+{p 4 8 2}
+ {cmd:msign(}{it:string}{cmd:)} determines the form of the minus sign. The
+ standard minus sign ({cmd:-}) is replaced by {it:string}.
+ {p_end}
+{marker lz}
+{p 4 8 2}
+ {cmd:lz} specifies that the leading zero of fixed format numbers in the
+ interval (-1,1) be printed. This is the default. Use {cmd:nolz} to advise
+ {cmd:estout} to omit the leading zeros (that is, to print numbers like
+ {cmd:0.021} or {cmd:-0.33} as {cmd:.021} and {cmd:-.33}).
+ {p_end}
+{marker extracols}
+{p 4 8 2}
+ {cmd:extracols(}{it:{help numlist}}{cmd:)} inserts empty table columns
+ at the indicated positions. For example, {cmd:extracols(1)} adds
+ an extra column between the left stub of the table and the first
+ column.
+ {p_end}
+{marker substitute}
+{p 4 8 2}
+ {cmd:substitute(}{it:subst_list}{cmd:)} specifies that the substitutions
+ specified in {it:subst_list} be applied to the estimates table after it has
+ been created. Specify {it:subst_list} as a list of substitution pairs, that
+ is:
+
+{p 12 12 2}
+ {it:from} {it:to} [{it:from} {it:to} ...]
+
+{p 8 8 2}
+ For example, specify {cmd:substitute(_ \_)} to replace the underscore
+ character (as in {cmd:_cons} or {cmd:F_p}) with it's LaTeX equivalent {cmd:\_}.
+
+{marker lab}
+{dlgtab:Labeling}
+{marker label}
+{p 4 8 2}
+ {cmd:label} specifies that variable labels be displayed instead of variable
+ names in the left stub of the table.
+ {p_end}
+{marker abbrev}
+{p 4 8 2}
+ {cmd:abbrev} specifies that long names and labels be abbreviated if
+ a {cmd:modelwidth()} and/or a {cmd:varwidth()} is specified.
+ {p_end}
+{marker wrap}
+{p 4 8 2}
+ {cmd:wrap} causes long variable labels to be wrapped if space permits and
+ a {cmd:varwidth()} is specified. The {cmd:wrap} option is only useful if
+ several parameter statistics are printed beneath one another and, therefore,
+ white space is available beneath the labels.
+ {p_end}
+{marker title}
+{p 4 8 2}
+ {cmd:title(}{it:string}{cmd:)} may be used to specify a title for the table.
+ The {it:string} is printed at the top of the table unless {cmd:prehead()},
+ {cmd:posthead()}, {cmd:prefoot()}, or {cmd:postfoot()} is specified. In
+ the latter case, the variable {cmd:@title} can be used to insert the title.
+ {p_end}
+{marker note}
+{p 4 8 2}
+ {cmd:note(}{it:string}{cmd:)} may be used to specify a note for the table.
+ The {it:string} is printed at the bottom, of the table unless {cmd:prehead()},
+ {cmd:posthead()}, {cmd:prefoot()}, or {cmd:postfoot()} is specified. In
+ the latter case, the variable {cmd:@note} can be used to insert the note.
+ {p_end}
+{marker legend}
+{p 4 8 2}
+ {cmd:legend} adds a legend explaining the significance symbols and
+ thresholds.
+ {p_end}
+{marker prehead}
+{p 4 8 2}
+ {cmd:prehead(}{it:strlist}{cmd:)}, {cmd:posthead(}{it:strlist}{cmd:)},
+ {cmd:prefoot(}{it:strlist}{cmd:)}, and {cmd:postfoot(}{it:strlist}{cmd:)} may
+ be used to define lists of text lines to appear before and after the table
+ heading or the table footer. For example, the specification
+
+{p 12 12 2}
+ {inp:. estout} {it:...}{inp:, prehead("\S_DATE \S_TIME" "")}
+
+{p 8 8 2}
+ would add a line containing the current date and time followed by
+ an empty line before the table. Various substitution functions can be used
+ as part of the text lines specified in {it:strlist} (see the
+ {help estout##atvar:Remarks on using @-variables}). For example,
+ {cmd:@hline} plots a horizontal "line" (series of dashes, by default; see
+ the {cmd:hlinechar()} option) or {cmd:@M} inserts the number of models
+ in the table. {cmd:@M} could be used in a LaTeX table heading
+ as follows:
+
+{p 12 12 2}
+ {inp:. estout} {it:...}{inp:, prehead(\begin{tabular}{l*{@M}{r}})}
+ {p_end}
+{marker hlinechar}
+{p 4 8 2}
+ {cmd:hlinechar(}{it:string}{cmd:)} specifies the character(s) to be
+ used in {cmd:@hline}. The default is {cmd:hlinechar(-)}, resulting in a
+ dashed line. To produce a solid line, specify {cmd:hlinechar(`=char(151)')}
+ (Windows only; other systems may use other codes).
+ {p_end}
+{marker varlabels}
+{p 4 8 2}
+ {cmd:varlabels(}{it:matchlist}[{cmd:,} {it:suboptions}]{cmd:)} may be used to
+ relabel the regressors from the models, where {it:matchlist} is
+
+{p 12 12 2}
+ {it:name} {it:label} [{it:name} {it:label} ...]
+
+{p 8 8 2}
+ A {it:name} is a parameter name (e.g. {cmd:price}) or a full name
+ (e.g. {cmd:mean:price}) (abbreviation and wildcards
+ not allowed). For example, specify {cmd:varlabels(_cons Constant)} to replace
+ each occurrence of {cmd:_cons} with {cmd:Constant}. (Note that, in LaTeX,
+ the underscore character produces an error unless it is specified as
+ {cmd:\_}. Thus, names such as {cmd:_cons} should always be changed if
+ the estimates table is to be used with LaTeX. The {cmd:substitute()} may also be
+ helpful; see the {help estout##lay:Layout} options.) The {it:suboptions} are:
+
+{p 12 16 2}
+ {cmd:blist(}{it:matchlist}{cmd:)} to assign specific prefixes to
+ certain rows in the table body. Specify the {it:matchlist} as pairs of
+ regressors and prefixes, that is:
+
+{p 20 20 2}
+ {it:name} {it:prefix} [{it:name} {it:prefix} ...]
+
+{p 16 16 2}
+ A {it:name} is a parameter name (e.g. {cmd:price}), an equation name
+ followed by a colon (e.g. {cmd:mean:}), or a full name
+ (e.g. {cmd:mean:price}) (abbreviation and wildcards
+ not allowed). Note that equation names cannot be used if the
+ {cmd:unstack} option is specified.
+
+{p 12 16 2}
+ {cmd:elist(}{it:matchlist}{cmd:)} to assign specific suffixes to
+ certain rows in the table body (see the analogous {cmd:blist()} option
+ above). This option may, for example, be useful for separating
+ thematic blocks of variables by
+ adding vertical space at the end of each block. A LaTeX example:
+
+{p 20 20 2}
+ {inp:. estout} {it:...}{inp:, varlabels(,elist(price \addlinespace mpg \addlinespace))}
+
+{p 16 16 2}
+ (the macro {cmd:\addlinespace} is provided by the
+ {cmd:booktabs} package in LaTeX)
+
+{p 12 16 2}
+ {it:{help estout##lsub:label_subopts}}, which are
+ explained in their own section.
+ {p_end}
+{marker labcol2}
+{p 4 8 2}
+ {cmd:labcol2(}{it:strlist}[{cmd:,} {it:suboptions}]{cmd:)} adds a second column
+ containing additional labels for the coefficients and summary statistics. Labels
+ containing spaces should be embraced in double quotes ({bind:{cmd:"}{it:label 1}{cmd:"}}
+ {bind:{cmd:"}{it:label 2}{cmd:"}} etc.). An example would be to add a column
+ indicating the hypothesized directions of effects, e.g.,
+
+ {com}. estout {txt}{it:...}{com}, labcol2(+ - +/- + 0){txt}
+
+{p 8 8 2}
+ The {it:suboptions} are:
+
+{p 12 16 2}
+ {cmd:title(}{it:strlist}{cmd:)} to add text in the table header above
+ the column. Use double quotes to break the title into several
+ rows (given there are multiple header rows), i.e. specify {it:strlist}
+ as {bind:{cmd:"}{it:line 1}{cmd:"}} {bind:{cmd:"}{it:line 2}{cmd:"}} etc.
+
+{p 12 16 2}
+ {cmd:width(}{it:#}{cmd:)} to set the width, in number of characters, of the
+ column. The default is the value of {cmd:modelwidth()}.
+ {p_end}
+{marker refcat}
+{p 4 8 2}
+ {cmd:refcat(}{it:matchlist}[{cmd:,} {it:suboptions}]{cmd:)} may be used to
+ insert a row containing information on the reference category
+ of a categorical variable in the model. {it:matchlist} is
+
+{p 12 12 2}
+ {it:name} {it:refcat} [{it:name} {it:refcat} ...]
+
+{p 8 8 2}
+ A {it:name} is a parameter name (e.g. {cmd:_Irep78_2})
+ (abbreviation and wildcards not allowed). For
+ example, assume that you include the categorical variable {cmd:rep78}
+ ("Repair Record 1978" from the auto dataset) in some of your models
+ using {cmd:xi} (see help {helpb xi}). Since {cmd:rep78} has five
+ levels, 1 through 5, {cmd:xi} will create 4 dummy variables,
+ {cmd:_Irep78_2} through {cmd:_Irep78_5}. You can now type
+
+{p 12 12 2}
+ {inp:. estout} {it:...}{inp:, refcat(_Irep78_2 _Irep78_1)}
+
+{p 8 8 2}
+ to add a table row containing "_Irep78_1" in the left stub and
+ "ref." in each column in which the {cmd:_Irep78_2}
+ dummy appears. The {it:suboptions} are:
+
+{p 12 16 2}
+ {cmd:label(}{it:string}{cmd:)} to specify the label that is printed
+ in the table columns. The default is {cmd:label(ref.)}. Type {cmd:nolabel}
+ to suppress the default label.
+
+{p 12 16 2}
+ {cmd:below} to position the reference category row below the specified
+ coefficient's row. The default is above. For example, if the 5th
+ category of {cmd:rep78} is used as reference category, i.e. if
+ {cmd:_Irep78_1} through {cmd:_Irep78_4} are included in the models,
+ you might want to type {cmd:refcat(_Irep78_4 _Irep78_5, below)}.
+ {p_end}
+{marker mlabels}
+{p 4 8 2}
+ {cmd:mlabels(}{it:strlist}[{cmd:,} {it:suboptions}]{cmd:)} determines the
+ model captions printed in the table heading. The default is to use the names of
+ the stored estimation sets (or their titles, if the {cmd:label} option is
+ specified and titles are available). The {it:suboptions} for use with
+ {cmd:mlabels} are:
+
+{p 12 16 2}
+ {cmd:depvars} to specify that the name (or label) of the (first) dependent
+ variable of the model be used as model label.
+
+{p 12 16 2}
+ {cmd:titles} to specify that, if available, the title of the stored
+ estimation set be used as the model label. Note that the {cmd:label} option
+ implies {cmd:titles} (unless {cmd:notitles} is specified). {cmd:depvars}
+ takes precedence over {cmd:titles}.
+
+{p 12 16 2}
+ {cmd:numbers} to cause the model labels to be numbered consecutively.
+
+{p 12 16 2}
+ {it:{help estout##lsub:label_subopts}}, which are explained in their own section.
+ {p_end}
+{marker collabels}
+{p 4 8 2}
+ {cmd:collabels(}{it:strlist}[{cmd:,} {it:{help estout##lsub:label_subopts}}]{cmd:)}
+ specifies labels for the columns within models or equations. The
+ default is to compose a label from the names or labels of the
+ statistics printed in the cells of that column. The {it:label_subopts}
+ are explained in their own section below.
+ {p_end}
+{marker eqlabels}
+{p 4 8 2}
+ {cmd:eqlabels(}{it:strlist}[{cmd:,} {it:suboptions}]{cmd:)}
+ labels the equations. The default is to use the equation names as
+ stored by the estimation command, or to use the variable labels if the
+ equation names correspond to individual variables and the {cmd:label}
+ option is specified. The {it:suboptions} for use with {cmd:eqlabels}
+ are:
+
+{p 12 16 2}
+ {cmd:merge} to merge equation labels and parameter labels instead of
+ printing equation labels in separate rows. Equation and parameter labels
+ will be separated by ":" unless another delimiter is specified via the
+ {cmd:suffix()} suboption (see {it:{help estout##lsub:label_subopts}}).
+ {cmd:merge} has no effect if {cmd:unstack} is specified.
+
+{p 12 16 2}
+ {it:{help estout##lsub:label_subopts}}, which are explained in their own
+ section. Note that {bind:{cmd:eqlabels(none)}} causes {cmd:_cons} to be
+ replaced with the equation name or label, if {cmd:_cons} is the only
+ parameter in an equation. This is useful, e.g., for tabulating
+ {cmd:ologit} or {cmd:oprobit} results in Stata 9. Specify
+ {bind:{cmd:eqlabels("", none)}} to not replace {cmd:_cons}.
+ {p_end}
+{marker mgroups}
+{p 4 8 2}
+ {cmd:mgroups(}{it:strlist}[{cmd:,} {it:suboptions}]{cmd:)} may be used to
+ labels groups of (consecutive) models at the top of the table heading. The
+ labels are placed in the first physical column of the output for the group of
+ models to which they apply. The {it:suboptions} for use with {cmd:mgroups}
+ are:
+
+{p 12 16 2}
+ {cmd:pattern(}{it:pattern}{cmd:)} to establish how the models are to be grouped.
+ {it:pattern} should be a list of zeros and ones, with ones indicating the
+ start of a new group of models. For example,
+
+{p 20 20 2}
+ {inp:. estout} {it:...}{inp:, mgroups("Group 1" "Group 2", pattern(1 0 0 1 0))}
+
+{p 16 16 2}
+ would group Models 1, 2, and 3 together and then groups Models 4 and 5
+ together as well. Note that the first group will always start with the first
+ model regardless of whether the first token of {it:pattern} is a one or a
+ zero.
+
+{p 12 16 2}
+ {it:{help estout##lsub:label_subopts}}, which are explained
+ in their own section. In
+ particular, the {cmd:span} suboption might be of interest here.
+ {p_end}
+{marker numbers}
+{p 4 8 2}
+ {cmd:numbers}[{cmd:(}{it:l} {it:r}{cmd:)}] adds a row to the table header
+ displaying consecutive model numbers. The default is to
+ enclose the numbers in parentheses, i.e. {cmd:(1)}, {cmd:(2)}, etc.
+ Alternatively, specify {it:l} and {it:r} to change the tokens on the
+ left and right of each number. For example, {cmd:numbers("" ")")}
+ would result in {cmd:1)}, {cmd:2)}, etc.
+
+{marker out}
+{dlgtab:Output}
+{marker replace}
+{p 4 8 2}
+ {cmd:replace} permits {cmd:estout} to overwrite an existing file.
+ {p_end}
+{marker append}
+{p 4 8 2}
+ {cmd:append} specifies that the output be appended to an existing file. It
+ may be used even if the file does not yet exist.
+ {p_end}
+{marker type}
+{p 4 8 2}
+ {cmd:type} specifies that the assembled estimates table be printed in the
+ results window and the log file. This is the default unless {cmd:using} is
+ specified. Use {cmd:notype} to suppress the display of the table.
+ {p_end}
+{marker showtabs}
+{p 4 8 2}
+ {cmd:showtabs} requests that tabs be displayed as {cmd:}s in both the
+ results window and the log file instead of in expanded form. This option does
+ not affect how tabs are written to the text file specified by {cmd:using}.
+ {p_end}
+{marker topfile}
+{p 4 8 2}
+ {cmd:topfile(}{it:filename}{cmd:)} and
+ {cmd:bottomfile(}{it:filename}{cmd:)} may be used to insert text before
+ and after the table, where the text is imported from a file on disk. Note that
+ {cmd:substitute()} does not apply to text inserted by {cmd:topfile()} or
+ {cmdab:bottomfile()}.
+
+{marker def}
+{dlgtab:Defaults}
+{marker style}
+{p 4 8 2}
+ {cmd:style(}{it:style}{cmd:)} specifies a "style" for the output
+ table. {cmdab:def:aults:(}{it:style}{cmd:)} is a synonym for
+ {cmd:style(}{it:style}{cmd:)}. A "style" is a named combination of options
+ that is saved in an auxiliary file called {cmd:estout_}{it:style}{cmd:.def}.
+ In addition, there are five internal styles called {cmd:smcl}
+ (default for screen display), {cmd:tab} (export default), {cmd:fixed},
+ {cmd:tex}, and {cmd:html}. The {cmd:smcl} style is suitable for displaying
+ the table in Stata's results window and is the default unless
+ {cmd:using} is specified. It includes {help smcl:SMCL} formatting tags and
+ horizontal lines to structure the table. The particulars of the other styles are:
+
+ settings {col 38}styles
+ {col 26}{cmd:tab}{col 34}{cmd:fixed}{col 42}{cmd:tex}{col 50}{cmd:html}
+ {hline 47}
+ {cmd:begin} {col 50}{cmd:}
+ {cmd:delimiter} {col 26}{cmd:_tab}{col 34}{cmd:" "}{col 42}{cmd:&}{col 50}{cmd: | }
+ {cmd:end} {col 42}{cmd:\\}{col 50}{cmd: |
}
+ {cmd:varwidth} {col 26}{cmd:0}{col 34}{cmd:12/20}*{col 42}{cmd:12/20}*{col 50}{cmd:12/20}*
+ {cmd:modelwidth}{col 26}{cmd:0}{col 34}{cmd:12}{col 42}{cmd:12}{col 50}{cmd:12}
+ {cmd:abbrev} {col 26}off{col 34}on{col 42}off{col 50}off
+ (* if {cmd:label} is on)
+
+{p 8 8 2}
+ {cmd:tab} is the default export style (i.e. if {cmd:using} is specified).
+
+{p 8 8 2}
+ Note that explicitly specified options take precedence
+ over settings provided by a style. For example, if you type
+
+ {com}. estout, delimiter("") style(tab){txt}
+
+{p 8 8 2}
+ then the column delimiter will be set to empty string since the
+ {cmd:delimiter()} option overwrites the default from the {cmd:tab}
+ style. Similarly, specifying
+ {cmd:noabbrev} will turn abbreviation off if using the {cmd:fixed}
+ style.
+
+{p 8 8 2}
+ See {help estout##defaults:Defaults files} in the
+ {help estout##rem:Remarks} section to make available your own style.
+
+{marker lsub}
+{it:{dlgtab:label_subopts}}
+
+{p 4 4 2}
+The following suboptions may be used within the {cmd:mgroups()},
+{cmd:mlabels()}, {cmd:collabels()}, {cmd:eqlabels()},
+{cmd:varlabels()}, and {cmd:stats(, labels())} options:
+
+{p 4 8 2}
+ {cmd:none} suppresses the printing of the labels or drops the
+ part of the table heading to which it applies. Note that instead of
+ typing {bind:{it:option}{cmd:(, none)}} you may simply specify
+ {it:option}{cmd:(none)}.
+
+{p 4 8 2}
+ {cmd:prefix(}{it:string}{cmd:)} specifies a common prefix to be added to each
+ label.
+
+{p 4 8 2}
+ {cmd:suffix(}{it:string}{cmd:)} specifies a common suffix to be added to each
+ label.
+
+{p 4 8 2}
+ {cmd:begin(}{it:strlist}{cmd:)} specifies a prefix to be printed at the
+ beginning of the part of the table to which it applies. If {cmd:begin} is
+ specified in {cmd:varlabels()} or {cmd:stats(,labels())}, the prefix will
+ be repeated for each regressor or summary statistic.
+
+{p 4 8 2}
+ {cmd:first} specifies that the first occurrence of the {cmd:begin()}-prefix in
+ {cmd:varlabels()} or {cmd:stats(,labels())} be printed. This
+ is the default. Use {cmd:nofirst} to suppress the first occurrence of the
+ prefix. In {cmd:varlabels()}, {cmd:nofirst} applies equation-wise, i.e., the first
+ {cmd:begin()}-prefix in each equation is suppressed (unless {cmd:unstack} is
+ specified).
+
+{p 4 8 2}
+ {cmd:end(}{it:strlist}{cmd:)} specifies a suffix to be printed at the end of the
+ part of the table to which it applies. If {cmd:end} is specified in
+ {cmd:varlabels()} or {cmd:stats(,labels())}, the suffix will be repeated
+ for each regressor or summary statistic.
+
+{p 4 8 2}
+ {cmd:last} specifies that the last occurrence of the {cmd:end()}-suffix in
+ {cmd:varlabels()} or {cmd:stats(,labels())} be printed. This
+ is the default. Use {cmd:nolast} to suppress the last occurrence of the
+ suffix. In {cmd:varlabels()}, {cmd:nolast} applies equation-wise, i.e., the last
+ {cmd:end()}-suffix in each equation is suppressed (unless {cmd:unstack} is
+ specified).
+
+{p 4 8 2}
+ {cmd:replace} causes the label suboption {cmd:begin()}-prefix and {cmd:end()}-suffix
+ to be used instead of the global {cmd:begin()} and {cmd:end()} strings. The default
+ is to print both. {cmd:replace} also applies to {cmd:blist()} and {cmd:elist()}
+ if specified in {cmd:varlabels()}.
+
+{p 4 8 2}
+ {cmd:span} causes labels to span columns, i.e. extends the labels across
+ several columns, if appropriate. This suboption is relevant only for the
+ {cmd:mgroups()}, {cmd:mlabels()}, {cmd:eqlabels()}, and
+ {cmd:collabels()} options. The {cmd:@span} string returns the number of
+ spanned columns if it is included in the label, prefix, or suffix. A LaTeX example:
+
+{p 8 8 2}
+ {inp:. estout} {it:...}{inp:, mlabels(, span prefix(\multicolumn{@span}{c}{) suffix(}))}
+
+{p 4 8 2}
+ {cmd:erepeat(}{it:string}{cmd:)} specifies a string that is repeated for each
+ group of spanned columns at the very end of the row if the {cmd:span}
+ suboption is specified. This suboption is relevant only for the
+ {cmd:mgroups()}, {cmd:mlabels()}, {cmd:eqlabels()}, and
+ {cmd:collabels()} options. If the {cmd:@span} string is included in
+ {it:string} it will be replaced by the range of columns spanned. A LaTeX example:
+
+{p 8 8 2}
+ {inp:. estout} {it:...}{inp:, mlabels(, span erepeat(\cline{@span}))}
+
+{p 4 8 2}
+ {cmd:lhs(}{it:string}{cmd:)} inserts {it:string} into the otherwise empty cell
+ in the left stub of the row of the table heading to which it applies. This
+ suboption is relevant only for the {cmd:mgroups()}, {cmd:mlabels()},
+ {cmd:eqlabels()}, and {cmd:collabels()} options.
+
+{marker msub}
+{it:{dlgtab:matrix_subopts}}
+
+{p 4 4 2}
+The following suboptions may be applied within the {cmd:matrix()},
+{cmd:e()}, or {cmd:r()} argument used to tabulate a matrix:
+ {p_end}
+{marker mfmt}
+{p 4 8 2}
+ {cmd:fmt(}{it:fmtlist}{cmd:)} sets the display formats for the matrix.
+ {it:fmtlist} contains a list of format specifications, one for each
+ column of the matrix. {it:fmtlist} is recycled if it supplies less
+ specifications than there are columns in the matrix. A format
+ specification may be a single {it:{help estout##fmt:fmt}} such as,
+ e.g., {cmd:%9.0g} or {cmd:a3} (see {help estout##fmt:Numerical formats}
+ in the {help estout##rem:Remarks} section for details) to be applied to
+ all cells in the column. Alternatively, a format specification may be
+ a list of {it:{help estout##fmt:fmt}}s, enclosed in double quotes, to be
+ used for the cells in the column one by one. The last format in the
+ list is used for the remaining cells if the number of cells in the
+ column is greater than the number of formats in the list. Also see the
+ {help estout##ex7:examples} below.
+ {p_end}
+{marker mtranspose}
+{p 4 8 2}
+ {cmd:transpose} causes the matrix to be transposed for tabulation.
+
+{marker exa}
+{title:Examples}
+
+ Contents
+ {help estout##intro:Introduction}
+ {help estout##ex1:Publication style table}
+ {help estout##ex2:t-statistics for selected variables only}
+ {help estout##ex3:Summary statistics only}
+ {help estout##ex4:Table of descriptives}
+ {help estout##ex5:Unstack multiple equations}
+ {help estout##ex6:Marginal effects}
+ {help estout##ex7:Tabulating a matrix}
+
+{p 4 4 2} Please first read the {help estout##intro:Introduction}. The
+other examples are more advanced and intended for users
+already familiar with the basic features of
+{cmd:estout}. Additional examples can be found in Jann (2005) and at
+{browse "http://repec.org/bocode/e/estout"}.
+
+{marker intro}
+{dlgtab:Introduction}
+
+{p 4 4 2}
+The full syntax of {cmd:estout} is rather complex and is to be found
+above. However, consider the following basic syntax, which
+includes only the most important options:
+
+{p 8 15 2}
+{cmd:estout} [ {it:namelist} ] [ {cmd:using} {it:filename} ] [ {cmd:,}
+ {cmdab:c:ells:(}{it:array}{cmd:)}
+ {cmdab:s:tats:(}{it:scalarlist}{cmd:)}
+ {cmdab:sty:le:(}{it:style}{cmd:)}
+ {it:more_options}
+ ]
+
+{p 4 4 2}
+where {it:namelist} is a list of the names of stored estimation sets (the name
+list can be entered as {cmd:*} to refer to all stored estimates). The
+{cmd:cells()} and {cmd:stats()} options determine the primary contents of
+the table. The {cmd:style()} option determines the basic formatting of the
+table.
+
+{p 4 4 2}{ul:Basic usage}
+
+{p 4 4 2}
+The general procedure for using {cmd:estout} is to first store several
+models using the {cmd:estimates store} or the {helpb eststo} command and then apply
+{cmd:estout} to display or save a table of the estimates. By default,
+{cmd:estout} displays a plain table of the coefficients of the models and
+uses {help SMCL} tags and horizontal lines to structure the table:
+
+ {com}. sysuse auto
+ {txt}(1978 Automobile Data)
+
+ {com}. replace price = price / 1000
+ {txt}price was {res}int{txt} now {res}float
+ {txt}(74 real changes made)
+
+ {com}. replace weight = weight / 1000
+ {txt}weight was {res}int{txt} now {res}float
+ {txt}(74 real changes made)
+
+ {com}. quietly regress price weight mpg
+ {txt}
+ {com}. estimates store m1, title(Model 1)
+ {txt}
+ {com}. generate forXmpg = foreign * mpg
+ {txt}
+ {com}. quietly regress price weight mpg forXmpg foreign
+ {txt}
+ {com}. estimates store m2, title(Model 2)
+ {txt}
+ {com}. estout m1 m2
+ {res}
+ {txt}{hline 38}
+ {txt} m1 m2
+ {txt} b b
+ {txt}{hline 38}
+ {txt}weight {res} 1.746559 4.613589{txt}
+ {txt}mpg {res} -.0495122 .2631875{txt}
+ {txt}forXmpg {res} -.3072165{txt}
+ {txt}foreign {res} 11.24033{txt}
+ {txt}_cons {res} 1.946068 -14.44958{txt}
+ {txt}{hline 38}
+
+{p 4 4 2}Alternatively, if {cmd:using} is specified, {cmd:estout} writes a
+raw tab-delimited table (without SMCL tags and without lines) to the
+indicated file ({cmd:*} is used in the following example to indicate that
+all stored models be tabulated):
+
+ {com}. estout * using example.txt
+ {txt}(output written to {browse `"example.txt"'})
+
+ {com}. type example.txt
+ {res} m1 m2
+ b b
+ weight 1.746559 4.613589
+ mpg -.0495122 .2631875
+ forXmpg -.3072165
+ foreign 11.24033
+ _cons 1.946068 -14.44958
+ {txt}
+{p 4 4 2} The table looks messy in the Stata results window or the Stata
+log because the columns are tab-separated (note that tab characters are not
+preserved in the results window or the log). However, the table would look
+tidy if "example.txt" were opened, for example, in a spreadsheet program.
+
+{p 4 4 2}{ul:Choosing a style}
+
+{p 4 4 2}{cmd:estout} has a {cmd:style()} option to set the basic format of
+the table. The default style for screen display is the {cmd:smcl} style.
+The default export style (i.e. if {cmd:using} is specified) is the
+{cmd:tab} style. (See the examples above.) Other predefined styles are
+{cmd:fixed}, {cmd:tex}, and {cmd:html}, but it is also possible to define
+one's own styles (see {help estout##defaults:Defaults files} in the
+{help estout##rem:Remarks} section). The {cmd:tex} style, for example, modifies
+the output table for use with LaTeX's tabular environment:
+
+ {com}. estout *, style(tex) varlabels(_cons \_cons)
+ {res}
+ & m1& m2\\
+ & b& b\\
+ weight & 1.746559& 4.613589\\
+ mpg & -.0495122& .2631875\\
+ forXmpg & & -.3072165\\
+ foreign & & 11.24033\\
+ \_cons & 1.946068& -14.44958\\
+ {txt}
+{p 4 4 2}
+Note that {cmd:_cons} has been replaced by its LaTeX equivalent in the example above
+using the {cmd:varlabels()} option (the underscore character produces an
+error in LaTeX unless it is preceded by a backslash). For more
+information on the {cmd:varlabels()} option, see {cmd:estout}'s
+{help estout##lab:Labeling} options.
+
+{p 4 4 2}{ul:The cells option}
+
+{p 4 4 2}
+Use the {cmd:cells()} option to specify the parameter statistics to be
+tabulated and how they are to be arranged. The parameter statistics
+available are {cmd:b} (point estimates; the default), {cmd:se} (standard
+errors), {cmd:t} (t-/z-statistics), {cmd:p} (p-values), {cmd:ci}
+(confidence intervals; to display the lower and upper bounds in separate
+cells use {cmd:ci_l} and {cmd:ci_u}), as well as any additional
+parameter statistics included in the {cmd:e()}-returns for the models
+(see {cmd:estout}'s {help estout##par:Parameter Statistics} options). For
+example, {cmd:cells(b se)} results
+in the reporting of point estimates and standard errors:
+
+ {com}. estout *, cells(b se)
+ {res}
+ {txt}{hline 38}
+ {txt} m1 m2
+ {txt} b/se b/se
+ {txt}{hline 38}
+ {txt}weight {res} 1.746559 4.613589{txt}
+ {res} .6413538 .7254961{txt}
+ {txt}mpg {res} -.0495122 .2631875{txt}
+ {res} .086156 .1107961{txt}
+ {txt}forXmpg {res} -.3072165{txt}
+ {res} .1085307{txt}
+ {txt}foreign {res} 11.24033{txt}
+ {res} 2.751681{txt}
+ {txt}_cons {res} 1.946068 -14.44958{txt}
+ {res} 3.59705 4.42572{txt}
+ {txt}{hline 38}
+
+{p 4 4 2}
+Multiple statistics are placed in separate rows beneath one another by
+default as in the example above. However, elements that are listed in
+quotes or in parentheses are placed beside one another. For
+example, specifying {bind:{cmd:cells("b se t p")}} or, equivalently,
+{bind:{cmd:cells((b se t p))}} produces the following table:
+
+ {com}. estout m2, cells("b se t p")
+ {res}
+ {txt}{hline 64}
+ {txt} m2
+ {txt} b se t p
+ {txt}{hline 64}
+ {txt}weight {res} 4.613589 .7254961 6.359219 1.89e-08{txt}
+ {txt}mpg {res} .2631875 .1107961 2.375421 .0203122{txt}
+ {txt}forXmpg {res} -.3072165 .1085307 -2.830687 .0060799{txt}
+ {txt}foreign {res} 11.24033 2.751681 4.084896 .0001171{txt}
+ {txt}_cons {res} -14.44958 4.42572 -3.26491 .0017061{txt}
+ {txt}{hline 64}
+
+{p 4 4 2}
+The two approaches can be combined. For example, {cmd:cells("b p" se)}
+would produce a table with point estimates and standard errors beneath one
+another in the first column and p-values in the top row of the second
+column for each model.
+
+{p 4 4 2}
+Note that for each statistic named in the {cmd:cells()} option a set of
+suboptions may be specified in parentheses. For example, in social sciences
+it is common to report standard errors or t-statistics in parentheses beneath
+the coefficients and to indicate the significance of individual
+coefficients with stars. Furthermore, the results are rounded. Just such a
+table can be created using the following procedure:
+
+ {com}. estout *, cells(b(star fmt(3)) t(par fmt(2)))
+ {res}
+ {txt}{hline 44}
+ {txt} m1 m2
+ {txt} b/t b/t
+ {txt}{hline 44}
+ {txt}weight {res} 1.747** 4.614***{txt}
+ {res} (2.72) (6.36) {txt}
+ {txt}mpg {res} -0.050 0.263* {txt}
+ {res} (-0.57) (2.38) {txt}
+ {txt}forXmpg {res} -0.307** {txt}
+ {res} (-2.83) {txt}
+ {txt}foreign {res} 11.240***{txt}
+ {res} (4.08) {txt}
+ {txt}_cons {res} 1.946 -14.450** {txt}
+ {res} (0.54) (-3.26) {txt}
+ {txt}{hline 44}
+
+{p 4 4 2}
+The {cmd:estout} default is to display {cmd:*} for p<.05,
+{cmd:**} for p<.01, and {cmd:***} for p<.001. However, note that
+the significance thresholds and symbols are fully customizable (see {cmd:estout}'s
+{help estout##sig:Significance stars} options).
+
+{p 4 4 2}{ul:The stats option}
+
+{p 4 4 2}
+Finally, use the {cmd:stats()} option to specify scalar
+statistics to be displayed for each model in the table footer. The
+available scalar statistics are {cmd:aic} (Akaike's information criterion),
+{cmd:bic} (Schwarz's information criterion), {cmd:rank} (the rank of
+{cmd:e(V)}, i.e. the number of free parameters in model), {cmd:p} (the
+p-value of the model), as well as any numeric or string scalars contained in the
+{cmd:e()}-returns for the models (see
+{cmd:estout}'s
+{help estout##sum:Summary statistics} options). For example, specify
+{cmd:stats(r2 bic N)} to add the R-squared, BIC, and the number of cases:
+
+ {com}. estout *, stats(r2 bic N)
+ {res}
+ {txt}{hline 38}
+ {txt} m1 m2
+ {txt} b b
+ {txt}{hline 38}
+ {txt}weight {res} 1.746559 4.613589{txt}
+ {txt}mpg {res} -.0495122 .2631875{txt}
+ {txt}forXmpg {res} -.3072165{txt}
+ {txt}foreign {res} 11.24033{txt}
+ {txt}_cons {res} 1.946068 -14.44958{txt}
+ {txt}{hline 38}
+ {txt}r2 {res} .2933891 .5516277{txt}
+ {txt}bic {res} 356.2918 331.2406{txt}
+ {txt}N {res} 74 74{txt}
+ {txt}{hline 38}
+{marker ex1}
+{dlgtab:Publication style table}
+
+ {com}. label variable foreign "Foreign car type"
+ {txt}
+ {com}. label variable forXmpg "Foreign*Mileage"
+ {txt}
+ {com}. estout *, cells(b(star fmt(%9.3f)) se(par)) ///
+ > stats(r2_a N, fmt(%9.3f %9.0g) labels(R-squared)) ///
+ > legend label collabels(none) varlabels(_cons Constant)
+ {res}
+ {txt}{hline 52}
+ {txt} Model 1 Model 2
+ {txt}{hline 52}
+ {txt}Weight (lbs.) {res} 1.747** 4.614***{txt}
+ {res} (0.641) (0.725) {txt}
+ {txt}Mileage (mpg) {res} -0.050 0.263* {txt}
+ {res} (0.086) (0.111) {txt}
+ {txt}Foreign*Mileage {res} -0.307** {txt}
+ {res} (0.109) {txt}
+ {txt}Foreign car type {res} 11.240***{txt}
+ {res} (2.752) {txt}
+ {txt}Constant {res} 1.946 -14.450** {txt}
+ {res} (3.597) (4.426) {txt}
+ {txt}{hline 52}
+ {txt}R-squared {res} 0.273 0.526 {txt}
+ {txt}N {res} 74 74 {txt}
+ {txt}{hline 52}
+ {txt}* p<0.05, ** p<0.01, *** p<0.001
+{marker ex2}
+{dlgtab:t-statistics for selected variables only}
+
+ {com}. estout *, cells(b(star) t(par keep(mpg)))
+ {res}
+ {txt}{hline 44}
+ {txt} m1 m2
+ {txt} b/t b/t
+ {txt}{hline 44}
+ {txt}weight {res} 1.746559** 4.613589***{txt}
+ {txt}mpg {res} -.0495122 .2631875* {txt}
+ {res} (-.5746806) (2.375421) {txt}
+ {txt}forXmpg {res} -.3072165** {txt}
+ {txt}foreign {res} 11.24033***{txt}
+ {txt}_cons {res} 1.946068 -14.44958** {txt}
+ {txt}{hline 44}
+{marker ex3}
+{dlgtab:Summary statistics only}
+
+ {com}. estout *, cells(none) stats(r2_a bic N, star)
+ {res}
+ {txt}{hline 44}
+ {txt} m1 m2
+ {txt}{hline 44}
+ {txt}r2_a {res} .2734846*** .5256351***{txt}
+ {txt}bic {res} 356.2918 331.2406 {txt}
+ {txt}N {res} 74 74 {txt}
+ {txt}{hline 44}
+{marker ex4}
+{dlgtab:Table of descriptives}
+
+ {com}. quietly generate x = uniform()
+ {txt}
+ {com}. quietly regress x price weight mpg foreign
+ {txt}
+ {com}. estadd mean
+
+ {txt}added matrix:
+ e(mean) : {res}1 x 5
+ {txt}
+ {com}. estadd sd, nobinary
+
+ {txt}added matrix:
+ e(sd) : {res}1 x 5
+ {txt}
+ {com}. estout, cells("mean sd") stats(N) mlabels(,none) drop(_cons)
+ {res}
+ {txt}{hline 38}
+ {txt} mean sd
+ {txt}{hline 38}
+ {txt}price {res} 6.165257 2.949496{txt}
+ {txt}weight {res} 3.019459 .7771936{txt}
+ {txt}mpg {res} 21.2973 5.785503{txt}
+ {txt}foreign {res} .2972973 {txt}
+ {txt}{hline 38}
+ {txt}N {res} 74 {txt}
+ {txt}{hline 38}
+{marker ex5}
+{dlgtab:Unstack multiple equations}
+
+ {com}. quietly sureg (price foreign weight length) ///
+ > (mpg displ = foreign weight)
+ {txt}
+ {com}. estout, cells(b t(par)) stats(r2 chi2 p) unstack
+ {res}
+ {txt}{hline 51}
+ {txt} price mpg displacement
+ {txt} b/t b/t b/t
+ {txt}{hline 51}
+ {txt}foreign {res} 3.57526 -1.650029 -25.6127{txt}
+ {res} (5.749891) (-1.565555) (-2.047999){txt}
+ {txt}weight {res} 5.691462 -6.587886 96.75485{txt}
+ {res} (6.182983) (-10.55641) (13.06594){txt}
+ {txt}length {res} -.0882711 {txt}
+ {res} (-2.809689) {txt}
+ {txt}_cons {res} 4.506212 41.6797 -87.23547{txt}
+ {res} (1.255897) (19.64914) (-3.46585){txt}
+ {txt}{hline 51}
+ {txt}r2 {res} .548808 .6627029 .8115213{txt}
+ {txt}chi2 {res} 89.73586 145.3912 318.6174{txt}
+ {txt}p {res} 2.50e-19 2.68e-32 6.50e-70{txt}
+ {txt}{hline 51}
+{marker ex6}
+{dlgtab:Marginal effects}
+
+ {com}. generate record = 0
+ {txt}
+ {com}. replace record = 1 if rep > 3
+ {txt}(34 real changes made)
+
+ {com}. eststo raw: quietly logit foreign mpg record
+ {txt}
+ {com}. eststo mfx: quietly mfx
+ {txt}
+ {com}. estout raw mfx, cells("b Xmfx_X(pattern(0 1))" se(par)) margin legend
+ {res}
+ {txt}{hline 51}
+ {txt} raw mfx
+ {txt} b/se b/se Xmfx_X
+ {txt}{hline 51}
+ {txt}mpg {res} .1079219 .0184528 21.2973{txt}
+ {res} (.0565077) (.0101674) {txt}
+ {txt}record (d) {res} 2.435068 .4271707 .4594595{txt}
+ {res} (.7128444) (.1043178) {txt}
+ {txt}_cons {res} -4.689347 {txt}
+ {res} (1.326547) {txt}
+ {txt}{hline 51}
+ {txt}(d) for discrete change of dummy variable from 0 to 1
+{marker ex7}
+{dlgtab:Tabulating a matrix}
+
+{p 4 4 2}
+ Use {cmd:estout matrix(}{it:matname}{cmd:)} to tabulate Stata matrix
+ {it:matname}. Example:
+
+ {com}. set seed 123
+ {txt}
+ {com}. matrix A = matuniform(3,2)
+ {txt}
+ {com}. matrix list A
+
+ {txt}A[3,2]
+ c1 c2
+ r1 {res}.91204397 .0075452
+ {txt}r2 {res}.28085881 .46027868
+ {txt}r3 {res}.56010592 .67319061
+ {txt}
+ {com}. estout matrix(A)
+ {res}
+ {txt}{hline 38}
+ {txt} A
+ {txt} c1 c2
+ {txt}{hline 38}
+ {txt}r1 {res} .912044 .0075452{txt}
+ {txt}r2 {res} .2808588 .4602787{txt}
+ {txt}r3 {res} .5601059 .6731906{txt}
+ {txt}{hline 38}
+
+{p 4 4 2}
+ Numeric formats for the columns can be set using the {cmd:fmt()}
+ suboption:
+
+ {com}. estout matrix(A, fmt(2 3))
+ {res}
+ {txt}{hline 38}
+ {txt} A
+ {txt} c1 c2
+ {txt}{hline 38}
+ {txt}r1 {res} 0.91 0.008{txt}
+ {txt}r2 {res} 0.28 0.460{txt}
+ {txt}r3 {res} 0.56 0.673{txt}
+ {txt}{hline 38}
+
+{p 4 4 2}
+ A list of formats can be specified for each column:
+
+ {com}. estout matrix(A, fmt("2 3 4" "4 3 2"))
+ {res}
+ {txt}{hline 38}
+ {txt} A
+ {txt} c1 c2
+ {txt}{hline 38}
+ {txt}r1 {res} 0.91 0.0075{txt}
+ {txt}r2 {res} 0.281 0.460{txt}
+ {txt}r3 {res} 0.5601 0.67{txt}
+ {txt}{hline 38}
+{marker rem}
+{title:Remarks}
+
+ Contents
+
+ {help estout##fmt:Numerical formats}
+ {help estout##spchar:Special characters}
+ {help estout##atvar:Using @-variables}
+ {help estout##defaults:Defaults files}
+{marker fmt}
+{dlgtab:Numerical formats}
+
+{p 4 4 2}
+Numerical display formats may be specified in {cmd:estout}
+as follows:
+
+{p 5 8 2}
+1. Official Stata's display formats: You may specify formats, such as
+{cmd:%9.0g} or {cmd:%8.2f}. See help {help format} for a list
+of available formats. {cmd:%g} or {cmd:g} may be used as a
+synonym for {cmd:%9.0g}.
+
+{p 5 8 2}
+2. Fixed format: You may specify an integer value such as {cmd:0},
+{cmd:1}, {cmd:2}, etc. to request a display format with a fixed number
+of decimal places. For example, {cmd:cells(t(fmt(3)))} would display
+t-statistics with three decimal places.
+
+{p 5 8 2}
+3. Automatic format: You may specify {cmd:a1}, {cmd:a2}, ..., or
+{cmd:a9} to cause {cmd:esttab} to choose a reasonable display format for
+each number depending on the number's value. {cmd:a} may be used as a
+synonym for {cmd:a3}. The {it:#} in
+{cmd:a}{it:#} determines the minimum precision according to the
+following rules:
+
+{p 10 12 2}
+o Absolute numbers smaller than 1 are displayed with {it:#}
+significant decimal places (i.e. with {it:#} decimal places ignoring
+any leading zeros after the decimal point). For example,
+{cmd:0.00123456} is displayed as {cmd:0.00123} if the format is
+{cmd:a3}.
+
+{p 10 12 2}
+o Absolute numbers greater than 1 are displayed with as many digits
+required to retain at least one decimal place and are displayed with
+a minimum of ({it:#} + 1) digits. For example, if the format is
+{cmd:a3}, {cmd:1.23456} is displayed as {cmd:1.235}, {cmd:12.3456} is
+displayed as {cmd:12.35}, and {cmd:1234.56} is displayed as
+{cmd:1234.6}.
+
+{p 10 12 2}
+o In any case, integers are displayed with zero decimal places, and
+very large or very small absolute numbers are displayed in
+exponential format.
+
+{marker spchar}
+{dlgtab:Special characters}
+
+{p 4 4 2}
+The {cmd:\} and {cmd:$} characters and quotation marks have
+special meanings in Stata. You should therefore consider the following
+instructions if you, for example, intend to specify akward delimiters or
+specify special characters in labels:
+
+{p 6 8 2}- Strings containing unmatched quotes should be enclosed in compound double
+quotes (thus, {cmd:delimiter(`"""')} results in columns
+delimited by {cmd:"}, while {cmd:delimiter(")} produces an error).
+
+{p 6 8 2}- The backslash character is used to delay macro expansion in
+Stata. Specifying {cmd:\\} in Stata 8 just results in the printing of {cmd:\}. To get
+a double backslash in Stata 8 (the {cmd:\newline} command in TeX), type {cmd:\\\}.
+
+{p 6 8 2}- The dollar sign is used for global macro expansion in Stata. Thus,
+{cmd:$x} would result in the display of the contents of global macro
+{cmd:x} (or nothing, if the macro is empty). Therefore, use
+{cmd:\$} to produce {cmd:$} in the output. For math mode in LaTeX I
+recommend using {cmd:\(}...{cmd:\)} instead of {cmd:$}...{cmd:$}.
+
+{p 4 4 2}
+Stata's {cmd:char()} function may also be used to specify odd characters
+(see help {help strfun}). In particular, {cmd:"`=char(9)'"}
+results in a tab character and {cmd:"`=char(13)'"} results
+in a carriage return. For example, {bind:{cmd:delimiter(" `=char(9)' ")}}
+specifies that a tab character with a leading and
+a trailing blank be used as delimiter.
+
+{p 4 4 2} {it:Tip:} It is sometimes very useful to set the format of all cells in a
+spreadsheet to "Text" before pasting the estimates table. This prevents the
+spreadsheet program from trying to interpret the cells and ensures that the contents
+of the table remain unchanged.
+
+{marker atvar}
+{dlgtab:Using @-variables}
+
+{p 4 4 2}
+{cmd:estout} features several variables that can be used within string
+specifications. The following list provides an overview of these variables.
+
+{p 5 8 2}o{space 2}In {cmd:prehead()}, {cmd:posthead()}, {cmd:prefoot()},
+ and {cmd:postfoot()}, in the {cmd:begin()} and {cmd:end()} label
+ suboptions, and in the {cmd:blist()} and {cmd:elist()} suboptions
+ in {cmd:varlabels()}:
+
+{p 12 16 2}{cmd:@span} to return the value of a count variable for the total number of physical
+ columns of the table.
+
+{p 12 16 2}{cmd:@M} to return the number of models in the table.
+
+{p 12 16 2}{cmd:@E} to return the total number columns containing separate equations.
+
+{p 12 16 2}{cmd:@width} to return the total width of the table (number of characters).
+
+{p 12 16 2}{cmd:@hline} to return a horizontal line (series of dashes, by default;
+ see the {cmd:hlinechar()} option).
+
+{p 5 8 2}o{space 2}In {cmd:prehead()}, {cmd:posthead()}, {cmd:prefoot()},
+ and {cmd:postfoot()}:
+
+{p 12 16 2}{cmd:@title} to return the title specified with the {cmd:title()} option.
+
+{p 12 16 2}{cmd:@note} to return the note specified with the {cmd:note()} option.
+
+{p 12 16 2}{cmd:@discrete} to return the explanations provided by the
+ {cmd:discrete()} option (provided that the {cmd:margin} option is activated).
+
+{p 12 16 2}{cmd:@starlegend} to return a legend explaining the significance symbols.
+
+{p 5 8 2}o{space 2}In the {cmd:prefix()} and {cmd:suffix()} suboptions of {cmd:mgroups()},
+ {cmd:mlabels()}, {cmd:eqlabels()}, and
+ {cmd:collabels()}, and in the labels specified in these options:
+
+{p 12 16 2}{cmd:@span} to return the number of spanned columns.
+
+{p 5 8 2}o{space 2}In the {cmd:erepeat()} suboption of
+ {cmd:mgroups()}, {cmd:mlabels()}, {cmd:eqlabels()}, and
+ {cmd:collabels()}:
+
+{p 12 16 2}{cmd:@span} to return the range of spanned columns (e.g. {cmd:2-4} if columns 2, 3 and 4
+ are spanned).
+
+{marker defaults}
+{dlgtab:Defaults files}
+
+{p 4 4 2}{ul:Creating new defaults files:}
+
+{p 4 4 2}
+To make available an own set
+of default options, proceed as follows:
+
+{p 8 11 2}
+1. Download "estout_mystyle.def" from the SSC
+Archive (click
+{stata "copy http://fmwww.bc.edu/repec/bocode/e/estout_mystyle.def estout_mystyle.def, text":here}
+to copy the file from SSC and store it in the working directory).
+
+{p 8 11 2}
+2. Open "estout_mystyle.def" in a text editor and make the desired modifications
+(click {stata "doedit estout_mystyle.def":here} to open "estout_mystyle.def" in Stata's Do-File
+Editor).
+
+{p 8 11 2}
+3. Save the file in the current directory or elsewhere
+in the ado-file path as {cmd:estout_}{it:newstyle}{cmd:.def} (see help {help sysdir}).
+
+{p 4 4 2}To use the new options set in {cmd:estout}, then type:
+
+ {inp:. estout} {it:...} {inp:, style(}{it:newstyle}{inp:)}
+
+
+{p 4 4 2}{ul:Defaults files syntax:}
+
+{p 4 4 2}
+{cmd:estout} has two main types of options, which are treated differentially
+in defaults files. On the one hand, there are simple on/off options without
+arguments, like {cmd:legend} or {cmd:showtabs}. To turn such an option on,
+enter the option followed by the options name as an argument, i.e. add the line
+
+ {it:option} {it:option}
+
+{p 4 4 2}
+to the defaults file. For example,
+
+ {inp:legend legend}
+
+{p 4 4 2}
+specifies that a legend be printed in the table footer. Otherwise, if you want
+to turn the option of, just delete or comment out the line that contains it (or
+specify {it:option} without an argument).
+
+{p 4 4 2}
+To temporarily turn off an option that has been activated in a defaults file,
+specify {cmd:no}{it:option} in the command line (do not, however, use
+{cmd:no}{it:option} in defaults files). For example, if the legend has been
+turned on in the defaults file, but you want to suppress it in a specific call of
+{cmd:estout}, type
+
+ {inp:. estout} {it:...}{inp:, nolegend}
+
+{p 4 4 2}
+On the other hand, there are options that take arguments, such as
+{cmd:prehead(}{it:args}{cmd:)}, {cmd:delimiter(}{it:args}{cmd:)}, or
+{cmd:stats(}{it:args}{cmd:,} {it:...}{cmd:)}. Such options are specified as
+
+ {it:option} {it:args}
+
+{p 4 4 2}
+in the defaults file (where {it:args} must not include suboptions; see
+below). Specifying an option in the command line overwrites the settings from
+the defaults file. However, note that a {cmd:no} form, which exists for the
+first options type, is not available here.
+
+{p 4 4 2}
+Last but not least, there are two options that reflect a combination of the first
+and second types: {cmd:eform}[{cmd:(}{it:args}{cmd:)}] and
+{cmd:margin}[{cmd:(}{it:args}{cmd:)}]. These options can be specified
+as either
+
+ {it:option} {it:option}
+
+{p 4 4 2}
+or
+
+ {it:option} {it:args}
+
+{p 4 4 2}
+in the defaults file; the {cmd:no} form is allowed.
+
+{p 4 4 2}
+Many {cmd:estout} options have suboptions, i.e., an option might take the
+form {it:option}{cmd:(}{it:...}{cmd:,} {it:suboption}{cmd:)} or
+{it:option}{cmd:(}{it:...}{cmd:,} {it:suboption}{cmd:(}{it:args}{cmd:))}. In
+the defaults file, the suboptions cannot be included in the
+definition of a higher-level option. Instead, they must be
+specified in their own lines, as either
+
+ {it:optionsuboption} {it:suboption}
+
+{p 4 4 2}
+or
+
+ {it:optionsuboption} {it:args}
+
+{p 4 4 2}
+In the case of a two-level nesting of options, the name
+used to refer to the suboption is a concatenation of the option's name and the
+suboption's name,
+i.e. {cmd:"}{it:optionsuboption}{cmd:"="}{it:option}{cmd:"+"}{it:suboption}{cmd:"}. For
+example, the {cmd:labels()} suboption of the {cmd:stats()} option would be
+set by the term {cmd:statslabels}. Analogously, the three level nesting in
+the {cmd:stats()} option yields suboption names composed of three names. For
+instance, the suboption called by the command
+
+ {inp:. estout} {it:...}{inp:, stats(}{it:...}{inp:, labels(}{it:...}{inp:, prefix(}{it:args}{inp:)))}
+
+{p 4 4 2}
+would be referred to as
+
+ {inp:statslabelsprefix} {it:args}
+
+{p 4 4 2}
+in the defaults file. The {cmd:cells()} option represents an exception to
+this rule. It may be defined in the defaults file using
+only a plain array of cells elements without suboptions, e.g.
+
+ {inp:cells "b se" p}
+
+{p 4 4 2}
+However, the suboptions of the cells elements may be referred to as
+{it:el_suboption}, for example
+
+ {inp:b_star star}
+
+{p 4 4 2}
+or
+
+ {inp:se_par [ ]}
+
+
+{p 4 4 2}{ul:Comments in defaults files:}
+
+{p 4 4 2}
+Be aware that the support for comments in defaults files is limited. In
+particular, the {cmd:/*} and {cmd:*/} comment indicators cannot be used.
+The other comment indicators work (more or less) as usual, that is:
+
+{p 5 8 2}
+ o{space 2}Empty lines and lines beginning with {cmd:*} (with or without preceding
+blanks) will be ignored.
+
+{p 5 8 2}
+ o{space 2}{cmd://} preceded by one or more blanks indicates that the rest of the
+line should be ignored. Lines beginning with {cmd://} (with or without preceding
+blanks) will be ignored.
+
+{p 5 8 2}
+ o{space 2}{cmd:///} preceded by one or more blanks indicates that the rest of the
+line should be ignored and the part of the line preceding it should be added to
+the next line. In other words, {cmd:///} can be used to split commands into
+two or more lines of code.
+
+{marker ret}
+{title:Saved results}
+
+{p 4 4 2}
+{cmd:estout} saves the following in {cmd:r()}:
+
+{p 4 4 2}Scalars
+ {p_end}
+{p 6 20 2}{cmd:r(nmodels)}{space 4}number of models
+ {p_end}
+{p 6 20 2}{cmd:r(ccols)}{space 6}number of columns per model in {cmd:r(coefs)}
+ {p_end}
+
+{p 4 4 2}Macros
+ {p_end}
+{p 6 20 2}{cmd:r(cmdline)}{space 4}command as typed
+ {p_end}
+{p 6 20 2}{cmd:r(names)}{space 6}names of models
+ {p_end}
+{p 6 20 2}{cmd:r(m}{it:#}{cmd:_}{it:name}{cmd:)}{space 4}model-specific
+macros where {it:#} is the model number and {it:name} is macro name
+ {p_end}
+
+{p 4 4 2}Matrices
+ {p_end}
+{p 6 20 2}{cmd:r(coefs)}{space 6}coefficients
+ {p_end}
+{p 6 20 2}{cmd:r(stats)}{space 6}summary statistics
+ {p_end}
+
+{marker ref}
+{title:References}
+
+{p 4 8 2}Cong, R. (2000). sg144: Marginal effects of the tobit model.
+{it:Stata Technical Bulletin} 56: 27-34.
+
+{p 4 8 2}Jann, B. (2005). Making regression tables from stored estimates.
+{it:The Stata Journal} 5(3): 288-308.
+
+{p 4 8 2}Jann, B. (2007). Making regression tables simplified.
+{it:The Stata Journal} 7(2): 227-244.
+
+{p 4 8 2}Newson, R. (2003). Confidence intervals and p-values for delivery to the end
+user. {it:The Stata Journal} 3(3): 245-269.
+
+{marker ack}
+{title:Acknowledgements}
+
+{p 4 4 2}I would like to thank numerous people
+for their comments and suggestions. Among them
+are
+Joao Pedro Azevedo,
+Kit Baum,
+Elisabeth Coutts,
+Henriette Engelhardt,
+Jonathan Gardnerand,
+Simone Hirschvogl,
+Daniel Hoechle,
+Friedrich Huebler,
+Maren Kandulla,
+J. Scott Long,
+David Newhouse,
+Clive Nicholas,
+Fredrik Wallenberg,
+Ian Watson, and
+Vince Wiggins.
+
+{marker aut}
+{title:Author}
+
+ Ben Jann, ETH Zurich, jannb@ethz.ch
+
+{marker als}
+{title:Also see}
+
+ Manual: {hi:[R] estimates}
+
+ SJ: SJ5-3 st0085 (Jann 2005)
+ SJ7-2 st0085_1 (Jann 2007)
+
+{p 4 13 2}Online: help for
+ {helpb estimates},
+ {help estcom},
+ {helpb est_table:estimates table},
+ {helpb ereturn},
+ {help format},
+ {helpb file},
+ {helpb mfx},
+ {helpb eststo},
+ {helpb esttab},
+ {helpb estadd},
+ {helpb estpost}
+{p_end}
diff --git a/Modules/ado/plus/e/estpost.ado b/Modules/ado/plus/e/estpost.ado
new file mode 100644
index 0000000..7cb7bd7
--- /dev/null
+++ b/Modules/ado/plus/e/estpost.ado
@@ -0,0 +1,1839 @@
+*! version 1.1.5 08oct2009 Ben Jann
+* 1. estpost
+* 2. estpost_summarize
+* 3. estpost_tabulate
+* 4. estpost_tabstat
+* 5. estpost_ttest
+* 6. estpost_correlate
+* 7. estpost_stci (Stata 9 required)
+* 8. estpost_ci
+* 9. estpost_prtest
+* 10. estpost__svy_tabulate
+* 99. _erepost
+
+* 1. estpost
+program estpost, rclass // rclass => remove r()'s left behind by subcommand
+ version 8.2
+ local caller : di _caller()
+ capt syntax [, * ]
+ if _rc==0 { // => for bootstrap
+ _coef_table_header
+ ereturn display, `options'
+ exit
+ }
+ gettoken subcommand rest : 0, parse(" ,:")
+ capt confirm name `subcommand'
+ if _rc {
+ di as err "invalid subcommand"
+ exit 198
+ }
+
+ local l = length(`"`subcommand'"')
+ if `"`subcommand'"'==substr("summarize",1,max(2,`l')) local subcommand "summarize"
+ else if `"`subcommand'"'==substr("tabulate",1,max(2,`l')) local subcommand "tabulate"
+ else if `"`subcommand'"'==substr("correlate",1,max(3,`l')) local subcommand "correlate"
+ else if `"`subcommand'"'=="svy" {
+ _estpost_parse_svy `macval(rest)'
+ }
+ else if substr(`"`subcommand'"',1,5)=="_svy_" {
+ di as err "invalid subcommand"
+ exit 198
+ }
+
+ capt local junk: properties estpost_`subcommand' // does not work in Stata 8
+ if _rc==199 {
+ di as err "invalid subcommand"
+ exit 198
+ }
+
+ version `caller': estpost_`subcommand' `macval(rest)'
+ //eret list
+end
+program _estpost_markout2 // marks out obs that are missing on *all* variables
+ gettoken touse varlist: 0
+ if `:list sizeof varlist'>0 {
+ tempname touse2
+ gen byte `touse2' = 0
+ foreach var of local varlist {
+ qui replace `touse2' = 1 if !missing(`var')
+ }
+ qui replace `touse' = 0 if `touse2'==0
+ }
+end
+program _estpost_parse_svy
+ version 9.2
+ _on_colon_parse `0'
+ local 0 `"`s(after)'"'
+ gettoken subcommand rest : 0, parse(" ,")
+ local l = length(`"`subcommand'"')
+ if `"`subcommand'"'==substr("tabulate",1,max(2,`l')) local subcommand "tabulate"
+ c_local subcommand `"_svy_`subcommand'"'
+ c_local rest `"`s(before)' : `rest'"'
+end
+program _estpost_namesandlabels // used by some routines such as estpost_tabulate
+ version 8.2 // returns locals names, savenames, and labels
+ args varname values0 labels0
+ if `"`values0'"'=="" { // generate values: 1 2 3 ...
+ local i 0
+ foreach label of local labels0 {
+ local values0 `values0' `++i'
+ }
+ }
+ local haslabels 0
+ if `"`labels0'"'=="" & "`varname'"!="" {
+ local vallab: value label `varname'
+ }
+ while (1) {
+ gettoken value values0 : values0
+ if "`value'"=="" continue, break //=> exit loop
+ if `"`vallab'"'!="" {
+ local lbl: label `vallab' `value', strict
+ }
+ else {
+ gettoken lbl labels0 : labels0
+ }
+ if index("`value'",".") {
+ local haslabels 1
+ if `"`lbl'"'=="" {
+ local lbl "`value'"
+ }
+ local value: subinstr local value "." "_missing_"
+ }
+ local names0 `names0' `value'
+ if `"`lbl'"'!="" {
+ local labels `"`labels'`lblspace'`value' `"`lbl'"'"'
+ local lblspace " "
+ }
+ if `haslabels' continue
+ if `"`lbl'"'=="" {
+ local names `"`names'`space'`value'"'
+ local savenames `"`savenames'`space'`value'"'
+ }
+ else {
+ if regexm(`"`lbl'"', `"[:."]"') local haslabels 1
+ else if length(`"`lbl'"')>30 local haslabels 1
+ else {
+ local names `"`names'`space'`"`lbl'"'"'
+ local lbl: subinstr local lbl " " "_", all
+ local savenames `"`savenames'`space'`lbl'"'
+ }
+ }
+ local space " "
+ }
+ if `haslabels' {
+ local names `names0'
+ local savenames `names0'
+ }
+ c_local names `"`names'"' // to be used as matrix row- or colnames
+ c_local savenames `"`savenames'"' // names without spaces (for matlist)
+ if `haslabels' {
+ c_local labels `"`labels'"' // label dictionary
+ }
+ else c_local labels ""
+end
+program _estpost_eqnamesandlabels // used by some routines such as estpost_tabulate
+ version 8.2 // returns locals eqnames and eqlabels
+ args varname values0 labels0
+ if `"`values0'"'=="" { // generate values: 1 2 3 ...
+ local i 0
+ foreach label of local labels0 {
+ local values0 `values0' `++i'
+ }
+ }
+ local haslabels 0
+ if `"`labels0'"'=="" & "`varname'"!="" {
+ local vallab: value label `varname'
+ }
+ while (1) {
+ gettoken value values0 : values0
+ if "`value'"=="" continue, break //=> exit loop
+ if `"`vallab'"'!="" {
+ local lbl: label `vallab' `value', strict
+ }
+ else {
+ gettoken lbl labels0 : labels0
+ }
+ if index("`value'",".") {
+ local haslabels 1
+ if `"`lbl'"'=="" {
+ local lbl "`value'"
+ }
+ local value: subinstr local value "." "_missing_"
+ }
+ local names0 `names0' `value'
+ if `"`lbl'"'=="" local lbl "`value'"
+ local labels `"`labels'`lblspace'`"`lbl'"'"'
+ local lblspace " "
+ if `haslabels' continue
+ if `"`lbl'"'=="" {
+ local names `"`names'`space'`value'"'
+ }
+ else {
+ if regexm(`"`lbl'"', `"[:."]"') local haslabels 1
+ else if length(`"`lbl'"')>30 local haslabels 1
+ else {
+ local names `"`names'`space'`"`lbl'"'"'
+ }
+ }
+ local space " "
+ }
+ if `haslabels' {
+ local names `names0'
+ }
+ c_local eqnames `"`names'"' // to be used as matrix roweqs or coleqs
+ if `haslabels' {
+ c_local eqlabels `"`labels'"' // list of labels
+ }
+ else c_local eqlabels ""
+end
+
+* 2. estpost_summarize: wrapper for -summarize-
+prog estpost_summarize, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax [varlist] [if] [in] [aw fw iw] [, ESample Quietly ///
+ LISTwise CASEwise Detail MEANonly ]
+ if "`casewise'"!="" local listwise listwise
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ local nvars: list sizeof varlist
+ tempname emptymat
+ mat `emptymat' = J(1, `nvars', .)
+ mat coln `emptymat' = `varlist'
+ local i 0
+ local rnames ""
+ foreach v of local varlist {
+ local ++i
+ qui summarize `v' if `touse' [`weight'`exp'], `detail' `meanonly'
+ local rnamesi: r(scalars)
+ local rnamesi: list rnamesi - rnames
+ if `"`rnamesi'"'!="" {
+ foreach name of local rnamesi {
+ tempname _`name'
+ mat `_`name'' = `emptymat'
+ }
+ local rnames: list rnames | rnamesi
+ }
+ foreach rname of local rnames {
+ mat `_`rname''[1,`i'] = r(`rname')
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ local rescoln
+ foreach rname of local rnames {
+ mat `res' = nullmat(`res'), `_`rname'''
+ if "`rname'"=="N" {
+ local rescoln `rescoln' e(count)
+ }
+ else {
+ local rescoln `rescoln' e(`rname')
+ }
+ }
+ mat coln `res' = `rescoln'
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ matlist `res', nohalf lines(oneline)
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local b
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname b V
+ mat `b' = J(1, `nvars', 0)
+ mat coln `b' = `varlist'
+ mat `V' = `b'' * `b'
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `b' `V', obs(`N') `esample'
+
+ eret scalar k = `nvars'
+
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local subcmd "summarize"
+ eret local cmd "estpost"
+
+ local nmat: list sizeof rnames
+ forv i=`nmat'(-1)1 {
+ local rname: word `i' of `rnames'
+ if "`rname'"=="N" {
+ eret matrix count = `_N'
+ continue
+ }
+ eret matrix `rname' = `_`rname''
+ }
+end
+
+
+* 2. estpost_tabulate: wrapper for -tabulate-
+prog estpost_tabulate, eclass
+ version 8.2
+ local caller : di _caller() // not used
+ syntax varlist(min=1 max=2) [if] [in] [fw aw iw pw] [, * ]
+ if `:list sizeof varlist'==1 {
+ version `caller': estpost_tabulate_oneway `0'
+ }
+ else {
+ version `caller': estpost_tabulate_twoway `0'
+ }
+end
+prog estpost_tabulate_oneway, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varname [if] [in] [fw aw iw] [, ESample Quietly ///
+ noTOTal subpop(passthru) Missing sort noLabel ]
+
+ // sample
+ if "`missing'"!="" marksample touse, nov strok
+ else marksample touse, strok
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // handle string variables
+ capt confirm numeric variable `varlist'
+ if _rc {
+ tempname varname
+ qui encode `varlist' if `touse', generate(`varname')
+ }
+ else local varname `varlist'
+
+ // gather results
+ tempname count vals
+ tab `varname' if `touse' [`weight'`exp'], nofreq ///
+ matcell(`count') matrow(`vals') `subpop' `missing' `sort'
+ local N = r(N)
+ mat `count' = `count''
+ local R = r(r)
+ forv r = 1/`R' {
+ local value: di `vals'[`r',1]
+ local values `values' `value'
+ }
+ if "`label'"=="" {
+ _estpost_namesandlabels `varname' "`values'" // sets names, savenames, labels
+ }
+ else {
+ _estpost_namesandlabels "" "`values'"
+ }
+ if "`total'"=="" {
+ mat `count' = `count', `N'
+ local names `"`names' Total"'
+ local savenames `"`savenames' Total"'
+ local linesopt "lines(rowtotal)"
+ }
+ mat colname `count' = `names'
+ tempname percent cum
+ mat `percent' = `count'/`N'*100
+ mat `cum' = J(1, colsof(`count'), .z)
+ mat colname `cum' = `names'
+ mat `cum'[1,1] = `count'[1,1]
+ forv r = 2/`R' {
+ mat `cum'[1,`r'] = `cum'[1,`r'-1] + `count'[1,`r']
+ }
+ mat `cum' = `cum'/`N'*100
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `count'', `percent'', `cum''
+ mat coln `res' = e(b) e(pct) e(cumpct)
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g) nodotz
+ }
+ else {
+ mat rown `res' = `savenames'
+ matlist `res', nohalf `linesopt' rowtitle(`varlist') nodotz
+ }
+ mat drop `res'
+ if `"`labels'"'!="" {
+ di _n as txt "row labels saved in macro e(labels)"
+ }
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // V required in Stata 8
+ tempname V
+ mat `V' = `count'' * `count' * 0
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `count' `V', depname(`varlist') obs(`N') `esample'
+ eret scalar r = r(r)
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local labels `"`labels'"'
+ eret local depvar "`varlist'"
+ eret local subcmd "tabulate"
+ eret local cmd "estpost"
+ eret mat cumpct = `cum'
+ eret mat pct = `percent'
+end
+prog estpost_tabulate_twoway, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist(min=2 max=2) [if] [in] [fw aw iw] [, ESample Quietly ///
+ noTOTal Missing noLabel ///
+ CHi2 Exact Exact2(passthru) Gamma LRchi2 Taub v All noLOg ]
+ local v = upper("`v'")
+ local qui2 "`quietly'"
+ local hastests = `"`chi2'`exact'`exact2'`gamma'`lrchi2'`taub'`v'`all'"'!=""
+ if `hastests' local nofreq nofreq
+ else local qui2 "quietly"
+
+ // sample
+ if "`missing'"!="" marksample touse, nov strok
+ else marksample touse, strok
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // handle string variables
+ gettoken rvar cvar : varlist
+ gettoken cvar : cvar
+ foreach d in r c {
+ capt confirm numeric variable ``d'var'
+ if _rc {
+ tempname `d'varname
+ qui encode ``d'var' if `touse', generate(``d'varname')
+ }
+ else local `d'varname ``d'var'
+ }
+
+ // gather results
+ tempname cell rvals cvals
+ if `hastests' {
+ `quietly' di ""
+ }
+ `qui2' tab `rvarname' `cvarname' if `touse' [`weight'`exp'], `nofreq' ///
+ matcell(`cell') matrow(`rvals') matcol(`cvals') `missing' ///
+ `chi2' `exact' `exact2' `gamma' `lrchi2' `taub' `v' `all' `log'
+ mat `cvals' = `cvals''
+ local N = r(N)
+ tempname rtot ctot
+ mat `ctot' = J(1,rowsof(`cell'),1) * `cell'
+ mat `rtot' = `cell' * J(colsof(`cell'),1,1)
+ foreach d in r c {
+ local I = r(`d')
+ forv i = 1/`I' {
+ local value: di ``d'vals'[`i',1]
+ local `d'values ``d'values' `value'
+ }
+ }
+ if "`label'"=="" {
+ _estpost_namesandlabels `rvarname' "`rvalues'" // sets names, savenames, labels
+ _estpost_eqnamesandlabels `cvarname' "`cvalues'" // sets eqnames, eqlabels
+ }
+ else {
+ _estpost_namesandlabels "" "`rvalues'" // sets names, savenames, labels
+ _estpost_eqnamesandlabels "" "`cvalues'" // sets eqnames, eqlabels
+ }
+ local savenames0 `"`savenames'"'
+ local savenames
+ if "`total'"=="" {
+ mat `ctot' = `ctot', `N'
+ mat `cell' = (`cell', `rtot') \ `ctot'
+ mat `rtot' = `rtot' \ `N'
+ local names `"`names' Total"'
+ local savenames0 `"`savenames0' Total"'
+ local eqnames `"`eqnames' Total"'
+ }
+ mat rowname `cell' = `names'
+ tempname count col row tot tmp
+ forv i = 1/`=colsof(`cell')' {
+ gettoken eq eqnames : eqnames
+ mat `tmp' = `cell'[1...,`i']
+ mat roweq `tmp' = `"`eq'"'
+ mat `tmp' = `tmp''
+ mat `count' = nullmat(`count'), `tmp'
+ mat `col' = nullmat(`col'), `tmp' / `ctot'[1,`i']*100
+ forv j = 1/`=colsof(`tmp')' {
+ mat `tmp'[1,`j'] = `tmp'[1,`j'] / `rtot'[`j',1]*100
+ }
+ mat `row' = nullmat(`row'), `tmp'
+ local savenames `"`savenames' `savenames0'"'
+ }
+ mat `tot' = `count' / `N'*100
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `count'', `tot'', `col'', `row''
+ mat coln `res' = e(b) e(pct) e(colpct) e(rowpct)
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ mat rown `res' = `savenames'
+ di _n as res %-12s abbrev("`cvar'",12) as txt " {c |}{space 44}"
+ matlist `res', twidth(12) format(%9.0g) noblank nohalf rowtitle(`rvar')
+ }
+ mat drop `res'
+ if `"`labels'`eqlabels'"'!="" {
+ di ""
+ if `"`labels'"'!="" {
+ di as txt "row labels saved in macro e(labels)"
+ }
+ if `"`eqlabels'"'!="" {
+ di as txt "column labels saved in macro e(eqlabels)"
+ }
+ }
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // V required in Stata 8
+ tempname V
+ mat `V' = `count'' * `count' * 0
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `count' `V', obs(`N') `esample'
+ local rscalars: r(scalars)
+ local rscalars: subinstr local rscalars "N" "", word
+ foreach rsc of local rscalars {
+ eret scalar `rsc' = r(`rsc')
+ }
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local labels `"`labels'"'
+ eret local eqlabels `"`eqlabels'"'
+ eret local colvar "`cvar'"
+ eret local rowvar "`rvar'"
+ eret local subcmd "tabulate"
+ eret local cmd "estpost"
+ eret mat rowpct = `row'
+ eret mat colpct = `col'
+ eret mat pct = `tot'
+end
+
+
+* 4. estpost_tabstat: wrapper for -tabstat-
+prog estpost_tabstat, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist [if] [in] [aw fw] [, ESample Quietly ///
+ Statistics(passthru) stats(passthru) LISTwise CASEwise ///
+ by(varname) noTotal Missing Columns(str) ]
+ if "`casewise'"!="" local listwise listwise
+ local l = length(`"`columns'"')
+ if `"`columns'"'==substr("variables",1,max(1,`l')) local columns "variables"
+ else if `"`columns'"'==substr("statistics",1,max(1,`l')) local columns "statistics"
+ else if `"`columns'"'=="stats" local columns "statistics"
+ else if `"`columns'"'=="" {
+ if `:list sizeof varlist'>1 local columns "variables"
+ else local columns "statistics"
+ }
+ else {
+ di as err `"columns(`columns') invalid"'
+ exit 198
+ }
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ if "`by'"!="" {
+ if "`missing'"=="" markout `touse' `by', strok
+ local byopt "by(`by')"
+ }
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ if "`total'"!="" & "`by'"=="" {
+ di as txt "nothing to post"
+ eret clear
+ exit
+ }
+ qui tabstat `varlist' if `touse' [`weight'`exp'], save ///
+ `statistics' `stats' `byopt' `total' `missing' columns(`columns')
+ tempname tmp
+ capt confirm matrix r(StatTot)
+ if _rc {
+ mat `tmp' = r(Stat1)
+ }
+ else {
+ mat `tmp' = r(StatTot)
+ }
+ if `"`columns'"'=="statistics" {
+ local cnames: rownames `tmp'
+ local cnames: subinstr local cnames "N" "count", word all
+ local cnames: subinstr local cnames "se(mean)" "semean", word all
+ local R = colsof(`tmp')
+ local stats "`cnames'"
+ local vars: colnames `tmp'
+ }
+ else {
+ local cnames: colnames `tmp'
+ local R = rowsof(`tmp')
+ local stats: rownames `tmp'
+ local stats: subinstr local stats "N" "count", word all
+ local stats: subinstr local stats "se(mean)" "semean", word all
+ local vars "`cnames'"
+ local cnames: subinstr local cnames "b" "_b", word all
+ local cnames: subinstr local cnames "V" "_V", word all
+ }
+ local j 0
+ foreach cname of local cnames {
+ tempname _`++j'
+ }
+ local groups: r(macros)
+ local g: list sizeof groups
+ local space
+ local labels
+ forv i = 1/`g' {
+ local labels `"`labels'`space'`"`r(name`i')'"'"'
+ }
+ if `R'==1 {
+ _estpost_namesandlabels "" "" `"`labels'"' // sets names, savenames, labels
+ }
+ else {
+ _estpost_eqnamesandlabels "" "" `"`labels'"' // sets eqnames, eqlabels
+ local names `"`eqnames'"'
+ local labels `"`eqlabels'"'
+ }
+ forv i = 1/`g' {
+ gettoken name names : names
+ mat `tmp' = r(Stat`i')
+ mat rown `tmp' = `stats'
+ if `"`columns'"'=="statistics" {
+ mat `tmp' = `tmp''
+ }
+ if `R'==1 {
+ mat rown `tmp' = `"`name'"'
+ }
+ else {
+ mat roweq `tmp' = `"`name'"'
+ }
+ local j 0
+ foreach cname of local cnames {
+ local ++j
+ mat `_`j'' = nullmat(`_`j''), `tmp'[1..., `j']'
+ }
+ }
+ if "`total'"=="" {
+ mat `tmp' = r(StatTot)
+ mat rown `tmp' = `stats'
+ if `"`columns'"'=="statistics" {
+ mat `tmp' = `tmp''
+ }
+ if `g'>0 {
+ if `R'==1 {
+ mat rown `tmp' = "Total"
+ local savenames `"`savenames' Total"'
+ local rowtotal "lines(rowtotal)"
+ }
+ else {
+ mat roweq `tmp' = "Total"
+ if `"`labels'"'!="" {
+ local labels `"`labels' Total"'
+ }
+ }
+ }
+ local j 0
+ foreach cname of local cnames {
+ local ++j
+ mat `_`j'' = nullmat(`_`j''), `tmp'[1..., `j']'
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ local rescoln
+ local j 0
+ foreach cname of local cnames {
+ local ++j
+ mat `res' = nullmat(`res'), `_`j'''
+ local rescoln `rescoln' e(`cname')
+ }
+ mat coln `res' = `rescoln'
+ di _n as txt "Summary statistics: `stats'"
+ di as txt " for variables: `vars'"
+ if "`by'"!="" {
+ di as txt " by categories of: `by'"
+ }
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ if `R'==1 & `g'>0 {
+ mat rown `res' = `savenames'
+ }
+ matlist `res', nohalf `rowtotal' rowtitle(`by')
+ }
+ if `"`labels'"'!="" {
+ di _n as txt "category labels saved in macro e(labels)"
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local b
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname b V
+ mat `b' = `_1' \ J(1, colsof(`_1'), 0)
+ mat `b' = `b'[2,1...]
+ mat `V' = `b'' * `b'
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `b' `V', obs(`N') `esample'
+
+ eret local labels `"`labels'"'
+ eret local byvar "`by'"
+ eret local vars "`vars'"
+ eret local stats "`stats'"
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local subcmd "tabstat"
+ eret local cmd "estpost"
+
+ local nmat: list sizeof cnames
+ forv j=`nmat'(-1)1 {
+ local cname: word `j' of `cnames'
+ eret matrix `cname' = `_`j''
+ }
+end
+
+
+* 5. estpost_ttest: wrapper for -ttest- (two-sample)
+prog estpost_ttest, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist(numeric) [if] [in] , by(varname) [ ESample Quietly ///
+ LISTwise CASEwise UNEqual Welch ]
+ if "`casewise'"!="" local listwise listwise
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ markout `touse' `by', strok
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ local nvars: list sizeof varlist
+ tempname diff count
+ mat `diff' = J(1, `nvars', .)
+ mat coln `diff' = `varlist'
+ mat `count' = `diff'
+ local mnames se /*sd*/ t df_t p_l p p_u N_1 mu_1 /*sd_1*/ N_2 mu_2 /*sd_2*/
+ foreach m of local mnames {
+ tempname `m'
+ mat ``m'' = `diff'
+ }
+ local i 0
+ foreach v of local varlist {
+ local ++i
+ qui ttest `v' if `touse', by(`by') `unequal' `welch'
+ mat `diff'[1,`i'] = r(mu_1) - r(mu_2)
+ mat `count'[1,`i'] = r(N_1) + r(N_2)
+ foreach m of local mnames {
+ mat ``m''[1,`i'] = r(`m')
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `diff'', `count''
+ local rescoln "e(b) e(count)"
+ foreach m of local mnames {
+ mat `res' = `res', ``m'''
+ local rescoln `rescoln' e(`m')
+ }
+ mat coln `res' = `rescoln'
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ matlist `res', nohalf lines(oneline)
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname V
+ mat `V' = diag(vecdiag(`se'' * `se'))
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `diff' `V', obs(`N') `esample'
+
+ eret scalar k = `nvars'
+
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local welch "`welch'"
+ eret local unequal "`unequal'"
+ eret local byvar "`by'"
+ eret local subcmd "ttest"
+ eret local cmd "estpost"
+
+ local nmat: list sizeof mnames
+ forv i=`nmat'(-1)1 {
+ local m: word `i' of `mnames'
+ eret matrix `m' = ``m''
+ }
+ eret matrix count = `count'
+end
+
+
+* 6. estpost_correlate: wrapper for -correlate-
+prog estpost_correlate, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist [if] [in] [aw fw iw pw] [, ESample Quietly ///
+ LISTwise CASEwise ///
+ Matrix noHalf Print(real 1) /*Covariance*/ Bonferroni SIDak ]
+ if "`casewise'"!="" local listwise listwise
+ if "`bonferroni'"!="" & "`sidak'"!="" {
+ di as err "only one of bonferroni and sidak allowed"
+ exit 198
+ }
+ local pw = ("`weight'"=="pweight")
+ if `:list sizeof varlist'<=1 & `"`matrix'"'=="" {
+ di as err "too few variables specified"
+ exit 102
+ }
+ if `"`matrix'"'!="" & `"`half'"'!="" local fullmatrix fullmatrix
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ tempname b rho pval count
+ if "`bonferroni'`sidak'"!="" {
+ local nvars : list sizeof varlist
+ local k = `nvars' * (`nvars'-1) / 2
+ }
+ foreach depvar of local varlist {
+ if `"`fullmatrix'"'!="" {
+ local indepvars `varlist'
+ }
+ else if `"`matrix'"'!="" {
+ local indepvars `depvar' `ferest()'
+ }
+ else {
+ local indepvars `ferest()'
+ }
+ foreach v of local indepvars {
+ qui reg `depvar' `v' [`weight'`exp'] if `touse'
+ local r = sqrt(e(r2)) * (-1)^(_b[`v']<0)
+ local n = e(N)
+ mat `b' = nullmat(`b'), `r'
+ if "`depvar'"=="`v'" {
+ mat `rho' = nullmat(`rho'), `r'
+ mat `count' = nullmat(`count'), `n'
+ mat `pval' = nullmat(`pval'), .z
+ continue
+ }
+ local p = Ftail(e(df_m), e(df_r), e(F))
+ if `pw' {
+ qui reg `v' `depvar' [`weight'`exp'] if `touse'
+ local p = max(`p', Ftail(e(df_m), e(df_r), e(F)))
+ }
+ if "`bonferroni'"!="" {
+ local p = min(1, `k'*`p')
+ }
+ else if "`sidak'"!="" {
+ local p = min(1, 1 - (1-`p')^`k')
+ }
+ if `p'>`print' {
+ local r .z
+ local n .z
+ local p .z
+ }
+ mat `rho' = nullmat(`rho'), `r'
+ mat `count' = nullmat(`count'), `n'
+ mat `pval' = nullmat(`pval'), `p'
+ }
+ if `"`matrix'`fullmatrix'"'=="" {
+ local colnames `indepvars'
+ local depname `depvar'
+ continue, break
+ }
+ foreach v of local indepvars {
+ local colnames `"`colnames'`depvar':`v' "'
+ }
+ }
+ mat coln `b' = `colnames'
+ mat coln `rho' = `colnames'
+ mat coln `count' = `colnames'
+ mat coln `pval' = `colnames'
+ local vce `"`e(vce)'"' // from last -regress- call
+ local vcetype `"`e(vcetype)'"'
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `b'', `rho'', `pval'', `count''
+ mat coln `res' = e(b) e(rho) e(p) e(count)
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g) nodotz
+ }
+ else {
+ matlist `res', nohalf lines(oneline) rowtitle(`depname') nodotz
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname b
+ mat `V' = `b'' * `b' * 0
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `b' `V', depname(`depname') obs(`N') `esample'
+ eret local vcetype `"`vcetype'"'
+ eret local vce `"`vce'"'
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local depvar `depname'
+ eret local subcmd "correlate"
+ eret local cmd "estpost"
+ eret matrix count = `count'
+ eret matrix p = `pval'
+ eret matrix rho = `rho'
+end
+
+
+* 7. estpost_stci: wrapper for -stci-
+prog estpost_stci, eclass
+ version 9.2 // Stata 8 not supported because levelsof is used
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax [if] [in] [ , ESample Quietly by(varname) ///
+ Median Rmean Emean p(numlist >0 <100 integer max=1) ///
+ CCorr Level(real `c(level)') ]
+ local stat "p50"
+ if `"`p'"'!="" {
+ local stat `"p`p'"'
+ local p `"p(`p')"'
+ }
+ else if "`rmean'"!="" local stat "rmean"
+ else if "`emean'"!="" local stat "emean"
+
+ // sample
+ marksample touse
+ if `"`by'"'!="" {
+ markout `touse' `by', strok
+ }
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // get results
+ tempname _`stat' se N_sub lb ub
+ if "`by'"!="" {
+ qui levelsof `by' if `touse', local(levels)
+ capt confirm string variable `by'
+ if _rc {
+ local vallab: value label `by'
+ if `"`vallab'"'!="" {
+ _estpost_namesandlabels `by' `"`levels'"' // sets names, savenames, labels
+ }
+ else {
+ local names `"`levels'"'
+ local savenames `"`levels'"'
+ }
+ }
+ else {
+ _estpost_namesandlabels `by' "" `"`levels'"' // sets names, savenames, labels
+ }
+ }
+ local levels `"`levels' "total""'
+ local names `"`names' "total""'
+ local savenames `"`savenames' "total""'
+ gettoken l rest : levels, quotes
+ while (`"`l'"'!="") {
+ if `"`rest'"'=="" local lcond
+ else local lcond `" & `by'==`l'"'
+ qui stci if `touse'`lcond', `median' `rmean' `emean' `p' `ccorr' level(`level')
+ mat `_`stat'' = nullmat(`_`stat''), r(`stat')
+ mat `se' = nullmat(`se'), r(se)
+ mat `N_sub' = nullmat(`N_sub'), r(N_sub)
+ mat `lb' = nullmat(`lb'), r(lb)
+ mat `ub' = nullmat(`ub'), r(ub)
+ gettoken l rest : rest, quotes
+ }
+ foreach m in _`stat' se N_sub lb ub {
+ mat coln ``m'' = `names'
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `N_sub'', `_`stat''', `se'', `lb'', `ub''
+ mat coln `res' = e(count) e(`stat') e(se) e(lb) e(ub)
+ di as txt "(confidence level is " `level' "%)"
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g) nodotz
+ }
+ else {
+ mat rown `res' = `savenames'
+ matlist `res', nohalf lines(rowtotal) nodotz
+ }
+ mat drop `res'
+ if `"`labels'"'!="" {
+ di _n as txt "labels saved in macro e(labels)"
+ }
+ }
+
+ // post results
+ local b
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname b V
+ mat `b' = `_`stat'' \ J(1, colsof(`_`stat''), 0)
+ mat `b' = `b'[2,1...]
+ mat `V' = `b'' * `b'
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `b' `V', obs(`N') `esample'
+ eret scalar level = `level'
+
+ eret local ccorr `ccorr'
+ eret local labels `"`labels'"'
+ eret local subcmd "stci"
+ eret local cmd "estpost"
+
+ eret matrix ub = `ub'
+ eret matrix lb = `lb'
+ eret matrix se = `se'
+ eret matrix `stat' = `_`stat''
+ eret matrix count = `N_sub'
+end
+
+
+* 8. estpost_ci: wrapper for -ci-
+prog estpost_ci, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax [varlist] [if] [in] [aw fw], [ ESample Quietly ///
+ LISTwise CASEwise Level(real `c(level)') ///
+ Binomial EXAct WAld Wilson Agresti Jeffreys ///
+ Poisson Exposure(varname) ///
+ ]
+ if "`casewise'"!="" local listwise listwise
+ if "`exposure'"!="" local exposureopt "exposure(`exposure')"
+ if "`binomial'"!="" & "`exact'`wald'`wilson'`agresti'`jeffreys'"=="" local exact exact
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ local mnames se lb ub
+ tempname mean count `mnames'
+ local i 0
+ foreach v of local varlist {
+ local ++i
+ qui ci `v' if `touse' [`weight'`exp'], level(`level') ///
+ `binomial' `exact' `wald' `wilson' `agresti' `jeffreys' ///
+ `poisson' `exposureopt'
+ if r(N)>=. continue
+ mat `mean' = nullmat(`mean'), r(mean)
+ mat `count' = nullmat(`count'), r(N)
+ foreach m of local mnames {
+ mat ``m'' = nullmat(``m''), r(`m')
+ }
+ local rnames "`rnames' `v'"
+ }
+ capt confirm matrix `count'
+ if _rc {
+ di as txt "nothing to post"
+ eret clear
+ exit
+ }
+ foreach m in mean count `mnames' {
+ mat coln ``m'' = `rnames'
+ }
+ if "`listwise'"=="" { // update sample
+ if colsof(`count') < `: list sizeof varlist' {
+ _estpost_markout2 `touse' `rnames'
+ qui count if `touse'
+ local N = r(N)
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `mean'', `count''
+ local rescoln "e(b) e(count)"
+ foreach m of local mnames {
+ mat `res' = `res', ``m'''
+ local rescoln `rescoln' e(`m')
+ }
+ mat coln `res' = `rescoln'
+ di as txt "(confidence level is " `level' "%)"
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ matlist `res', nohalf lines(oneline)
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname V
+ mat `V' = diag(vecdiag(`se'' * `se'))
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `mean' `V', obs(`N') `esample'
+
+ eret scalar k = colsof(`count')
+ eret scalar level = `level'
+
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local exposure "`exposure'"
+ eret local poisson "`poisson'"
+ eret local binomial "`exact'`wald'`wilson'`agresti'`jeffreys'"
+ eret local subcmd "ci"
+ eret local cmd "estpost"
+
+ local nmat: list sizeof mnames
+ forv i=`nmat'(-1)1 {
+ local m: word `i' of `mnames'
+ eret matrix `m' = ``m''
+ }
+ eret matrix count = `count'
+end
+
+
+* 9. estpost_prtest: wrapper for -prtest- (two-sample)
+prog estpost_prtest, eclass
+ version 8.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist(numeric) [if] [in] , by(varname) [ ESample Quietly ///
+ LISTwise CASEwise ]
+ if "`casewise'"!="" local listwise listwise
+
+ // sample
+ if "`listwise'"!="" marksample touse
+ else {
+ marksample touse, nov
+ _estpost_markout2 `touse' `varlist'
+ }
+ markout `touse' `by', strok
+ qui count if `touse'
+ local N = r(N)
+ if `N'==0 error 2000
+
+ // gather results
+ local nvars: list sizeof varlist
+ tempname diff count
+ mat `count' = J(1, `nvars', .)
+ mat coln `count' = `varlist'
+ mat `diff' = `count'
+ local mnames se se0 z p_l p p_u N_1 P_1 N_2 P_2
+ foreach m of local mnames {
+ tempname `m'
+ mat ``m'' = `count'
+ }
+ local i 0
+ foreach v of local varlist {
+ local ++i
+ qui prtest `v' if `touse', by(`by')
+ mat `count'[1,`i'] = r(N_1) + r(N_2)
+ mat `diff'[1,`i'] = r(P_1) - r(P_2)
+ mat `se'[1,`i'] = sqrt(r(P_1)*(1-r(P_1))/r(N_1) + r(P_2)*(1-r(P_2))/r(N_2))
+ mat `se0'[1,`i'] = `diff'[1,`i'] / r(z)
+ mat `p_l'[1,`i'] = normal(r(z))
+ mat `p'[1,`i'] = (1-normal(abs(r(z))))*2
+ mat `p_u'[1,`i'] = 1-normal(r(z))
+ foreach m in z N_1 P_1 N_2 P_2 {
+ mat ``m''[1,`i'] = r(`m')
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ tempname res
+ mat `res' = `diff'', `count''
+ local rescoln "e(b) e(count)"
+ foreach m of local mnames {
+ mat `res' = `res', ``m'''
+ local rescoln `rescoln' e(`m')
+ }
+ mat coln `res' = `rescoln'
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g)
+ }
+ else {
+ matlist `res', nohalf lines(oneline)
+ }
+ mat drop `res'
+ }
+
+ // post results
+ local V
+ if c(stata_version)<9 { // b and V required in Stata 8
+ tempname V
+ mat `V' = diag(vecdiag(`se'' * `se'))
+ }
+ if "`esample'"!="" local esample esample(`touse')
+ eret post `diff' `V', obs(`N') `esample'
+
+ eret scalar k = `nvars'
+
+ eret local wexp `"`exp'"'
+ eret local wtype `"`weight'"'
+ eret local byvar "`by'"
+ eret local subcmd "prtest"
+ eret local cmd "estpost"
+
+ local nmat: list sizeof mnames
+ forv i=`nmat'(-1)1 {
+ local m: word `i' of `mnames'
+ eret matrix `m' = ``m''
+ }
+ eret matrix count = `count'
+end
+
+
+* 10. estpost__svy_tabulate: wrapper for -svy:tabulate-
+prog estpost__svy_tabulate
+ version 9.2
+ local caller : di _caller()
+ _on_colon_parse `0'
+ local svyopts `"svyopts(`s(before)')"'
+ local 0 `"`s(after)'"'
+ syntax varlist(min=1 max=2) [if] [in] [ , * ]
+ if `:list sizeof varlist'==1 {
+ version `caller': _svy_tabulate_oneway `varlist' `if' `in', ///
+ `svyopts' `options'
+ }
+ else {
+ version `caller': _svy_tabulate_twoway `varlist' `if' `in', ///
+ `svyopts' `options'
+ }
+end
+prog _svy_tabulate_oneway
+ version 9.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varname [if] [in] [, ESample Quietly ///
+ svyopts(str asis) MISSing Level(cilevel) ///
+ noTOTal noMARGinals noLabel PROPortion PERcent ///
+ CELl COUnt se ci deff deft * ]
+ if "`marginals'"!="" local total "nototal"
+ else if "`total'"!="" local marginals "nomarginals"
+
+ // run svy:tabulate
+ `quietly' svy `svyopts' : tabulate `varlist' `if' `in', ///
+ level(`level') `cell' `count' `se' `ci' `deff' `deft' ///
+ `missing' `marginals' `label' `proportion' `percent' `options'
+ if "`count'"!="" & "`cell'`se'`ci'`deff'`deft'"=="" { // => return count in e(b)
+ quietly svy `svyopts' : tabulate `varlist' `if' `in', count se ///
+ level(`level') `missing' `marginals' `label' `proportion' `percent' `options'
+ }
+
+ // get labels
+ qui levelsof `varlist' if e(sample), `missing' local(levels)
+ local R : list sizeof levels
+ if e(r)!=`R' {
+ di as err "unexpected error; number of rows unequal number of levels"
+ exit 499
+ }
+ capt confirm string variable `varlist'
+ if _rc {
+ if "`label'"=="" {
+ _estpost_namesandlabels `varlist' "`levels'" // sets names, savenames, labels
+ }
+ else {
+ _estpost_namesandlabels "" "`levels'" // sets names, savenames, labels
+ }
+ }
+ else {
+ _estpost_namesandlabels "" "" `"`levels'"' // sets names, savenames, labels
+ }
+
+ // collect results
+ tempname cell count obs b se lb ub deff deft
+ local N_pop = cond(e(N_subpop)<., e(N_subpop), e(N_pop))
+ local N_obs = cond(e(N_sub)<., e(N_sub), e(N))
+ local tval = invttail(e(df_r), (100-`level')/200)
+ mat `cell' = e(Prop)'
+ mat `count' = `cell' * `N_pop'
+ capture confirm matrix e(ObsSub)
+ if _rc {
+ mat `obs' = e(Obs)'
+ }
+ else {
+ mat `obs' = e(ObsSub)'
+ }
+ capture confirm matrix e(Deff)
+ if _rc local DEFF ""
+ else {
+ local DEFF deff
+ mat `deff' = e(Deff)
+ }
+ capture confirm matrix e(Deft)
+ if _rc local DEFT ""
+ else {
+ local DEFT deft
+ mat `deft' = e(Deft)
+ }
+ mat `b' = e(b)
+ mata: st_matrix(st_local("se"), sqrt(diagonal(st_matrix("e(V)")))')
+ if "`total'"=="" {
+ mat `cell' = `cell', 1
+ mat `count' = `count', `N_pop'
+ mat `obs' = `obs', `N_obs'
+ if "`DEFF'"!="" mat `deff' = `deff', .z
+ if "`DEFT'"!="" mat `deft' = `deft', .z
+ if e(setype)=="count" {
+ mat `b' = `b', `N_pop'
+ mat `se' = `se', sqrt(el(e(V_col),1,1))
+ }
+ else { // e(setype)=="cell"
+ mat `b' = `b', 1
+ mat `se' = `se', 0
+ }
+ local names `"`names' "Total""'
+ local savenames `"`savenames' "Total""'
+ local linesopt "lines(rowtotal)"
+
+ }
+ if e(setype)!="count" {
+ mata: st_matrix( st_local("lb"), invlogit( ///
+ logit(st_matrix(st_local("b"))) - strtoreal(st_local("tval")) * ///
+ st_matrix(st_local("se")) :/ ///
+ (st_matrix(st_local("b")) :* (1 :- st_matrix(st_local("b"))))))
+ mata: st_matrix( st_local("ub"), invlogit( ///
+ logit(st_matrix(st_local("b"))) + strtoreal(st_local("tval")) * ///
+ st_matrix(st_local("se")) :/ ///
+ (st_matrix(st_local("b")) :* (1 :- st_matrix(st_local("b"))))))
+ if "`total'"=="" {
+ mat `lb'[1, colsof(`lb')] = .z
+ mat `ub'[1, colsof(`ub')] = .z
+ }
+ }
+ else {
+ mata: st_matrix( st_local("lb"), st_matrix(st_local("b")) - ///
+ strtoreal(st_local("tval")) * st_matrix(st_local("se")) )
+ mata: st_matrix( st_local("ub"), st_matrix(st_local("b")) + ///
+ strtoreal(st_local("tval")) * st_matrix(st_local("se")) )
+ }
+ foreach m in cell count obs b se lb ub `DEFF' `DEFT' {
+ capt mat coln ``m'' = `names'
+ }
+ if "`percent'"!="" {
+ mat `cell' = `cell' * 100
+ if e(setype)!="count" {
+ mat `b' = `b' * 100
+ mat `se' = `se' * 100
+ mat `lb' = `lb' * 100
+ mat `ub' = `ub' * 100
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ /*
+ tempname res
+ mat `res' = `b'', `se'', `lb'', `ub'', `deff'', `deft'' ///, `cell'', `count'', `obs''
+ mat coln `res' = e(b) e(se) e(lb) e(ub) e(deff) e(deft) /// e(cell) e(count) e(obs)
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g) nodotz
+ }
+ else {
+ mat rown `res' = `savenames'
+ matlist `res', nohalf `linesopt' rowtitle(`varlist') nodotz
+ }
+ mat drop `res'
+ */
+ local plabel = cond("`percent'"!="","percentages","proportions")
+ local blabel = cond("`e(setype)'"=="count", "weighted counts", "`e(setype)' `plabel'")
+ di _n as txt "saved vectors:"
+ di as txt %20s "e(b) = " " " as res "`blabel'"
+ di as txt %20s "e(se) = " " " as res "standard errors of `blabel'"
+ di as txt %20s "e(lb) = " " " as res "lower `level'% confidence bounds for `blabel'"
+ di as txt %20s "e(ub) = " " " as res "upper `level'% confidence bounds for `blabel'"
+ if "`DEFF'"!="" ///
+ di as txt %20s "e(deff) = " " " as res "deff for variances of `blabel'"
+ if "`DEFT'"!="" ///
+ di as txt %20s "e(deft) = " " " as res "deft for variances of `blabel'"
+ di as txt %20s "e(cell) = " " " as res "cell `plabel'"
+ di as txt %20s "e(count) = " " " as res "weighted counts"
+ di as txt %20s "e(obs) = " " " as res "number of observations"
+ if `"`labels'"'!="" {
+ di _n as txt "row labels saved in macro e(labels)"
+ }
+ }
+
+ // post results
+ erepost b=`b', cmd(estpost) nov `esample'
+ qui estadd local labels `"`labels'"'
+ qui estadd local subcmd "tabulate"
+ qui estadd scalar level = `level'
+ foreach m in obs count cell `DEFT' `DEFF' ub lb se {
+ qui estadd matrix `m' = ``m'', replace
+ }
+end
+prog _svy_tabulate_twoway
+ version 9.2
+ local caller : di _caller() // not used
+
+ // syntax
+ syntax varlist(min=1 max=2) [if] [in] [, ESample Quietly ///
+ svyopts(str asis) MISSing Level(cilevel) ///
+ noTOTal noMARGinals noLabel PROPortion PERcent ///
+ CELl COUnt COLumn row se ci deff deft * ]
+ if "`marginals'"!="" local total "nototal"
+ else if "`total'"!="" local marginals "nomarginals"
+
+ // run svy:tabulate
+ `quietly' svy `svyopts' : tabulate `varlist' `if' `in', ///
+ level(`level') `cell' `count' `column' `row' `se' `ci' `deff' `deft' ///
+ `missing' `marginals' `label' `proportion' `percent' `options'
+ if `: word count `count' `column' `row''==1 & "`cell'`se'`ci'`deff'`deft'"=="" {
+ quietly svy `svyopts' : tabulate `varlist' `if' `in', `count' `column' `row' se ///
+ level(`level') `missing' `marginals' `label' `proportion' `percent' `options'
+ }
+
+ // get labels
+ local rvar `"`e(rowvar)'"'
+ qui levelsof `rvar' if e(sample), `missing' local(levels)
+ local R : list sizeof levels
+ if e(r)!=`R' {
+ di as err "unexpected error; number of rows unequal number of rowvar levels"
+ exit 499
+ }
+ capt confirm string variable `rvar'
+ if _rc {
+ if "`label'"=="" {
+ _estpost_namesandlabels `rvar' "`levels'" // sets names, savenames, labels
+ }
+ else {
+ _estpost_namesandlabels "" "`levels'" // sets names, savenames, labels
+ }
+ }
+ else {
+ _estpost_namesandlabels "" "" `"`levels'"' // sets names, savenames, labels
+ }
+ local cvar `"`e(colvar)'"'
+ qui levelsof `cvar' if e(sample), `missing' local(levels)
+ local C : list sizeof levels
+ if e(c)!=`C' {
+ di as err "unexpected error; number of column unequal number of colvar levels"
+ exit 499
+ }
+ local savenames0 `"`savenames'"'
+ local savenames
+ capt confirm string variable `cvar'
+ if _rc {
+ if "`label'"=="" {
+ _estpost_eqnamesandlabels `cvar' "`levels'" // sets eqnames, eqlabels
+ }
+ else {
+ _estpost_eqnamesandlabels "" "`levels'" // sets eqnames, eqlabels
+ }
+ }
+ else {
+ _estpost_eqnamesandlabels "" "" `"`levels'"' // sets eqnames, eqlabels
+ }
+
+ // collect results
+ tempname tmp cell row col count obs b se lb ub deff deft
+ local N_pop = cond(e(N_subpop)<., e(N_subpop), e(N_pop))
+ local N_obs = cond(e(N_sub)<., e(N_sub), e(N))
+ local tval = invttail(e(df_r), (100-`level')/200)
+ mat `cell' = e(Prop) // r x c matrix
+ mat `cell' = (`cell', `cell' * J(`C',1,1)) \ (J(1,`R',1) * `cell', 1)
+ mat `count' = `cell' * `N_pop'
+ mat `tmp' = `cell'[1..., `C'+1]
+ mata: st_matrix(st_local("row"), st_matrix(st_local("cell")) :/ ///
+ st_matrix(st_local("tmp")))
+ mat `tmp' = `cell'[`R'+1, 1...]
+ mata: st_matrix(st_local("col"), st_matrix(st_local("cell")) :/ ///
+ st_matrix(st_local("tmp")))
+ mat drop `tmp'
+ capture confirm matrix e(ObsSub)
+ if _rc {
+ mat `obs' = e(Obs) // r x c matrix
+ }
+ else {
+ mat `obs' = e(ObsSub) // r x c matrix
+ }
+ capt confirm matrix e(Deff)
+ if _rc local DEFF ""
+ else {
+ local DEFF deff
+ mat `deff' = e(Deff) // vector
+ }
+ capt confirm matrix e(Deft)
+ if _rc local DEFT ""
+ else {
+ local DEFT deft
+ mat `deft' = e(Deft) // vector
+ }
+ mat `b' = e(b) // vector
+ mata: st_matrix(st_local("se"), sqrt(diagonal(st_matrix("e(V)")))') // vector
+ if e(setype)=="count" local btype count
+ else if e(setype)=="row" local btype row
+ else if e(setype)=="column" local btype col
+ else local btype cell
+ foreach m in `DEFF' `DEFT' b se { // vector -> r x c matrix
+ forv r = 1/`R' {
+ local from = (`r'-1)*`C' + 1
+ local to = `r'*`C'
+ mat `tmp' = nullmat(`tmp') \ ``m''[1, `from'..`to']
+ }
+ mat drop ``m''
+ mat rename `tmp' ``m''
+ }
+ if "`total'"=="" {
+ mat `obs' = (`obs', `obs' * J(`C',1,1)) \ (J(1,`R',1) * `obs', `N_obs')
+ if "`DEFF'"!="" mat `deff' = (`deff', e(Deff_row)') \ (e(Deff_col), .z)
+ if "`DEFT'"!="" mat `deft' = (`deft', e(Deft_row)') \ (e(Deft_col), .z)
+ mat `b' = (`b', ``btype''[1..`R',`C'+1]) \ ``btype''[`R'+1,1...]
+ mata: st_matrix(st_local("se"), ///
+ ((st_matrix(st_local("se")), sqrt(diagonal(st_matrix("e(V_row)")))) ///
+ \ (sqrt(diagonal(st_matrix("e(V_col)")))', .z)))
+ if "`btype'"=="row" {
+ mat `se' = `se'[1..., 1..`C'], J(`R'+1, 1, .z)
+ }
+ else if "`btype'"=="col" {
+ mat `se' = `se'[1..`R', 1...] \ J(1, `C'+1, .z)
+ }
+ local names `"`names' "Total""'
+ local savenames0 `"`savenames0' "Total""'
+ local eqnames `"`eqnames' "Total""'
+ }
+ else {
+ mat `cell' = `cell'[1..`R', 1..`C']
+ mat `count' = `count'[1..`R', 1..`C']
+ mat `row' = `row'[1..`R', 1..`C']
+ mat `col' = `col'[1..`R', 1..`C']
+ }
+ if "`btype'"!="count" {
+ mata: st_matrix( st_local("lb"), invlogit( ///
+ logit(st_matrix(st_local("b"))) - strtoreal(st_local("tval")) * ///
+ st_matrix(st_local("se")) :/ ///
+ (st_matrix(st_local("b")) :* (1 :- st_matrix(st_local("b"))))))
+ mata: st_matrix( st_local("ub"), invlogit( ///
+ logit(st_matrix(st_local("b"))) + strtoreal(st_local("tval")) * ///
+ st_matrix(st_local("se")) :/ ///
+ (st_matrix(st_local("b")) :* (1 :- st_matrix(st_local("b"))))))
+ }
+ else {
+ mata: st_matrix( st_local("lb"), st_matrix(st_local("b")) - ///
+ strtoreal(st_local("tval")) * st_matrix(st_local("se")) )
+ mata: st_matrix( st_local("ub"), st_matrix(st_local("b")) + ///
+ strtoreal(st_local("tval")) * st_matrix(st_local("se")) )
+ }
+ if "`total'"=="" {
+ if "`btype'"=="row" {
+ mat `lb' = `lb'[1..., 1..`C'] , J(`R'+1, 1, .z)
+ mat `ub' = `ub'[1..., 1..`C'] , J(`R'+1, 1, .z)
+ }
+ else if "`btype'"=="col" {
+ mat `lb' = `lb'[1..`R', 1...] \ J(1, `C'+1, .z)
+ mat `ub' = `ub'[1..`R', 1...] \ J(1, `C'+1, .z)
+ }
+ else {
+ mat `lb'[`R'+1, `C'+1] = .z
+ mat `ub'[`R'+1, `C'+1] = .z
+ }
+ }
+ foreach m in cell count obs row col `DEFF' `DEFT' b se lb ub { // r x c matrix -> vector
+ mat rown ``m'' = `names'
+ gettoken eq rest : eqnames
+ forv c = 1/`=colsof(``m'')' {
+ mat roweq ``m'' = `"`eq'"'
+ mat `tmp' = nullmat(`tmp'), ``m''[1...,`c']'
+ gettoken eq rest : rest
+ }
+ mat drop ``m''
+ mat rename `tmp' ``m''
+ }
+ if "`percent'"!="" {
+ mat `cell' = `cell' * 100
+ mat `col' = `col' * 100
+ mat `row' = `row' * 100
+ if e(setype)!="count" {
+ mat `b' = `b' * 100
+ mat `se' = `se' * 100
+ mat `lb' = `lb' * 100
+ mat `ub' = `ub' * 100
+ }
+ }
+
+ // display
+ if "`quietly'"=="" {
+ /*
+ forv c = 1/`=colsof(`cell')' {
+ local savenames `"`savenames' `savenames0'"'
+ }
+ tempname res
+ mat `res' = `b'', `se'', `lb'', `ub'', `deff'', `deft'', `cell'', `row'', `col'', `count'', `obs''
+ mat coln `res' = e(b) e(se) e(lb) e(ub) e(deff) e(deft) e(cell) e(row) e(col) e(count) e(obs)
+ if c(stata_version)<9 {
+ mat list `res', noheader nohalf format(%9.0g) nodotz
+ }
+ else {
+ mat rown `res' = `savenames'
+ di _n as res %-12s abbrev("`cvar'",12) as txt " {c |}{space 44}"
+ matlist `res', twidth(12) format(%9.0g) noblank nohalf ///
+ rowtitle(`rvar') nodotz
+ }
+ mat drop `res'
+ */
+ local plabel = cond("`percent'"!="","percentages","proportions")
+ local blabel = cond("`e(setype)'"=="count", "weighted counts", "`e(setype)' `plabel'")
+ di _n as txt "saved vectors:"
+ di as txt %20s "e(b) = " " " as res "`blabel'"
+ di as txt %20s "e(se) = " " " as res "standard errors of `blabel'"
+ di as txt %20s "e(lb) = " " " as res "lower `level'% confidence bounds for `blabel'"
+ di as txt %20s "e(ub) = " " " as res "upper `level'% confidence bounds for `blabel'"
+ if "`DEFF'"!="" ///
+ di as txt %20s "e(deff) = " " " as res "deff for variances of `blabel'"
+ if "`DEFT'"!="" ///
+ di as txt %20s "e(deft) = " " " as res "deft for variances of `blabel'"
+ di as txt %20s "e(cell) = " " " as res "cell `plabel'"
+ di as txt %20s "e(row) = " " " as res "row `plabel'"
+ di as txt %20s "e(col) = " " " as res "column `plabel'"
+ di as txt %20s "e(count) = " " " as res "weighted counts"
+ di as txt %20s "e(obs) = " " " as res "number of observations"
+ if `"`labels'`eqlabels'"'!="" {
+ di ""
+ if `"`labels'"'!="" {
+ di as txt "row labels saved in macro e(labels)"
+ }
+ if `"`eqlabels'"'!="" {
+ di as txt "column labels saved in macro e(eqlabels)"
+ }
+ }
+ }
+
+ // post results
+ erepost b=`b', cmd(estpost) nov `esample'
+ qui estadd local eqlabels `"`eqlabels'"'
+ qui estadd local labels `"`labels'"'
+ qui estadd local subcmd "tabulate"
+ qui estadd scalar level = `level'
+ foreach m in obs count row col cell `DEFT' `DEFF' ub lb se {
+ qui estadd matrix `m' = ``m'', replace
+ }
+end
+
+* 11. estpost_margins: wrapper for -margins- (Stata 11)
+prog estpost_margins, eclass
+ version 11
+ local caller : di _caller()
+
+ // syntax
+ _parse comma anything 0 : 0
+ syntax [ , /*ESample*/ Quietly ///
+ post * ]
+ if "`post'"!="" {
+ di as err "post not allowed"
+ exit 198
+ }
+
+ // run margins
+ `quietly' version `caller': margins `anything', `options'
+
+ // post results
+ capt postrtoe, noclear resize
+ if _rc<=1 { // -postrtoe- does not work, e.g., with -regress-
+ error _rc // _rc=1 (break)
+ exit
+ }
+ tempname b V
+ mat `b' = r(b)
+ mat `V' = r(V)
+ erepost b = `b' V = `V' /*, `esample'*/
+ foreach r in `:r(scalars)' {
+ eret scalar `r' = r(`r')
+ }
+ foreach r in `:r(macros)' {
+ eret local `r' `"`r(`r')'"'
+ }
+ tempname tmp
+ foreach r in `:r(matrices)' {
+ if inlist("`r'", "b", "V") continue
+ mat `tmp' = r(`r')
+ eret matrix `r' = `tmp'
+ }
+end
+
+* 99.
+* copy of erepost.ado, version 1.0.1, Ben Jann, 30jul2007
+* 14jan2009: noV option added => repost e(b) and remove e(V) if not specified
+prog erepost, eclass
+ version 8.2
+ syntax [anything(equalok)] [, NOV cmd(str) noEsample Esample2(varname) REName ///
+ Obs(passthru) Dof(passthru) PROPerties(passthru) * ]
+ if "`esample'"!="" & "`esample2'"!="" {
+ di as err "only one allowed of noesample and esample()"
+ exit 198
+ }
+// parse [b = b] [V = V]
+ if `"`anything'"'!="" {
+ tokenize `"`anything'"', parse(" =")
+ if `"`7'"'!="" error 198
+ if `"`1'"'=="b" {
+ if `"`2'"'=="=" & `"`3'"'!="" {
+ local b `"`3'"'
+ confirm matrix `b'
+ }
+ else error 198
+ if `"`4'"'=="V" {
+ if `"`5'"'=="=" & `"`6'"'!="" {
+ local v `"`6'"'
+ confirm matrix `b'
+ }
+ else error 198
+ }
+ else if `"`4'"'!="" error 198
+ }
+ else if `"`1'"'=="V" {
+ if `"`4'"'!="" error 198
+ if `"`2'"'=="=" & `"`3'"'!="" {
+ local v `"`3'"'
+ confirm matrix `v'
+ }
+ else error 198
+ }
+ else error 198
+ }
+//backup existing e()'s
+ if "`esample2'"!="" {
+ local sample "`esample2'"
+ }
+ else if "`esample'"=="" {
+ tempvar sample
+ gen byte `sample' = e(sample)
+ }
+ local emacros: e(macros)
+ if `"`properties'"'!="" {
+ local emacros: subinstr local emacros "properties" "", word
+ }
+ foreach emacro of local emacros {
+ local e_`emacro' `"`e(`emacro')'"'
+ }
+ local escalars: e(scalars)
+ if `"`obs'"'!="" {
+ local escalars: subinstr local escalars "N" "", word
+ }
+ if `"`dof'"'!="" {
+ local escalars: subinstr local escalars "df_r" "", word
+ }
+ foreach escalar of local escalars {
+ tempname e_`escalar'
+ scalar `e_`escalar'' = e(`escalar')
+ }
+ local ematrices: e(matrices)
+ if "`v'"=="" & "`nov'"!="" { // added 14jan2009
+ local nov V
+ local ematrices : list ematrices - nov
+ }
+ if "`b'"=="" & `:list posof "b" in ematrices' {
+ tempname b
+ mat `b' = e(b)
+ }
+ if "`v'"=="" & `:list posof "V" in ematrices' {
+ tempname v
+ mat `v' = e(V)
+ }
+ local bV "b V"
+ local ematrices: list ematrices - bV
+ foreach ematrix of local ematrices {
+ tempname e_`ematrix'
+ matrix `e_`ematrix'' = e(`ematrix')
+ }
+// rename
+ if "`b'"!="" & "`v'"!="" & "`rename'"!="" {
+ local eqnames: coleq `b', q
+ local vnames: colnames `b'
+ mat coleq `v' = `eqnames'
+ mat coln `v' = `vnames'
+ mat roweq `v' = `eqnames'
+ mat rown `v' = `vnames'
+ }
+// post results
+ if "`esample'"=="" {
+ eret post `b' `v', esample(`sample') `obs' `dof' `properties' `options'
+ }
+ else {
+ eret post `b' `v', `obs' `dof' `properties' `options'
+ }
+ foreach emacro of local emacros {
+ eret local `emacro' `"`e_`emacro''"'
+ }
+ if `"`cmd'"'!="" {
+ eret local cmd `"`cmd'"'
+ }
+ foreach escalar of local escalars {
+ eret scalar `escalar' = scalar(`e_`escalar'')
+ }
+ foreach ematrix of local ematrices {
+ eret matrix `ematrix' = `e_`ematrix''
+ }
+end
diff --git a/Modules/ado/plus/e/estpost.hlp b/Modules/ado/plus/e/estpost.hlp
new file mode 100644
index 0000000..81454a6
--- /dev/null
+++ b/Modules/ado/plus/e/estpost.hlp
@@ -0,0 +1,1322 @@
+{smcl}
+{* 08oct2009}{...}
+{hi:help estpost}{right:also see: {helpb esttab}, {helpb estout}, {helpb eststo}, {helpb estadd}}
+{right: {browse "http://repec.org/bocode/e/estout"}}
+{hline}
+
+{title:Title}
+
+{p 4 4 2}{hi:estpost} {hline 2} Post results from various commands in {cmd:e()}
+
+
+{title:Syntax}
+
+{p 8 15 2}
+{cmd:estpost} {it:{help estpost##commands:command}} [...]
+
+{marker commands}
+ {it:command}{col 26}description
+ {hline 64}
+ {helpb estpost##summarize:{ul:su}mmarize}{col 26}{...}
+post summary statistics
+ {helpb estpost##tabstat:tabstat}{col 26}{...}
+post summary statistics
+ {helpb estpost##ttest:ttest}{col 26}{...}
+post two-group mean-comparison tests
+ {helpb estpost##prtest:prtest}{col 26}{...}
+post two-group tests of proportions
+ {helpb estpost##tabulate:{ul:ta}bulate}{col 26}{...}
+post one-way or two-way frequency table
+ {helpb estpost##svy_tabulate:svy: {ul:ta}bulate}{col 26}{...}
+post frequency table for survey data
+ {helpb estpost##correlate:{ul:cor}relate}{col 26}{...}
+post correlations
+ {helpb estpost##ci:ci}{col 26}{...}
+post confidence intervals for means,
+ {col 26}{...}
+ proportions, or counts
+ {helpb estpost##stci:stci}{col 26}{...}
+post confidence intervals for means
+ {col 26}{...}
+ and percentiles of survival time
+ {helpb estpost##margins:margins}{col 26}{...}
+post results from {cmd:margins} (Stata 11)
+ {hline 64}
+
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:estpost} posts results from various Stata commands in {cmd:e()}
+so that they can be tabulated using {helpb esttab} or {helpb estout}. Type
+{helpb ereturn:ereturn list} after {cmd:estpost} to list the elements saved
+in {cmd:e()}.
+
+
+{title:Commands}
+{marker summarize}
+{dlgtab:summarize}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:su:mmarize}
+ [{it:{help varlist}}] [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:d:etail}
+ {cmdab:mean:only}
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts summary statistics computed by {helpb summarize}. If no
+ {it:varlist} is specified, summary statistics are calculated for all
+ variables in the dataset.
+
+{p 4 4 2}
+ {cmd:aweight}s, {cmd:fweight}s, and {cmd:iweight}s are allowed
+ (however, {cmd:iweight}s may not be used with the {cmd:detail} option);
+ see {help weight}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:detail} and {cmd:meanonly} as described in help {helpb summarize}.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation
+ sample if any of the variables in {it:varlist} is missing for that
+ observation. The default is to determine the used observations for
+ each variable separately without regard to whether other variables
+ are missing. {cmd:casewise} is a synonym for {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following results vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(count)}}number of observations
+ {lalign 13:{cmd:e(mean)}}mean
+ {lalign 13:{cmd:e(min)}}minimum
+ {lalign 13:{cmd:e(max)}}maximum
+ {lalign 13:{cmd:e(sum)}}sum of variable
+ {lalign 13:{cmd:e(sum_w)}}sum of the weights
+ {lalign 13:{cmd:e(Var)}}variance (unless {cmd:meanonly})
+ {lalign 13:{cmd:e(sd)}}standard deviation (unless {cmd:meanonly})
+ {lalign 13:{cmd:e(p1)}}1st percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p5)}}5th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p10)}}10th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p25)}}25th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p50)}}50th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p75)}}75th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p90)}}90th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p95)}}95th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(p99)}}99th percentile ({cmd:detail} only)
+ {lalign 13:{cmd:e(skewness)}}skewness ({cmd:detail} only)
+ {lalign 13:{cmd:e(kurtosis)}}kurtosis ({cmd:detail} only)
+
+{p 4 4 2}
+ Example:
+
+{* begin example summarize }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost summarize price mpg rep78 foreign
+
+ {txt}{ralign 12:} {c |} {ralign 9:e(count)} {ralign 9:e(sum_w)} {ralign 9:e(mean)} {ralign 9:e(Var)} {ralign 9:e(sd)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 6165.257}}} {ralign 9:{res:{sf: 8699526}}} {ralign 9:{res:{sf: 2949.496}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 21.2973}}} {ralign 9:{res:{sf: 33.47205}}} {ralign 9:{res:{sf: 5.785503}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: 3.405797}}} {ralign 9:{res:{sf: .9799659}}} {ralign 9:{res:{sf: .9899323}}}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: .2972973}}} {ralign 9:{res:{sf: .2117734}}} {ralign 9:{res:{sf: .4601885}}}
+
+ {ralign 12:} {c |} {ralign 9:e(min)} {ralign 9:e(max)} {ralign 9:e(sum)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 3291}}} {ralign 9:{res:{sf: 15906}}} {ralign 9:{res:{sf: 456229}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 12}}} {ralign 9:{res:{sf: 41}}} {ralign 9:{res:{sf: 1576}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 5}}} {ralign 9:{res:{sf: 235}}}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 22}}}
+
+ {com}. esttab ., cells("mean sd count") noobs
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt}
+ {txt} mean sd count
+ {txt}{hline 51}
+ {txt}price {res} 6165.257 2949.496 74{txt}
+ {txt}mpg {res} 21.2973 5.785503 74{txt}
+ {txt}rep78 {res} 3.405797 .9899323 69{txt}
+ {txt}foreign {res} .2972973 .4601885 74{txt}
+ {txt}{hline 51}
+{* end example }{txt}{...}
+
+{marker tabstat}
+{dlgtab:tabstat}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:tabstat}
+ {it:{help varlist}} [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:s:tatistics:(}{it:{help tabstat##statname:statname}} [{it:...}]{cmd:)}
+ {cmdab:c:olumns:(}{cmdab:v:ariables}|{cmdab:s:tatistics:)}
+ {cmd:by(}{it:varname}{cmd:)}
+ {cmdab:not:otal}
+ {cmdab:m:issing}
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts summary statistics computed by {helpb tabstat}. {cmd:aweight}s and
+ {cmd:fweight}s are allowed; see {help weight}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:statistics()}, {cmd:columns()}, {cmd:by()}, {cmd:nototal},
+ and {cmd:missing} as described in help {helpb tabstat}.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation
+ sample if any of the variables in {it:varlist} is missing for that
+ observation. The default is to determine the used observations for
+ each variable separately without regard to whether other variables
+ are missing. {cmd:casewise} is a synonym for {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}A vector of results is saved in {cmd:e()} for each specified
+variable or statistic, depending on {cmd:columns()}.
+
+{p 4 4 2}
+ Examples:
+
+{* begin example tabstat }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost tabstat price mpg rep78, listwise ///
+ > statistics(mean sd)
+
+ {txt}Summary statistics: mean sd
+ for variables: price mpg rep78
+
+ {ralign 12:} {c |} {ralign 9:e(price)} {ralign 9:e(mpg)} {ralign 9:e(rep78)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}
+ {ralign 12:mean} {c |} {ralign 9:{res:{sf: 6146.043}}} {ralign 9:{res:{sf: 21.28986}}} {ralign 9:{res:{sf: 3.405797}}}
+ {ralign 12:sd} {c |} {ralign 9:{res:{sf: 2912.44}}} {ralign 9:{res:{sf: 5.866408}}} {ralign 9:{res:{sf: .9899323}}}
+
+ {com}. esttab ., cells("price mpg rep78")
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt}
+ {txt} price mpg rep78
+ {txt}{hline 51}
+ {txt}mean {res} 6146.043 21.28986 3.405797{txt}
+ {txt}sd {res} 2912.44 5.866408 .9899323{txt}
+ {txt}{hline 51}
+ {txt}N {res} 69 {txt}
+ {txt}{hline 51}
+
+ {com}. estpost tabstat price mpg rep78, listwise ///
+ > statistics(mean sd) columns(statistics)
+
+ {txt}Summary statistics: mean sd
+ for variables: price mpg rep78
+
+ {ralign 12:} {c |} {ralign 9:e(mean)} {ralign 9:e(sd)}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 6146.043}}} {ralign 9:{res:{sf: 2912.44}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 21.28986}}} {ralign 9:{res:{sf: 5.866408}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 3.405797}}} {ralign 9:{res:{sf: .9899323}}}
+
+ {com}. esttab ., cells("mean(fmt(a3)) sd")
+ {res}
+ {txt}{hline 38}
+ {txt} (1)
+ {txt}
+ {txt} mean sd
+ {txt}{hline 38}
+ {txt}price {res} 6146.0 2912.4{txt}
+ {txt}mpg {res} 21.29 5.866{txt}
+ {txt}rep78 {res} 3.406 0.990{txt}
+ {txt}{hline 38}
+ {txt}N {res} 69 {txt}
+ {txt}{hline 38}
+
+ {com}. estpost tabstat price mpg rep78, by(foreign) ///
+ > statistics(mean sd) columns(statistics) listwise
+
+ {txt}Summary statistics: mean sd
+ for variables: price mpg rep78
+ by categories of: foreign
+
+ {ralign 12:foreign} {c |} {ralign 9:e(mean)} {ralign 9:e(sd)}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {res:{lalign 13:Domestic}}{c |}{space 11}{space 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 6179.25}}} {ralign 9:{res:{sf: 3188.969}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 19.54167}}} {ralign 9:{res:{sf: 4.753312}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 3.020833}}} {ralign 9:{res:{sf: .837666}}}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {res:{lalign 13:Foreign}}{c |}{space 11}{space 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 6070.143}}} {ralign 9:{res:{sf: 2220.984}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 25.28571}}} {ralign 9:{res:{sf: 6.309856}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 4.285714}}} {ralign 9:{res:{sf: .7171372}}}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {res:{lalign 13:Total}}{c |}{space 11}{space 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 6146.043}}} {ralign 9:{res:{sf: 2912.44}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 21.28986}}} {ralign 9:{res:{sf: 5.866408}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 3.405797}}} {ralign 9:{res:{sf: .9899323}}}
+
+ {com}. esttab ., main(mean) aux(sd) nostar unstack ///
+ > noobs nonote label
+ {res}
+ {txt}{hline 59}
+ {txt} (1)
+ {txt}
+ {txt} Domestic Foreign Total
+ {txt}{hline 59}
+ {txt}Price {res} 6179.3 6070.1 6146.0{txt}
+ {res} {ralign 12:{txt:(}3189.0{txt:)}} {ralign 12:{txt:(}2221.0{txt:)}} {ralign 12:{txt:(}2912.4{txt:)}}{txt}
+
+ {txt}Mileage (mpg) {res} 19.54 25.29 21.29{txt}
+ {res} {ralign 12:{txt:(}4.753{txt:)}} {ralign 12:{txt:(}6.310{txt:)}} {ralign 12:{txt:(}5.866{txt:)}}{txt}
+
+ {txt}Repair Record 1978 {res} 3.021 4.286 3.406{txt}
+ {res} {ralign 12:{txt:(}0.838{txt:)}} {ralign 12:{txt:(}0.717{txt:)}} {ralign 12:{txt:(}0.990{txt:)}}{txt}
+ {txt}{hline 59}
+{* end example }{txt}{...}
+
+{marker ttest}
+{dlgtab:ttest}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:ttest}
+ {it:{help varlist}} [{it:{help if}}] [{it:{help in}}]{cmd:,}
+ {cmd:by(}{it:groupvar}{cmd:)}
+ [
+ {cmdab:une:qual} {cmdab:w:elch}
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts two-group mean-comparison tests computed by {helpb ttest}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:by()}, {cmd:unequal}, and {cmd:welch} as described in
+ help {helpb ttest}.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation
+ sample if any of the variables in {it:varlist} is missing for that
+ observation. The default is to determine the used observations for
+ each variable separately without regard to whether other variables
+ are missing. {cmd:casewise} is a synonym for {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following results vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(b)}}mean difference
+ {lalign 13:{cmd:e(count)}}number of observations
+ {lalign 13:{cmd:e(se)}}standard error of difference
+ {lalign 13:{cmd:e(t)}}t statistic
+ {lalign 13:{cmd:e(df_t)}}degrees of freedom
+ {lalign 13:{cmd:e(p_l)}}lower one-sided p-value
+ {lalign 13:{cmd:e(p)}}two-sided p-value
+ {lalign 13:{cmd:e(p_u)}}upper one-sided p-value
+ {lalign 13:{cmd:e(N_1)}}number of observations in group 1
+ {lalign 13:{cmd:e(mu_1)}}mean in group 1
+ {lalign 13:{cmd:e(N_2)}}number of observations in group 2
+ {lalign 13:{cmd:e(mu_2)}}mean in group 2
+
+{p 4 4 2}
+ Example:
+
+{* begin example ttest }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost ttest price mpg headroom trunk, by(foreign)
+
+ {txt}{ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(count)} {ralign 9:e(se)} {ralign 9:e(t)} {ralign 9:e(df_t)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf:-312.2587}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 754.4488}}} {ralign 9:{res:{sf:-.4138899}}} {ralign 9:{res:{sf: 72}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf:-4.945804}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 1.362162}}} {ralign 9:{res:{sf:-3.630848}}} {ralign 9:{res:{sf: 72}}}
+ {ralign 12:headroom} {c |} {ralign 9:{res:{sf: .5402098}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: .2070884}}} {ralign 9:{res:{sf: 2.608596}}} {ralign 9:{res:{sf: 72}}}
+ {ralign 12:trunk} {c |} {ralign 9:{res:{sf: 3.340909}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 1.022208}}} {ralign 9:{res:{sf: 3.268327}}} {ralign 9:{res:{sf: 72}}}
+
+ {ralign 12:} {c |} {ralign 9:e(p_l)} {ralign 9:e(p)} {ralign 9:e(p_u)} {ralign 9:e(N_1)} {ralign 9:e(mu_1)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: .3400925}}} {ralign 9:{res:{sf: .6801851}}} {ralign 9:{res:{sf: .6599075}}} {ralign 9:{res:{sf: 52}}} {ralign 9:{res:{sf: 6072.423}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: .0002627}}} {ralign 9:{res:{sf: .0005254}}} {ralign 9:{res:{sf: .9997373}}} {ralign 9:{res:{sf: 52}}} {ralign 9:{res:{sf: 19.82692}}}
+ {ralign 12:headroom} {c |} {ralign 9:{res:{sf: .9944757}}} {ralign 9:{res:{sf: .0110486}}} {ralign 9:{res:{sf: .0055243}}} {ralign 9:{res:{sf: 52}}} {ralign 9:{res:{sf: 3.153846}}}
+ {ralign 12:trunk} {c |} {ralign 9:{res:{sf: .99917}}} {ralign 9:{res:{sf: .00166}}} {ralign 9:{res:{sf: .00083}}} {ralign 9:{res:{sf: 52}}} {ralign 9:{res:{sf: 14.75}}}
+
+ {ralign 12:} {c |} {ralign 9:e(N_2)} {ralign 9:e(mu_2)}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 22}}} {ralign 9:{res:{sf: 6384.682}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 22}}} {ralign 9:{res:{sf: 24.77273}}}
+ {ralign 12:headroom} {c |} {ralign 9:{res:{sf: 22}}} {ralign 9:{res:{sf: 2.613636}}}
+ {ralign 12:trunk} {c |} {ralign 9:{res:{sf: 22}}} {ralign 9:{res:{sf: 11.40909}}}
+
+ {com}. esttab ., wide
+ {res}
+ {txt}{hline 41}
+ {txt} (1)
+ {txt}
+ {txt}{hline 41}
+ {txt}price {res} -312.3 {ralign 12:{txt:(}-0.41{txt:)}}{txt}
+ {txt}mpg {res} -4.946*** {ralign 12:{txt:(}-3.63{txt:)}}{txt}
+ {txt}headroom {res} 0.540* {ralign 12:{txt:(}2.61{txt:)}}{txt}
+ {txt}trunk {res} 3.341** {ralign 12:{txt:(}3.27{txt:)}}{txt}
+ {txt}{hline 41}
+ {txt}N {res} 74 {txt}
+ {txt}{hline 41}
+ {txt}t statistics in parentheses
+ {txt}* p<0.05, ** p<0.01, *** p<0.001
+{* end example }{txt}{...}
+
+{marker prtest}
+{dlgtab:prtest}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:prtest}
+ {it:{help varlist}} [{it:{help if}}] [{it:{help in}}]{cmd:,}
+ {cmd:by(}{it:groupvar}{cmd:)}
+ [
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts two-group tests of proportions computed by {helpb prtest}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:by()} as described in
+ help {helpb prtest}.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation
+ sample if any of the variables in {it:varlist} is missing for that
+ observation. The default is to determine the used observations for
+ each variable separately without regard to whether other variables
+ are missing. {cmd:casewise} is a synonym for {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following results vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(b)}}difference in proportions
+ {lalign 13:{cmd:e(count)}}number of observations
+ {lalign 13:{cmd:e(se)}}standard error of difference
+ {lalign 13:{cmd:e(se0)}}standard error under Ho
+ {lalign 13:{cmd:e(z)}}z statistic
+ {lalign 13:{cmd:e(p_l)}}lower one-sided p-value
+ {lalign 13:{cmd:e(p)}}two-sided p-value
+ {lalign 13:{cmd:e(p_u)}}upper one-sided p-value
+ {lalign 13:{cmd:e(N_1)}}number of observations in group 1
+ {lalign 13:{cmd:e(P_1)}}proportion in group 1
+ {lalign 13:{cmd:e(N_2)}}number of observations in group 2
+ {lalign 13:{cmd:e(P_2)}}proportion in group 2
+
+{p 4 4 2}
+ Example:
+
+{* begin example prtest }{...}
+ {com}. webuse cure2, clear
+ {txt}
+ {com}. estpost prtest cure, by(sex)
+
+ {txt}{ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(count)} {ralign 9:e(se)} {ralign 9:e(se0)} {ralign 9:e(z)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:cure} {c |} {ralign 9:{res:{sf:-.0729167}}} {ralign 9:{res:{sf: 109}}} {ralign 9:{res:{sf: .0933123}}} {ralign 9:{res:{sf: .0942404}}} {ralign 9:{res:{sf:-.7737309}}}
+
+ {ralign 12:} {c |} {ralign 9:e(p_l)} {ralign 9:e(p)} {ralign 9:e(p_u)} {ralign 9:e(N_1)} {ralign 9:e(P_1)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:cure} {c |} {ralign 9:{res:{sf: .219545}}} {ralign 9:{res:{sf: .43909}}} {ralign 9:{res:{sf: .780455}}} {ralign 9:{res:{sf: 64}}} {ralign 9:{res:{sf: .59375}}}
+
+ {ralign 12:} {c |} {ralign 9:e(N_2)} {ralign 9:e(P_2)}
+ {hline 13}{c +}{hline 11}{hline 11}
+ {ralign 12:cure} {c |} {ralign 9:{res:{sf: 45}}} {ralign 9:{res:{sf: .6666667}}}
+
+ {com}. esttab ., cell("b se0 z p")
+ {res}
+ {txt}{hline 64}
+ {txt} (1)
+ {txt}
+ {txt} b se0 z p
+ {txt}{hline 64}
+ {txt}cure {res} -.0729167 .0942404 -.7737309 .43909{txt}
+ {txt}{hline 64}
+ {txt}N {res} 109 {txt}
+ {txt}{hline 64}
+{* end example }{txt}{...}
+
+{marker tabulate}
+{dlgtab:tabulate}
+
+{p 4 4 2}One-way table:
+
+{p 8 15 2}
+{cmd:estpost} {cmdab:ta:bulate}
+ {it:varname} [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:m:issing}
+ {cmdab:nol:abel}
+ {cmd:sort}
+ {cmd:subpop(}{it:varname}{cmd:)}
+ {cmdab:notot:al}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}Two-way table:
+
+{p 8 15 2}
+{cmd:estpost} {cmdab:ta:bulate}
+ {it:varname1} {it:varname2} [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:m:issing}
+ {cmdab:nol:abel}
+ {cmdab:ch:i2}
+ {cmdab:e:xact}[{cmd:(}{it:#}{cmd:)}]
+ {cmdab:g:amma}
+ {cmdab:lr:chi2}
+ {cmdab:t:aub}
+ {cmdab:v}
+ {cmdab:notot:al}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ {cmd:estpost tabulate} posts a one-way or two-way table
+ computed by {helpb tabulate}. {cmd:aweight}s, {cmd:fweight}s,
+ and {cmd:iweight}s are allowed; see {help weight}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:missing},
+ {cmd:nolabel},
+ {cmd:sort},
+ {cmd:subpop()},
+ {cmd:chi2},
+ {cmd:exact},
+ {cmd:gamma},
+ {cmd:lrchi2},
+ {cmd:taub}, and
+ {cmd:v}
+ as described in help {helpb tabulate}.
+
+{p 8 12 2}
+ {cmdab:nototal} to omit row and column totals.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(b)}}frequency counts
+ {lalign 13:{cmd:e(pct)}}percent
+ {lalign 13:{cmd:e(cumpct)}}cumulative percent (one-way only)
+ {lalign 13:{cmd:e(colpct)}}column percent (two-way only)
+ {lalign 13:{cmd:e(rowpct)}}row percent (two-way only)
+
+{p 4 4 2}If two-way options such as, e.g., {cmd:chi2} or {cmd:exact} are
+specified, the results of the tests added as scalars in {cmd:e()} using the
+names documented in {helpb tabulate:{bind:[R] tabulate}}.
+
+{p 4 4 2}The value labels of the row variable are stored as names in the
+saved vectors, unless
+no label exceeds 30 characters or contains unsuitable characters in which case
+the labels are stored in macro {cmd:e(labels)}. Type
+{cmd:varlabels(`e(labels)')} in {helpb esttab} or {helpb estout} to
+use the labels stored {cmd:e(labels)}. The value labels of the column variable
+are stored as equation names or, alternatively,
+in macro {cmd:e(eqlabels)}. Type {cmd:eqlabels(`e(eqlabels)')} in
+{helpb esttab} or {helpb estout} to use the labels stored in {cmd:e(eqlabels)}.
+
+{p 4 4 2}Examples:
+
+{* begin example tabulate }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost tabulate foreign
+
+ {txt}{ralign 12:foreign} {c |} {ralign 9:e(b)} {ralign 9:e(pct)} {ralign 9:e(cumpct)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}
+ {ralign 12:Domestic} {c |} {ralign 9:{res:{sf: 52}}} {ralign 9:{res:{sf: 70.27027}}} {ralign 9:{res:{sf: 70.27027}}}
+ {ralign 12:Foreign} {c |} {ralign 9:{res:{sf: 22}}} {ralign 9:{res:{sf: 29.72973}}} {ralign 9:{res:{sf: 100}}}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}
+ {ralign 12:Total} {c |} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: 100}}} {ralign 9:{res:{sf:{space 9}}}}
+
+ {com}. esttab ., cells("b pct(fmt(2)) cumpct(fmt(2))") noobs
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt} foreign
+ {txt} b pct cumpct
+ {txt}{hline 51}
+ {txt}Domestic {res} 52 70.27 70.27{txt}
+ {txt}Foreign {res} 22 29.73 100.00{txt}
+ {txt}Total {res} 74 100.00 {txt}
+ {txt}{hline 51}
+
+ {com}. estpost tabulate rep78 foreign
+
+ {res}foreign {txt} {c |}{space 44}
+ {ralign 12:rep78} {c |} {ralign 9:e(b)} {ralign 9:e(pct)} {ralign 9:e(colpct)} {ralign 9:e(rowpct)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {res:{lalign 13:Domestic}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:1} {c |} {ralign 9:{res:{sf: 2}}} {ralign 9:{res:{sf: 2.898551}}} {ralign 9:{res:{sf: 4.166667}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:2} {c |} {ralign 9:{res:{sf: 8}}} {ralign 9:{res:{sf: 11.5942}}} {ralign 9:{res:{sf: 16.66667}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:3} {c |} {ralign 9:{res:{sf: 27}}} {ralign 9:{res:{sf: 39.13043}}} {ralign 9:{res:{sf: 56.25}}} {ralign 9:{res:{sf: 90}}}
+ {ralign 12:4} {c |} {ralign 9:{res:{sf: 9}}} {ralign 9:{res:{sf: 13.04348}}} {ralign 9:{res:{sf: 18.75}}} {ralign 9:{res:{sf: 50}}}
+ {ralign 12:5} {c |} {ralign 9:{res:{sf: 2}}} {ralign 9:{res:{sf: 2.898551}}} {ralign 9:{res:{sf: 4.166667}}} {ralign 9:{res:{sf: 18.18182}}}
+ {ralign 12:Total} {c |} {ralign 9:{res:{sf: 48}}} {ralign 9:{res:{sf: 69.56522}}} {ralign 9:{res:{sf: 100}}} {ralign 9:{res:{sf: 69.56522}}}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {res:{lalign 13:Foreign}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:1} {c |} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}}
+ {ralign 12:2} {c |} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}} {ralign 9:{res:{sf: 0}}}
+ {ralign 12:3} {c |} {ralign 9:{res:{sf: 3}}} {ralign 9:{res:{sf: 4.347826}}} {ralign 9:{res:{sf: 14.28571}}} {ralign 9:{res:{sf: 10}}}
+ {ralign 12:4} {c |} {ralign 9:{res:{sf: 9}}} {ralign 9:{res:{sf: 13.04348}}} {ralign 9:{res:{sf: 42.85714}}} {ralign 9:{res:{sf: 50}}}
+ {ralign 12:5} {c |} {ralign 9:{res:{sf: 9}}} {ralign 9:{res:{sf: 13.04348}}} {ralign 9:{res:{sf: 42.85714}}} {ralign 9:{res:{sf: 81.81818}}}
+ {ralign 12:Total} {c |} {ralign 9:{res:{sf: 21}}} {ralign 9:{res:{sf: 30.43478}}} {ralign 9:{res:{sf: 100}}} {ralign 9:{res:{sf: 30.43478}}}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {res:{lalign 13:Total}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:1} {c |} {ralign 9:{res:{sf: 2}}} {ralign 9:{res:{sf: 2.898551}}} {ralign 9:{res:{sf: 2.898551}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:2} {c |} {ralign 9:{res:{sf: 8}}} {ralign 9:{res:{sf: 11.5942}}} {ralign 9:{res:{sf: 11.5942}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:3} {c |} {ralign 9:{res:{sf: 30}}} {ralign 9:{res:{sf: 43.47826}}} {ralign 9:{res:{sf: 43.47826}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:4} {c |} {ralign 9:{res:{sf: 18}}} {ralign 9:{res:{sf: 26.08696}}} {ralign 9:{res:{sf: 26.08696}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:5} {c |} {ralign 9:{res:{sf: 11}}} {ralign 9:{res:{sf: 15.94203}}} {ralign 9:{res:{sf: 15.94203}}} {ralign 9:{res:{sf: 100}}}
+ {ralign 12:Total} {c |} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: 100}}} {ralign 9:{res:{sf: 100}}} {ralign 9:{res:{sf: 100}}}
+
+ {com}. esttab ., cell(colpct(fmt(2))) unstack noobs
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt}
+ {txt} Domestic Foreign Total
+ {txt} colpct colpct colpct
+ {txt}{hline 51}
+ {txt}1 {res} 4.17 0.00 2.90{txt}
+ {txt}2 {res} 16.67 0.00 11.59{txt}
+ {txt}3 {res} 56.25 14.29 43.48{txt}
+ {txt}4 {res} 18.75 42.86 26.09{txt}
+ {txt}5 {res} 4.17 42.86 15.94{txt}
+ {txt}Total {res} 100.00 100.00 100.00{txt}
+ {txt}{hline 51}
+
+ {com}. esttab ., cell(colpct(fmt(2)) count(fmt(g) par keep(Total))) ///
+ > collabels(none) unstack noobs nonumber nomtitle ///
+ > eqlabels(, lhs("Repair Rec.")) ///
+ > varlabels(, blist(Total "{c -(}hline @width{c )-}{c -(}break{c )-}"))
+ {res}
+ {txt}{hline 51}
+ {txt}Repair Rec. Domestic Foreign Total
+ {txt}{hline 51}
+ {txt}1 {res} 4.17 0.00 2.90{txt}
+ {txt}2 {res} 16.67 0.00 11.59{txt}
+ {txt}3 {res} 56.25 14.29 43.48{txt}
+ {txt}4 {res} 18.75 42.86 26.09{txt}
+ {txt}5 {res} 4.17 42.86 15.94{txt}
+ {txt}{hline 51}{break} Total {res} 100.00 100.00 100.00{txt}
+ {res} {txt}
+ {txt}{hline 51}
+{* end example }{txt}{...}
+
+{marker svy_tabulate}
+{dlgtab:svy: tabulate}
+
+{p 4 4 2}One-way table:
+
+{p 8 15 2}
+{cmd:estpost} {cmd:svy} [{it:vcetype}] [, {it:svy_options}] {cmd::} {cmdab:ta:bulate}
+ {it:varname} [{it:{help if}}] [{it:{help in}}]
+ [{cmd:,}
+ {cmdab:notot:al}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ {help svy_tabulate_oneway:{it:svy_tabulate_opts}}
+ ]
+
+{p 4 4 2}Two-way table:
+
+{p 8 15 2}
+{cmd:estpost} {cmd:svy} [{it:vcetype}] [, {it:svy_options}] {cmd::} {cmdab:ta:bulate}
+ {it:varname1} {it:varname2} [{it:{help if}}] [{it:{help in}}]
+ [{cmd:,}
+ {cmdab:notot:al}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ {help svy_tabulate_oneway:{it:svy_tabulate_opts}}
+ ]
+
+{p 4 4 2}
+ {cmd:estpost svy: tabulate} posts a one-way or two-way table
+ for complex survey data computed by {helpb svy_tabulate:svy: tabulate}. Stata 9 or newer
+ is required.
+
+{p 4 4 2}
+ Options are as described in {helpb svy_tabulate_oneway:[SVY] svy: tabulate oneway} or
+ {helpb svy_tabulate_twoway:[SVY] svy: tabulate twoway}, respectively, and:
+
+{p 8 12 2}
+ {cmdab:nototal} to omit row and column totals (synonym for {cmd:nomarginals}).
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}{cmd:estpost svy: tabulate} posts results in {cmd:e()} (except {cmd:e(V)})
+as documented in {helpb svy_tabulate_oneway:[SVY] svy: tabulate oneway} and
+{helpb svy_tabulate_twoway:[SVY] svy: tabulate twoway}, respectively,
+and adds or replaces the following matrices:
+
+ {lalign 10:{cmd:e(b)}}cell, column, or row proportions or percentages,
+ or weighted counts, depending on options
+ {lalign 10:{cmd:e(se)}}standard errors of {cmd:e(b)}
+ {lalign 10:{cmd:e(lb)}}lower confidence bounds for {cmd:e(b)}
+ {lalign 10:{cmd:e(ub)}}upper confidence bounds for {cmd:e(b)}
+ {lalign 10:{cmd:e(deff)}}deff for variances of {cmd:e(b)}
+ {lalign 10:{cmd:e(deft)}}deft for variances of {cmd:e(b)}
+ {lalign 10:{cmd:e(cell)}}cell proportion or percentages
+ {lalign 10:{cmd:e(row)}}row proportion or percentages (two-way only)
+ {lalign 10:{cmd:e(col)}}column proportion or percentages (two-way only)
+ {lalign 10:{cmd:e(count)}}weighted counts
+ {lalign 10:{cmd:e(obs)}}number of observations
+
+{p 4 4 2}The value labels of the row variable are stored as names in the
+saved vectors, unless
+no label exceeds 30 characters or contains unsuitable characters in which case
+the labels are stored in macro {cmd:e(labels)}. Type
+{cmd:varlabels(`e(labels)')} in {helpb esttab} or {helpb estout} to
+use the labels stored {cmd:e(labels)}. The value labels of the column variable
+are stored as equation names or, alternatively,
+in macro {cmd:e(eqlabels)}. Type {cmd:eqlabels(`e(eqlabels)')} in
+{helpb esttab} or {helpb estout} to use the labels stored in {cmd:e(eqlabels)}.
+
+{p 4 4 2}Examples:
+
+{* begin example svy_tabulate }{...}
+ {com}. webuse nhanes2b, clear
+ {txt}
+ {com}. svyset psuid [pweight=finalwgt], strata(stratid)
+
+ {txt}pweight:{col 16}{res}finalwgt
+ {txt}VCE:{col 16}{res}linearized
+ {txt}Single unit:{col 16}{res}missing
+ {txt}Strata 1:{col 16}{res}stratid
+ {txt}SU 1:{col 16}{res}psuid
+ {txt}FPC 1:{col 16}
+ {p2colreset}{...}
+
+ {com}. estpost svy: tabulate race
+ {txt}(running tabulate on estimation sample)
+
+ {col 1}Number of strata{col 20}= {res} 31{txt}{col 48}Number of obs{col 67}= {res} 10351
+ {txt}{col 1}Number of PSUs{col 20}= {res} 62{txt}{col 48}Population size{col 67}={res} 117157513
+ {txt}{col 48}Design df{col 67}= {res} 31
+
+ {txt}{hline 10}{c TT}{hline 12}
+ 1=white, {c |}
+ 2=black, {c |}
+ 3=other {c |} proportions
+ {hline 10}{c +}{hline 12}
+ White {c |} {res}.8792
+ {txt}Black {c |} {res}.0955
+ {txt}Other {c |} {res}.0253
+ {txt}{c |}
+ Total {c |} {res}1
+ {txt}{hline 10}{c BT}{hline 12}
+ Key: {col 1}proportions = {res}cell proportions
+
+ {txt}saved vectors:
+ e(b) = {res}cell proportions
+ {txt}e(se) = {res}standard errors of cell proportions
+ {txt}e(lb) = {res}lower 95% confidence bounds for cell proportions
+ {txt}e(ub) = {res}upper 95% confidence bounds for cell proportions
+ {txt}e(deff) = {res}deff for variances of cell proportions
+ {txt}e(deft) = {res}deft for variances of cell proportions
+ {txt}e(cell) = {res}cell proportions
+ {txt}e(count) = {res}weighted counts
+ {txt}e(obs) = {res}number of observations
+ {txt}
+ {com}. esttab ., cell("b(f(4)) se deft")
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt}
+ {txt} b se deft
+ {txt}{hline 51}
+ {txt}White {res} 0.8792 0.0167 5.2090{txt}
+ {txt}Black {res} 0.0955 0.0127 4.4130{txt}
+ {txt}Other {res} 0.0253 0.0105 6.8246{txt}
+ {txt}Total {res} 1.0000 0.0000 {txt}
+ {txt}{hline 51}
+ {txt}N {res} 10351 {txt}
+ {txt}{hline 51}
+
+ {com}. estpost svy: tabulate race diabetes, row percent
+ {txt}(running tabulate on estimation sample)
+
+ {col 1}Number of strata{col 20}= {res} 31{txt}{col 48}Number of obs{col 67}= {res} 10349
+ {txt}{col 1}Number of PSUs{col 20}= {res} 62{txt}{col 48}Population size{col 67}={res} 117131111
+ {txt}{col 48}Design df{col 67}= {res} 31
+
+ {txt}{hline 10}{c TT}{hline 20}
+ 1=white, {c |} diabetes, 1=yes,
+ 2=black, {c |} 0=no
+ 3=other {c |} 0 1 Total
+ {hline 10}{c +}{hline 20}
+ White {c |} {res}96.8 3.195 100
+ {txt}Black {c |} {res}94.1 5.903 100
+ {txt}Other {c |} {res}97.97 2.034 100
+ {txt}{c |}
+ Total {c |} {res}96.58 3.425 100
+ {txt}{hline 10}{c BT}{hline 20}
+ Key: {col 1}{res}row percentages
+
+ {txt} Pearson:
+ {col 5}Uncorrected{col 19}chi2({res}2{txt}){col 35}= {res} 21.3483
+ {txt}{col 5}Design-based{col 19}F({res}1.52{txt}, {res}47.26{txt}){col 35}= {res} 15.0056{col 51}{txt}P = {res}0.0000
+
+ {txt}saved vectors:
+ e(b) = {res}row percentages
+ {txt}e(se) = {res}standard errors of row percentages
+ {txt}e(lb) = {res}lower 95% confidence bounds for row percentages
+ {txt}e(ub) = {res}upper 95% confidence bounds for row percentages
+ {txt}e(deff) = {res}deff for variances of row percentages
+ {txt}e(deft) = {res}deft for variances of row percentages
+ {txt}e(cell) = {res}cell percentages
+ {txt}e(row) = {res}row percentages
+ {txt}e(col) = {res}column percentages
+ {txt}e(count) = {res}weighted counts
+ {txt}e(obs) = {res}number of observations
+ {txt}
+ {com}. esttab ., b(2) se(2) scalars(F_Pear) nostar unstack ///
+ > mtitle(`e(colvar)')
+ {res}
+ {txt}{hline 51}
+ {txt} (1)
+ {txt} diabetes
+ {txt} 0 1 Total
+ {txt}{hline 51}
+ {txt}White {res} 96.80 3.20 100.00{txt}
+ {res} {ralign 12:{txt:(}0.20{txt:)}} {ralign 12:{txt:(}0.20{txt:)}} {txt}
+
+ {txt}Black {res} 94.10 5.90 100.00{txt}
+ {res} {ralign 12:{txt:(}0.61{txt:)}} {ralign 12:{txt:(}0.61{txt:)}} {txt}
+
+ {txt}Other {res} 97.97 2.03 100.00{txt}
+ {res} {ralign 12:{txt:(}0.76{txt:)}} {ralign 12:{txt:(}0.76{txt:)}} {txt}
+
+ {txt}Total {res} 96.58 3.42 100.00{txt}
+ {res} {ralign 12:{txt:(}0.18{txt:)}} {ralign 12:{txt:(}0.18{txt:)}} {txt}
+ {txt}{hline 51}
+ {txt}N {res} 10349 {txt}
+ {txt}F_Pear {res} 15.01 {txt}
+ {txt}{hline 51}
+ {txt}Standard errors in parentheses
+{* end example }{txt}{...}
+
+{marker correlate}
+{dlgtab:correlate}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:cor:relate}
+ {it:{help varlist}} [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:m:atrix}
+ {cmdab:noh:alf}
+ {cmdab:print:(}{it:#}{cmd:)}
+ {cmdab:b:onferroni}
+ {cmdab:sid:ak}
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts the pairwise correlations between the first variable in
+ {it:varlist} and the remaining variables. Alternatively, if the
+ {cmd:matrix} option is specified, all pairwise correlations among the
+ variable in {it:varlist} are posted.
+
+{p 4 4 2}
+ {cmd:aweight}s, {cmd:fweight}s,
+ {cmd:iweight}s and {cmd:pweight}s are allowed; see {help weight}.
+
+{p 4 4 2}
+ Methods and formulas are as described in
+ {helpb correlate:{bind:[R] correlate}}. However, if {cmd:pweight}s
+ are specified, the p-values of the correlations are computed
+ as suggested in the Stata FAQ on
+ {browse "http://www.stata.com/support/faqs/stat/survey.html":"Estimating correlations with survey data"}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:matrix} to return the (lower triangle) of the correlation
+ matrix of the variables in {it:varlist}. The default is to return
+ the pairwise correlations between the first variable in
+ {it:varlist} and the remaining variables.
+
+{p 8 12 2}
+ {cmd:nohalf} to return the full correlation matrix rather than just
+ the lower triangle. {cmd:nohalf} has no effect unless {cmd:matrix}
+ is specified.
+
+{p 8 12 2}
+ {cmd:print(}{it:#}{cmd:)} to suppress (leave blank)
+ correlation coefficients with a p-value larger than
+ {it:#}. {cmd:print()} only affects what is saved in
+ {cmd:e(rho)}, {cmd:e(p)}, and {cmd:e(count)}, but
+ not what is saved in {cmd:e(b)}.
+
+{p 8 12 2}
+ {cmd:bonferroni} to apply the Bonferroni adjustment to the
+ p-values.
+
+{p 8 12 2}
+ {cmd:sidak} to apply the Sidak adjustment to the
+ p-values.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation sample
+ if any of the variables in {it:varlist} is missing for that
+ observation. The default is to handle missing values by pairwise
+ deletion, i.e. all available observations are used to calculate a
+ pairwise correlation without regard to whether variables outside
+ that pair are missing. {cmd:casewise} is a synonym for
+ {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(b)}}correlation coefficients
+ {lalign 13:{cmd:e(rho)}}correlation coefficients
+ {lalign 13:{cmd:e(p)}}p-values
+ {lalign 13:{cmd:e(count)}}number of observations
+
+{p 4 4 2}Examples:
+
+{* begin example correlate }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost correlate price mpg turn foreign, matrix
+
+ {txt}{ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(rho)} {ralign 9:e(p)} {ralign 9:e(count)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {res:{lalign 13:price}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf:{space 9}}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf:-.4685967}}} {ralign 9:{res:{sf:-.4685967}}} {ralign 9:{res:{sf: .0000255}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:turn} {c |} {ralign 9:{res:{sf: .3096174}}} {ralign 9:{res:{sf: .3096174}}} {ralign 9:{res:{sf: .0072662}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: .0487195}}} {ralign 9:{res:{sf: .0487195}}} {ralign 9:{res:{sf: .6801851}}} {ralign 9:{res:{sf: 74}}}
+ {res:{lalign 13:mpg}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf:{space 9}}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:turn} {c |} {ralign 9:{res:{sf:-.7191863}}} {ralign 9:{res:{sf:-.7191863}}} {ralign 9:{res:{sf: 5.30e-13}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: .3933974}}} {ralign 9:{res:{sf: .3933974}}} {ralign 9:{res:{sf: .0005254}}} {ralign 9:{res:{sf: 74}}}
+ {res:{lalign 13:turn}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:turn} {c |} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf:{space 9}}}} {ralign 9:{res:{sf: 74}}}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf:-.6310965}}} {ralign 9:{res:{sf:-.6310965}}} {ralign 9:{res:{sf: 1.66e-09}}} {ralign 9:{res:{sf: 74}}}
+ {res:{lalign 13:foreign}}{c |}{space 11}{space 11}{space 11}{space 11}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf: 1}}} {ralign 9:{res:{sf:{space 9}}}} {ralign 9:{res:{sf: 74}}}
+
+ {com}. esttab ., not unstack compress noobs
+ {res}
+ {txt}{hline 62}
+ {txt} (1)
+ {txt}
+ {txt} price mpg turn foreign
+ {txt}{hline 62}
+ {txt}price {res} 1 {txt}
+ {txt}mpg {res} -0.469*** 1 {txt}
+ {txt}turn {res} 0.310** -0.719*** 1 {txt}
+ {txt}foreign {res} 0.0487 0.393*** -0.631*** 1 {txt}
+ {txt}{hline 62}
+ {txt}* p<0.05, ** p<0.01, *** p<0.001
+
+ {com}. bysort foreign: eststo: ///
+ > estpost correlate price turn weight rep78, listwise
+
+ {txt}{hline 60}
+ -> Domestic
+
+ {ralign 12:price} {c |} {ralign 9:e(b)} {ralign 9:e(rho)} {ralign 9:e(p)} {ralign 9:e(count)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:turn} {c |} {ralign 9:{res:{sf: .4328091}}} {ralign 9:{res:{sf: .4328091}}} {ralign 9:{res:{sf: .0021229}}} {ralign 9:{res:{sf: 48}}}
+ {ralign 12:weight} {c |} {ralign 9:{res:{sf: .6864719}}} {ralign 9:{res:{sf: .6864719}}} {ralign 9:{res:{sf: 7.19e-08}}} {ralign 9:{res:{sf: 48}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf:-.0193249}}} {ralign 9:{res:{sf:-.0193249}}} {ralign 9:{res:{sf: .8962741}}} {ralign 9:{res:{sf: 48}}}
+ ({res}est1{txt} stored)
+
+ {hline 60}
+ -> Foreign
+
+ {ralign 12:price} {c |} {ralign 9:e(b)} {ralign 9:e(rho)} {ralign 9:e(p)} {ralign 9:e(count)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:turn} {c |} {ralign 9:{res:{sf: .5102425}}} {ralign 9:{res:{sf: .5102425}}} {ralign 9:{res:{sf: .0181155}}} {ralign 9:{res:{sf: 21}}}
+ {ralign 12:weight} {c |} {ralign 9:{res:{sf: .8315886}}} {ralign 9:{res:{sf: .8315886}}} {ralign 9:{res:{sf: 2.99e-06}}} {ralign 9:{res:{sf: 21}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: .1797879}}} {ralign 9:{res:{sf: .1797879}}} {ralign 9:{res:{sf: .4354917}}} {ralign 9:{res:{sf: 21}}}
+ ({res}est2{txt} stored)
+
+ {com}. esttab est1 est2, not mtitles
+ {res}
+ {txt}{hline 44}
+ {txt} (1) (2)
+ {txt} Domestic Foreign
+ {txt}{hline 44}
+ {txt}turn {res} 0.433** 0.510* {txt}
+ {txt}weight {res} 0.686*** 0.832***{txt}
+ {txt}rep78 {res} -0.0193 0.180 {txt}
+ {txt}{hline 44}
+ {txt}N {res} 48 21 {txt}
+ {txt}{hline 44}
+ {txt}* p<0.05, ** p<0.01, *** p<0.001
+{* end example }{txt}{...}
+
+{marker ci}
+{dlgtab:ci}
+
+{p 4 15 2}
+{cmd:estpost} {cmdab:ci}
+ [{it:{help varlist}}] [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:b:inomial}
+ {cmdab:p:oisson} {cmdab:e:xposure:(}{it:varname}{cmd:)}
+ {cmdab:ex:act} {cmdab:wa:ld} {cmdab:w:ilson} {cmdab:a:gresti} {cmdab:j:effreys}
+ {cmdab:l:evel:(}{it:#}{cmd:)}
+ {cmdab:list:wise}
+ {cmdab:case:wise}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts standard errors and confidence intervals computed by
+ {helpb ci}. {cmd:aweight}s and {cmd:fweight}s are allowed,
+ but {cmd:aweight}s may not be specified with options
+ {cmd:binomial} or {cmd:poisson};
+ see {help weight}.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:binomial}, {cmd:poisson}, {cmd:exposure()},
+ {cmd:exact}, {cmd:wald}, {cmd:wilson}, {cmd:agresti},
+ {cmd:jeffreys}, and {cmd:level()}
+ as described in help {helpb ci}.
+
+{p 8 12 2}
+ {cmd:listwise} to handle missing values through listwise deletion,
+ meaning that an observation is omitted from the estimation
+ sample if any of the variables in {it:varlist} is missing for that
+ observation. The default is to determine the used observations for
+ each variable separately without regard to whether other variables
+ are missing. {cmd:casewise} is a synonym for {cmd:listwise}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following results vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(b)}}mean
+ {lalign 13:{cmd:e(count)}}number of observations
+ {lalign 13:{cmd:e(se)}}estimate of standard error
+ {lalign 13:{cmd:e(lb)}}lower bound of confidence interval
+ {lalign 13:{cmd:e(ub)}}upper bound of confidence interval
+
+{p 4 4 2}
+ Examples:
+
+{* begin example ci }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. estpost ci price mpg rep78, listwise
+ {txt}(confidence level is 95%)
+
+ {ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(count)} {ralign 9:e(se)} {ralign 9:e(lb)} {ralign 9:e(ub)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:price} {c |} {ralign 9:{res:{sf: 6146.043}}} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: 350.6166}}} {ralign 9:{res:{sf: 5446.399}}} {ralign 9:{res:{sf: 6845.688}}}
+ {ralign 12:mpg} {c |} {ralign 9:{res:{sf: 21.28986}}} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: .7062326}}} {ralign 9:{res:{sf: 19.88059}}} {ralign 9:{res:{sf: 22.69912}}}
+ {ralign 12:rep78} {c |} {ralign 9:{res:{sf: 3.405797}}} {ralign 9:{res:{sf: 69}}} {ralign 9:{res:{sf: .1191738}}} {ralign 9:{res:{sf: 3.167989}}} {ralign 9:{res:{sf: 3.643605}}}
+
+ {com}. esttab ., cells("b lb ub") label
+ {res}
+ {txt}{hline 59}
+ {txt} (1)
+ {txt}
+ {txt} b lb ub
+ {txt}{hline 59}
+ {txt}Price {res} 6146.043 5446.399 6845.688{txt}
+ {txt}Mileage (mpg) {res} 21.28986 19.88059 22.69912{txt}
+ {txt}Repair Record 1978 {res} 3.405797 3.167989 3.643605{txt}
+ {txt}{hline 59}
+ {txt}Observations {res} 69 {txt}
+ {txt}{hline 59}
+
+ {com}. eststo exact: estpost ci foreign, binomial exact
+ {txt}(confidence level is 95%)
+
+ {ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(count)} {ralign 9:e(se)} {ralign 9:e(lb)} {ralign 9:e(ub)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: .2972973}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: .0531331}}} {ralign 9:{res:{sf: .196584}}} {ralign 9:{res:{sf: .4148353}}}
+
+ {com}. eststo agresti: estpost ci foreign, binomial agresti
+ {txt}(confidence level is 95%)
+
+ {ralign 12:} {c |} {ralign 9:e(b)} {ralign 9:e(count)} {ralign 9:e(se)} {ralign 9:e(lb)} {ralign 9:e(ub)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:foreign} {c |} {ralign 9:{res:{sf: .2972973}}} {ralign 9:{res:{sf: 74}}} {ralign 9:{res:{sf: .0531331}}} {ralign 9:{res:{sf: .204807}}} {ralign 9:{res:{sf: .4097942}}}
+
+ {com}. esttab exact agresti, cells(lb ub) mtitles
+ {res}
+ {txt}{hline 38}
+ {txt} (1) (2)
+ {txt} exact agresti
+ {txt} lb/ub lb/ub
+ {txt}{hline 38}
+ {txt}foreign {res} .196584 .204807{txt}
+ {res} .4148353 .4097942{txt}
+ {txt}{hline 38}
+ {txt}N {res} 74 74{txt}
+ {txt}{hline 38}
+{* end example }{txt}{...}
+
+{marker stci}
+{dlgtab:stci}
+
+{p 4 15 2}
+{cmd:estpost} {cmd:stci}
+ [{it:{help if}}] [{it:{help in}}]
+ [{cmd:,}
+ {cmd:by(}{it:groupvar}{cmd:)}
+ {cmdab:m:edian}
+ {cmdab:r:mean}
+ {cmdab:e:mean}
+ {cmd:p(}{it:#}{cmd:)}
+ {cmdab:cc:orr}
+ {cmdab:l:evel:(}{it:#}{cmd:)}
+ {cmdab:q:uietly}
+ {cmdab:es:ample}
+ ]
+
+{p 4 4 2}
+ posts confidence intervals for means
+ and percentiles of survival time computed by {helpb stci}. Stata 9 or
+ newer is required.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:by(}{it:groupvar}{cmd:)}
+ to report separate summaries for each group defined by
+ {it:groupvar}, along with an overall total.
+
+{p 8 12 2}
+ {cmd:median},
+ {cmd:rmean},
+ {cmd:emean},
+ {cmd:p()},
+ {cmd:ccorr}, and
+ {cmd:level()}
+ as described in help {helpb stci}.
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {cmd:esample} to mark the estimation sample in {cmd:e(sample)}.
+
+{p 4 4 2}The following vectors are saved in {cmd:e()}:
+
+ {lalign 13:{cmd:e(count)}}number of subjects
+ {lalign 13:{cmd:e(p50)}}median (if {cmd:median} specified; the default)
+ {lalign 13:{cmd:e(p}{it:#}{cmd:)}}#th percentile (if {cmd:p(}{it:#}{cmd:)} specified)
+ {lalign 13:{cmd:e(rmean)}}restricted mean (if {cmd:rmean} specified)
+ {lalign 13:{cmd:e(emean)}}extended mean (if {cmd:emean} specified)
+ {lalign 13:{cmd:e(se)}}standard error
+ {lalign 13:{cmd:e(lb)}}lower bound of CI
+ {lalign 13:{cmd:e(ub)}}upper bound of CI
+
+{p 4 4 2}
+ Examples:
+
+{* begin example stci }{...}
+ {com}. webuse page2, clear
+ {txt}
+ {com}. estpost stci
+ {txt}(confidence level is 95%)
+
+ {ralign 12:} {c |} {ralign 9:e(count)} {ralign 9:e(p50)} {ralign 9:e(se)} {ralign 9:e(lb)} {ralign 9:e(ub)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:total} {c |} {ralign 9:{res:{sf: 40}}} {ralign 9:{res:{sf: 232}}} {ralign 9:{res:{sf: 2.562933}}} {ralign 9:{res:{sf: 213}}} {ralign 9:{res:{sf: 239}}}
+
+ {com}. esttab ., cell("count p50 se lb ub") noobs compress
+ {res}
+ {txt}{hline 60}
+ {txt} (1)
+ {txt}
+ {txt} count p50 se lb ub
+ {txt}{hline 60}
+ {txt}total {res} 40 232 2.562933 213 239{txt}
+ {txt}{hline 60}
+
+ {com}. estpost stci, by(group)
+ {txt}(confidence level is 95%)
+
+ {ralign 12:} {c |} {ralign 9:e(count)} {ralign 9:e(p50)} {ralign 9:e(se)} {ralign 9:e(lb)} {ralign 9:e(ub)}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:1} {c |} {ralign 9:{res:{sf: 19}}} {ralign 9:{res:{sf: 216}}} {ralign 9:{res:{sf: 5.171042}}} {ralign 9:{res:{sf: 190}}} {ralign 9:{res:{sf: 234}}}
+ {ralign 12:2} {c |} {ralign 9:{res:{sf: 21}}} {ralign 9:{res:{sf: 233}}} {ralign 9:{res:{sf: 2.179595}}} {ralign 9:{res:{sf: 232}}} {ralign 9:{res:{sf: 280}}}
+ {hline 13}{c +}{hline 11}{hline 11}{hline 11}{hline 11}{hline 11}
+ {ralign 12:total} {c |} {ralign 9:{res:{sf: 40}}} {ralign 9:{res:{sf: 232}}} {ralign 9:{res:{sf: 2.562933}}} {ralign 9:{res:{sf: 213}}} {ralign 9:{res:{sf: 239}}}
+
+ {com}. esttab ., cell("count p50 se lb ub") noobs compress
+ {res}
+ {txt}{hline 60}
+ {txt} (1)
+ {txt}
+ {txt} count p50 se lb ub
+ {txt}{hline 60}
+ {txt}1 {res} 19 216 5.171042 190 234{txt}
+ {txt}2 {res} 21 233 2.179595 232 280{txt}
+ {txt}total {res} 40 232 2.562933 213 239{txt}
+ {txt}{hline 60}
+{* end example }{txt}{...}
+
+{marker margins}
+{dlgtab:margins}
+
+{p 4 15 2}
+{cmd:estpost} {cmd:margins}
+ [{it:{help fvvarlist:marginlist}}] [{it:{help if}}] [{it:{help in}}] [{it:{help weight}}]
+ [{cmd:,}
+ {cmdab:q:uietly}
+ {it:{help margins:margins_opions}}
+ ]
+
+{p 4 4 2}
+ posts results from the {helpb margins} command, that was introduced in
+ Stata 11.
+
+{p 4 4 2}
+ Options are:
+
+{p 8 12 2}
+ {cmd:quietly} to suppress the output.
+
+{p 8 12 2}
+ {it:margins_opions} as described in help {helpb margins} (except {cmd:post}).
+
+{p 4 4 2}{cmd:estpost margins} replaces the current {cmd:e(b)} and
+{cmd:e(V)} with {cmd:r(b)} and {cmd:r(V)} from {helpb margins} and
+also copies all other matrixes, scalars, and macros from {helpb margins} into
+{cmd:e()} (possibly replacing identically named existing entries).
+
+{p 4 4 2}
+ Examples:
+
+{* begin example margins }{...}
+ {com}. sysuse auto, clear
+ {txt}(1978 Automobile Data)
+
+ {com}. quietly logit foreign price mpg weight
+ {txt}
+ {com}. estpost margins, dydx(*) quietly
+ {txt}
+ {com}. esttab ., cell("b se") pr2
+ {res}
+ {txt}{hline 38}
+ {txt} (1)
+ {txt} foreign
+ {txt} b se
+ {txt}{hline 38}
+ {txt}price {res} .0000686 .0000136{txt}
+ {txt}mpg {res} -.0089607 .006596{txt}
+ {txt}weight {res} -.0005069 .000055{txt}
+ {txt}{hline 38}
+ {txt}N {res} 74 {txt}
+ {txt}pseudo R-sq {res} 0.619 {txt}
+ {txt}{hline 38}
+{* end example }{txt}{...}
+
+
+{title:Author}
+
+{p 4 4 2} Ben Jann, ETH Zurich, jannb@ethz.ch
+
+
+{title:Also see}
+
+ Manual: {hi:[R] estimates}
+
+{p 4 13 2}Online: help for
+ {helpb estimates},
+ {helpb estout},
+ {helpb esttab},
+ {helpb eststo},
+ {helpb estadd}
+{p_end}
diff --git a/Modules/ado/plus/e/eststo.ado b/Modules/ado/plus/e/eststo.ado
new file mode 100644
index 0000000..6298d71
--- /dev/null
+++ b/Modules/ado/plus/e/eststo.ado
@@ -0,0 +1,343 @@
+*! version 1.1.0 05nov2008 Ben Jann
+
+program define eststo, byable(onecall)
+ version 8.2
+ local caller : di _caller()
+// --- eststo clear ---
+ if `"`1'"'=="clear" {
+ if `"`0'"'!="clear" {
+ di as err "invalid syntax"
+ exit 198
+ }
+ if "`_byvars'"!="" error 190
+ _eststo_clear
+ exit
+ }
+// --- update globals ---
+ _eststo_cleanglobal
+// --- eststo dir ---
+ if `"`1'"'=="dir" {
+ if `"`0'"'!="dir" {
+ di as err "invalid syntax"
+ exit 198
+ }
+ if "`_byvars'"!="" error 190
+ _eststo_dir
+ exit
+ }
+// --- eststo drop ---
+ if `"`1'"'=="drop" {
+ if "`_byvars'"!="" error 190
+ _eststo_`0'
+ exit
+ }
+// --- eststo store (no by) ---
+ if "`_byvars'"=="" {
+ version `caller': _eststo_store `0'
+ exit
+ }
+// --- eststo store (by) ---
+// - check sorting
+ local sortedby : sortedby
+ local i 0
+ foreach byvar of local _byvars {
+ local sortedbyi : word `++i' of `sortedby'
+ if "`byvar'"!="`sortedbyi'" error 5
+ }
+// - parse command on if qualified
+ capt _on_colon_parse `0'
+ if _rc error 190
+ if `"`s(after)'"'=="" error 190
+ local estcom `"`s(after)'"'
+ local 0 `"`s(before)'"'
+ if substr(trim(`"`estcom'"'),1,3)=="svy" {
+ di as err "svy commands not allowed with by ...: eststo:"
+ exit 190
+ }
+ AddBygrpToIfqualifier `estcom'
+// - parse syntax of _eststo_store call in order to determine
+// whether title() or missing was specified (note that
+// -estimates change- cannot be used to set the titles since
+// it does not work with -noesample-)
+ TitleAndMissing `0'
+// - generate byindex
+ tempname _byindex
+ qui egen long `_byindex' = group(`_byvars'), label `missing'
+ qui su `_byindex', meanonly
+ if r(N)==0 error 2000
+ local Nby = r(max)
+// - loop over bygroups
+ forv i = 1/`Nby' {
+ local ibylab: label (`_byindex') `i'
+ di as txt _n "{hline}"
+ di as txt `"-> `ibylab'"' // could be improved
+ if `titleopt'==0 local ibytitle
+ else if `titleopt'==1 local ibytitle `" title(`ibylab')"'
+ else if `titleopt'==2 local ibytitle `", title(`ibylab')"'
+ capture noisily {
+ version `caller': _eststo_store `0'`ibytitle' : `estcmd'
+ }
+ if _rc {
+ if "`_byrc0'"=="" error _rc
+ }
+ }
+end
+
+prog TitleAndMissing
+ capt syntax [anything] , Title(string) [ MISsing * ]
+ if _rc==0 {
+ c_local titleopt 0
+ c_local missing "`missing'"
+ }
+ else {
+ syntax [anything] [ , MISsing * ]
+ if `"`missing'`options'"'!="" c_local titleopt 1
+ else c_local titleopt 2
+ c_local missing "`missing'"
+ }
+end
+
+program AddBygrpToIfqualifier
+ syntax anything(equalok) [if/] [in] [using] [fw aw pw iw] [, * ]
+ local estcom `"`macval(anything)' if (\`_byindex'==\`i')"'
+ if `"`macval(if)'"'!="" {
+ local estcom `"`macval(estcom)' & (`macval(if)')"'
+ }
+ if `"`macval(in)'"'!="" {
+ local estcom `"`macval(estcom)' `macval(in)'"'
+ }
+ if `"`macval(using)'"'!="" {
+ local estcom `"`macval(estcom)' `macval(using)'"'
+ }
+ if `"`macval(weight)'"'!="" {
+ local estcom `"`macval(estcom)' [`macval(weight)'`macval(exp)']"'
+ }
+ if `"`macval(options)'"'!="" {
+ local estcom `"`macval(estcom)', `macval(options)'"'
+ }
+ c_local estcmd `"`macval(estcom)'"'
+end
+
+program define _eststo_clear
+ local names $eststo
+ foreach name of local names {
+ capt estimates drop `name'
+ }
+ global eststo
+ global eststo_counter
+end
+
+program define _eststo_dir
+ if `"$eststo"'!="" {
+ estimates dir $eststo
+ }
+end
+
+program define _eststo_cleanglobal
+ local enames $eststo
+ if `"`enames'"'!="" {
+ tempname hcurrent
+ _return hold `hcurrent'
+ qui _estimates dir
+ local snames `r(names)'
+ _return restore `hcurrent'
+ }
+ local names: list enames & snames
+ global eststo `names'
+ if "`names'"=="" global eststo_counter
+end
+
+program define _eststo_drop
+ local droplist `0'
+ if `"`droplist'"'=="" {
+ di as error "someting required"
+ exit 198
+ }
+ local names $eststo
+ foreach item of local droplist {
+ capt confirm integer number `item'
+ if _rc {
+ local dropname `item'
+ }
+ else {
+ if `item'<1 {
+ di as error "`item' not allowed"
+ exit 198
+ }
+ local dropname est`item'
+ }
+ local found 0
+ foreach name in `names' {
+ if match("`name'",`"`dropname'"') {
+ local found 1
+ estimates drop `name'
+ local names: list names - name
+ di as txt "(" as res "`name'" as txt " dropped)"
+ }
+ }
+ if `found'==0 {
+ di as txt "(no matches found for " as res `"`dropname'"' as txt ")"
+ }
+ }
+ global eststo `names'
+end
+
+
+program define _eststo_store, eclass
+ local caller : di _caller()
+ capt _on_colon_parse `0'
+ if !_rc {
+ local command `"`s(after)'"'
+ local 0 `"`s(before)'"'
+ }
+ syntax [name] [, ///
+ Title(passthru) ///
+ Prefix(name) ///
+ Refresh Refresh2(numlist integer max=1 >0) ///
+ ADDscalars(string asis) ///
+ noEsample ///
+ noCopy ///
+ MISsing svy /// doesn't do anything
+ ]
+ if `"`prefix'"'=="" local prefix "est"
+
+// get previous eststo names and counter
+ local names $eststo
+ local counter $eststo_counter
+ if `"`counter'"'=="" local counter 0
+
+// if name provided; set refresh on if name already in list
+ if "`namelist'"!="" {
+ if "`refresh2'"!="" {
+ di as error "refresh() not allowed"
+ exit 198
+ }
+ local name `namelist'
+ if `:list name in names' local refresh refresh
+ else {
+ if "`refresh'"!="" {
+ di as txt "(" as res "`name'" as txt " not found)"
+ }
+ local refresh
+ }
+ if "`refresh'"=="" local ++counter
+ }
+// if no name provided
+ else {
+ if "`refresh2'"!="" local refresh refresh
+ if "`refresh'"!="" {
+// refresh2 not provided => refresh last (if available)
+ if "`refresh2'"=="" {
+ if "`names'"=="" {
+ di as txt "(nothing to refresh)"
+ local refresh
+ }
+ else local name: word `:list sizeof names' of `names'
+ }
+// refresh2 provided => check availability
+ else {
+ if `:list posof "`prefix'`refresh2'" in names' {
+ local name `prefix'`refresh2'
+ }
+ else {
+ di as txt "(" as res "`prefix'`refresh2'" as txt " not found)"
+ local refresh
+ }
+ }
+ }
+ if "`refresh'"=="" local ++counter
+// set default name
+ if "`name'"=="" local name `prefix'`counter'
+ }
+
+// run estimation command if provided
+ if `"`command'"'!="" {
+ version `caller': `command'
+ }
+
+// add scalars to e()
+ if `"`addscalars'"'!="" {
+ capt ParseAddscalars `addscalars'
+ if _rc {
+ di as err `"addscalars() invalid"'
+ exit 198
+ }
+ if "`replace'"=="" {
+ local elist `: e(scalars)' `: e(macros)' `: e(matrices)' `: e(functions)'
+ }
+ local forbidden b V sample
+ while (1) {
+ gettoken lhs rest: rest
+ if `:list lhs in forbidden' {
+ di as err `"`lhs' not allowed in addscalars()"'
+ exit 198
+ }
+ if "`replace'"=="" {
+ if `:list lhs in elist' {
+ di as err `"e(`lhs') already defined"'
+ exit 110
+ }
+ }
+ gettoken rhs rest: rest, bind
+ capt eret scalar `lhs' = `rhs'
+ if _rc {
+ di as err `"addscalars() invalid"'
+ exit 198
+ }
+ capture local result = e(`lhs')
+ di as txt "(e(" as res `"`lhs'"' as txt ") = " ///
+ as res `result' as txt " added)"
+ if `"`rest'"'=="" continue, break
+ }
+ }
+// add e(cmd) if missing
+ if `"`e(cmd)'"'=="" {
+ if `"`: e(scalars)'`: e(macros)'`: e(matrices)'`: e(functions)'"'!="" {
+ eret local cmd "."
+ }
+ }
+
+// store estimates with e(sample)
+ estimates store `name' , `copy' `title'
+
+// remove e(sample) if -noesample- specified
+ if "`esample'"!="" {
+ capt confirm new var _est_`name'
+ if _rc {
+ tempname hcurrent
+ _est hold `hcurrent', restore estsystem nullok
+ qui replace _est_`name' = . in 1
+ _est unhold `name'
+ capt confirm new var _est_`name'
+ if _rc qui drop _est_`name'
+ else {
+ di as error "somethings wrong; please contact author of -eststo- " ///
+ "(see e-mail in help {help eststo})"
+ exit 498
+ }
+ _est hold `name', estimates varname(_est_`name')
+ // varname() only needed so that _est hold does not return error
+ // if variable `name' exists
+ }
+ }
+
+// report
+ if "`refresh'"=="" {
+ global eststo `names' `name'
+ global eststo_counter `counter'
+ if `"`namelist'"'=="" {
+ di as txt "(" as res "`name'" as txt " stored)"
+ }
+ }
+ else {
+ if `"`namelist'"'=="" {
+ di as txt "(" as res "`name'" as txt " refreshed)"
+ }
+ }
+end
+
+program ParseAddscalars
+ syntax anything [ , Replace ]
+ c_local rest `"`anything'"'
+ c_local replace `replace'
+end
diff --git a/Modules/ado/plus/e/eststo.hlp b/Modules/ado/plus/e/eststo.hlp
new file mode 100644
index 0000000..bde4b30
--- /dev/null
+++ b/Modules/ado/plus/e/eststo.hlp
@@ -0,0 +1,347 @@
+{smcl}
+{* 07jan2009}{...}
+{hi:help eststo}{right:also see: {helpb esttab}, {helpb estout}, {helpb estadd}, {helpb estpost}}
+{right: {browse "http://repec.org/bocode/e/estout"}}
+{hline}
+
+{title:Title}
+
+{p 4 4 2}{hi:eststo} {hline 2} Store estimates
+
+
+{title:Syntax}{smcl}
+
+{p 8 15 2}
+[{cmd:_}]{cmd:eststo} [{it:name}]
+[{cmd:,} {it:{help eststo##options:options}} ]
+[ {cmd::} {it:{help estimation_command}} ]
+
+{p 8 15 2}
+[{cmd:_}]{cmd:eststo dir}
+
+{p 8 15 2}
+[{cmd:_}]{cmd:eststo drop} {{it:#}|{it:name}} [ {{it:#}|{it:name}} ... ]
+
+{p 8 15 2}
+[{cmd:_}]{cmd:eststo clear}
+
+{marker options}
+ {it:options}{col 23}description
+ {hline 56}
+ [{ul:{cmd:no}}]{cmdab:e:sample}{col 23}{...}
+do not/do store {cmd:e(sample)}
+ {cmdab:t:itle:(}{it:string}{cmd:)}{col 23}{...}
+specify a title for the stored set
+ {cmdab:p:refix:(}{it:prefix}{cmd:)}{col 23}{...}
+specify a name prefix; default is {cmd:est}
+ {cmdab:add:scalars(}{it:...}{cmd:)}{col 23}{...}
+add scalar statistics
+ {cmdab:r:efresh}[{cmd:(}{it:#}{cmd:)}]{col 23}{...}
+overwrite a previously stored set
+ {cmdab:noc:opy}{col 23}{...}
+clear {cmd:e()} after storing the set
+ {cmdab:mis:sing}{col 23}{...}
+use missing values in the {cmd:by} groups
+ {hline 56}
+
+{p 4 4 2}
+{cmd:by} is allowed with {cmd:eststo} if {cmd:eststo}
+is used as a prefix command, i.e. specify
+
+ {cmd:by} {it:...} {cmd::} {cmd:eststo} {it:...} {cmd::} {it:estimation_command}
+
+{p 4 4 2}
+to apply {it:estimation_command} to each {cmd:by} group and store an estimation
+set for each group; see help {help by}. Note that the implementation of {cmd:by}
+with {cmd:eststo} requires {it:estimation_command}
+to follow {help language:standard Stata syntax} and
+allow the {it:{help if}} qualifier. Do not use the
+{bind:{cmd:by} {it:...}{cmd:: eststo:}} construct with
+{cmd:svy} commands.
+
+
+{title:Description}
+
+{p 4 4 2}
+{cmd:eststo} stores a copy of the active estimation results for later
+tabulation. If {it:name} is provided, the estimation set is stored
+under {it:name}. If {it:name} is not provided, the estimation set is
+stored under {cmd:est}{it:#}, where {it:#} is a counter for the
+number of stored estimation sets.
+
+{p 4 4 2}
+{cmd:eststo} may be used in two ways: Either after fitting a model as
+in
+
+ {com}. regress y x
+ . eststo{txt}
+
+{p 4 4 2}
+or as a prefix command (see help {help prefix}):
+
+ {com}. eststo: regress y x{txt}
+
+{p 4 4 2}
+{cmd:_eststo} is a variant on {cmd:eststo} that, by default, does not
+store the estimation sample information contained in {cmd:e(sample)}.
+Essentially, {cmd:_eststo} is a shortcut to {cmd:eststo, noesample}.
+
+{p 4 4 2}
+{cmd:eststo dir} displays a list of the stored estimates.
+
+{p 4 4 2}
+{cmd:eststo drop} drops estimation sets stored by {cmd:eststo}. If {it:name} is
+provided, the estimation set stored under {it:name}
+is dropped (if {cmd:*} or {cmd:?} wildcards are used {it:name},
+all matching sets are dropped). Alternatively, if {it:#} is provided,
+the estimation set stored as {cmd:est}{it:#} is dropped.
+
+{p 4 4 2}
+{cmd:eststo clear} drops all estimation sets stored by {cmd:eststo} (and clears
+{cmd:eststo}'s global macros).
+
+{p 4 4 2}
+{cmd:eststo} is an alternative to official Stata's
+{helpb estimates store}. The main differences are:
+
+{p 8 12 2}
+{space 1}o{space 2}{cmd:eststo} does not require the user to specify a
+name for the stored estimation set.
+
+{p 8 12 2}
+{space 1}o{space 2}{cmd:eststo} may be used as a prefix command (see
+help {help prefix}).
+
+{p 8 12 2}
+{space 1}o{space 2}{cmd:eststo} provides the possibility to store
+estimates without the {cmd:e(sample)} function (either specify the
+{cmd:noesample} option or use the {cmd:_eststo} command). Omitting
+{cmd:e(sample)} saves memory and also speeds up tabulation programs
+such as {helpb estimates table}, {helpb estout} or {helpb esttab}.
+{hi:Warning:} Some post-estimation commands may not work with
+estimation sets that do not contain the {cmd:e(sample)}.
+
+{p 8 12 2}
+{space 1}o{space 2}{cmd:eststo} can add additional scalar statistics to
+be stored with the estimation set.
+
+
+{title:Options}
+{marker esample}
+{p 4 8 2}
+{cmd:esample} causes the information in {cmd:e(sample)} to be stored
+with the estimates. This is the default in {cmd:eststo}. Type
+{cmd:noesample} or use the {cmd:_eststo} command to omit the
+{cmd:e(sample)}. Note that some post-estimation commands may not be
+working correctly with estimation sets that have been stored without
+{cmd:e(sample)}.
+
+{p 4 8 2}
+{cmd:title(}{it:string}{cmd:)} specifies a title for the stored
+estimation set.
+{p_end}
+{marker addscalars}
+{p 4 8 2}
+{cmd:addscalars(}{it:name exp} [{it:...}] [{cmd:,} {cmdab:r:eplace}]{cmd:)}
+may be used to add additional results to the {cmd:e()}-scalars of the
+estimation set before storing it. Specify the names and values of the
+scalars in pairs. For example, {cmd:addscalars(one 1 two 2)} would
+add {cmd:e(one)} = {cmd:1} and {cmd:e(two)} = {cmd:2}. See below for
+an example. The {cmd:replace} suboption permits overwriting existing
+{cmd:e()}-returns. Not allowed as names are "b", "V", or "sample".
+See {helpb estadd} for a more sophisticated tool to add additional
+results to {cmd:e()}-returns.
+
+{p 4 8 2}
+{cmd:prefix(}{it:prefix}{cmd:)} specifies a custom prefix for the
+automatic names of the stored estimation sets. The default prefix
+is {cmd:est}.
+
+{p 4 8 2}
+{cmd:refresh}[{cmd:(}{it:#}{cmd:)}] may be used to overwrite a
+previously stored estimation set instead of storing the estimates
+under a new name. {cmd:refresh}, specified without argument, will
+overwrite the last saved set. Alternatively,
+{cmd:refresh(}{it:#}{cmd:)} will overwrite the set named
+{cmd:est}{it:#} if it exists. If {it:name} is provided to {cmd:eststo},
+existing sets of the same name will always be overwritten whether or
+not {cmd:refresh} is specified. {cmd:refresh()} with argument is not
+allowed in this case.
+
+{p 4 8 2}
+{cmd:nocopy} specifies that after the estimation set has been stored,
+it no longer be available as the active estimation set.
+
+{p 4 8 2}
+{cmd:missing} is for use of {cmd:eststo} with the {cmd:by} prefix command and
+causes missing values to be treated like any other values in the {cmd:by}
+variables. The default is to discard observations with missing values in the
+{cmd:by} variables.
+
+
+{title:Examples}
+
+{p 4 4 2}
+Applying {cmd:eststo} after fiting a model to store the model's results,
+as in the following example:
+
+ {com}. sysuse auto
+ {txt}(1978 Automobile Data)
+
+ {com}. quietly regress price weight
+ {txt}
+ {com}. eststo model1
+ {txt}
+ {com}. quietly regress turn weight foreign
+ {txt}
+ {com}. eststo model2
+ {txt}
+ {com}. estout
+ {res}
+ {txt}{hline 38}
+ {txt} model1 model2
+ {txt} b b
+ {txt}{hline 38}
+ {txt}weight {res} 2.044063 .0042183{txt}
+ {txt}foreign {res} -1.809802{txt}
+ {txt}_cons {res} -6.707353 27.44963{txt}
+ {txt}{hline 38}
+
+
+{p 4 4 2}
+Applying {cmd:eststo} as a prefix commmand to fit and store a model in one step:
+
+ {com}. eststo model1: quietly regress price weight
+ {txt}
+ {com}. eststo model2: quietly regress turn weight foreign
+ {txt}
+ {com}. estout
+ {res}
+ {txt}{hline 38}
+ {txt} model1 model2
+ {txt} b b
+ {txt}{hline 38}
+ {txt}weight {res} 2.044063 .0042183{txt}
+ {txt}foreign {res} -1.809802{txt}
+ {txt}_cons {res} -6.707353 27.44963{txt}
+ {txt}{hline 38}
+
+
+{p 4 4 2}
+Using {cmd:eststo} with automatic names:
+
+ {com}. eststo clear
+ {txt}
+ {com}. eststo: quietly regress price weight
+ {txt}({res}est1{txt} stored)
+
+ {com}. eststo: quietly regress turn weight foreign
+ {txt}({res}est2{txt} stored)
+
+ {com}. estout
+ {res}
+ {txt}{hline 38}
+ {txt} est1 est2
+ {txt} b b
+ {txt}{hline 38}
+ {txt}weight {res} 2.044063 .0042183{txt}
+ {txt}foreign {res} -1.809802{txt}
+ {txt}_cons {res} -6.707353 27.44963{txt}
+ {txt}{hline 38}
+
+
+{p 4 4 2}
+Adding ancillary statistics:
+
+ {com}. eststo clear
+ {txt}
+ {com}. quietly regress price weight mpg
+ {txt}
+ {com}. test weight = mpg
+
+ {txt} ( 1) {res}weight - mpg = 0
+
+ {txt} F( 1, 71) ={res} 0.36
+ {txt}{col 13}Prob > F ={res} 0.5514
+ {txt}
+ {com}. eststo, add(p_diff r(p))
+ {txt}(e({res}p_diff{txt}) = {res}.55138216{txt} added)
+ ({res}est1{txt} stored)
+
+ {com}. estout, stat(p_diff)
+ {res}
+ {txt}{hline 25}
+ {txt} est1
+ {txt} b
+ {txt}{hline 25}
+ {txt}weight {res} 1.746559{txt}
+ {txt}mpg {res} -49.51222{txt}
+ {txt}_cons {res} 1946.069{txt}
+ {txt}{hline 25}
+ {txt}p_diff {res} .5513822{txt}
+ {txt}{hline 25}
+
+
+{p 4 4 2}
+Using the {cmd:by} prefix to store subbroup models:
+
+ {com}. eststo clear
+ {txt}
+ {com}. quietly by foreign: eststo: quietly reg price weight mpg
+ {txt}
+ {com}. esttab, label nodepvar nonumber
+ {res}
+ {txt}{hline 52}
+ {txt} Domestic Foreign
+ {txt}{hline 52}
+ {txt}Weight (lbs.) {res} 4.415*** 5.156***{txt}
+ {res} {ralign 12:{txt:(}4.66{txt:)}} {ralign 12:{txt:(}5.85{txt:)}} {txt}
+
+ {txt}Mileage (mpg) {res} 237.7 -19.78 {txt}
+ {res} {ralign 12:{txt:(}1.71{txt:)}} {ralign 12:{txt:(}-0.34{txt:)}} {txt}
+
+ {txt}Constant {res} -13285.4* -5065.8 {txt}
+ {res} {ralign 12:{txt:(}-2.32{txt:)}} {ralign 12:{txt:(}-1.58{txt:)}} {txt}
+ {txt}{hline 52}
+ {txt}Observations {res} 52 22 {txt}
+ {txt}{hline 52}
+ {txt}t statistics in parentheses
+ {txt}* p<0.05, ** p<0.01, *** p<0.001
+
+
+{title:Returned results}
+
+{p 4 4 2}
+The name under which an estimation set is stored, is added to the set in
+{cmd:e(_estimates_name)}.
+
+{p 4 4 2}
+In addition, {cmd:eststo} maintains two global macros. {cmd:$eststo} contains a list
+of the names of the stored estimation sets. {cmd:$eststo_counter}
+contains the count of stored estimation sets.
+
+
+{title:Acknowledgements}
+
+{p 4 4 2}
+Bill Gould suggested to make {cmd:eststo} "byable".
+
+
+{title:Author}
+
+{p 4 4 2}
+Ben Jann, ETH Zurich, jannb@ethz.ch
+
+
+{title:Also see}
+
+ Manual: {hi:[R] estimates}
+
+{p 4 13 2}Online: help for
+ {helpb estimates},
+ {helpb esttab},
+ {helpb estout},
+ {helpb estadd},
+ {helpb estpost}
+{p_end}
+
diff --git a/Modules/ado/plus/e/esttab.ado b/Modules/ado/plus/e/esttab.ado
new file mode 100644
index 0000000..88ddb52
--- /dev/null
+++ b/Modules/ado/plus/e/esttab.ado
@@ -0,0 +1,1199 @@
+*! version 2.0.5 09mar2009 Ben Jann
+*! wrapper for estout
+
+program define esttab
+ version 8.2
+ local caller : di _caller()
+
+// mode specific defaults
+ local cdate "`c(current_date)'"
+ local ctime "`c(current_time)'"
+// - fixed
+ local fixed_open0 `""% `cdate' `ctime'""'
+ local fixed_close0 `""""'
+ local fixed_open `""'
+ local fixed_close `""'
+ local fixed_caption `""@title""'
+ local fixed_open2 `""'
+ local fixed_close2 `""'
+ local fixed_toprule `""@hline""'
+ local fixed_midrule `""@hline""'
+ local fixed_bottomrule `""@hline""'
+ local fixed_topgap `""""'
+ local fixed_midgap `""""'
+ local fixed_bottomgap `""""'
+ local fixed_eqrule `"begin(@hline "")"'
+ local fixed_ssl `"N R-sq "adj. R-sq" "pseudo R-sq" AIC BIC"'
+ local fixed_lsl `"Observations R-squared "Adjusted R-squared" "Pseudo R-squared" AIC BIC"'
+ local fixed_starlevels `"* 0.05 ** 0.01 *** 0.001"'
+ local fixed_starlevlab `""'
+ local fixed_begin `""'
+ local fixed_delimiter `"" ""'
+ local fixed_end `""'
+ local fixed_incelldel `"" ""'
+ local fixed_varwidth `"\`= cond("\`label'"=="", 12, 20)'"'
+ local fixed_modelwidth `"12"'
+ local fixed_abbrev `"abbrev"'
+ local fixed_substitute `""'
+ local fixed_tstatlab `"t statistics"'
+ local fixed_zstatlab `"z statistics"'
+ local fixed_pvallab `"p-values"'
+ local fixed_cilab `"\`level'% confidence intervals"'
+// - smcl
+ local smcl_open0 `"{smcl} "{* % `cdate' `ctime'}{...}""'
+ local smcl_close0 `""""'
+ local smcl_open `""'
+ local smcl_close `""'
+ local smcl_caption `""@title""'
+ local smcl_open2 `""'
+ local smcl_close2 `""'
+ local smcl_toprule `""{hline @width}""'
+ local smcl_midrule `""{hline @width}""'
+ local smcl_bottomrule `""{hline @width}""'
+ local smcl_topgap `""""'
+ local smcl_midgap `""""'
+ local smcl_bottomgap `""""'
+ local smcl_eqrule `"begin("{hline @width}" "")"'
+ local smcl_ssl `"`macval(fixed_ssl)'"'
+ local smcl_lsl `"`macval(fixed_lsl)'"'
+ local smcl_starlevels `"`macval(fixed_starlevels)'"'
+ local smcl_starlevlab `""'
+ local smcl_begin `""'
+ local smcl_delimiter `"" ""'
+ local smcl_end `""'
+ local smcl_incelldel `"" ""'
+ local smcl_varwidth `"`macval(fixed_varwidth)'"'
+ local smcl_modelwidth `"`macval(fixed_modelwidth)'"'
+ local smcl_abbrev `"`macval(fixed_abbrev)'"'
+ local smcl_substitute `""'
+ local smcl_tstatlab `"`macval(fixed_tstatlab)'"'
+ local smcl_zstatlab `"`macval(fixed_zstatlab)'"'
+ local smcl_pvallab `"`macval(fixed_pvallab)'"'
+ local smcl_cilab `"`macval(fixed_cilab)'"'
+// - tab
+ local tab_open0 `"`macval(fixed_open0)'"'
+ local tab_close0 `""""'
+ local tab_open `""'
+ local tab_close `""'
+ local tab_caption `""@title""'
+ local tab_open2 `""'
+ local tab_close2 `""'
+ local tab_topgap `""""'
+ local tab_midgap `""""'
+ local tab_bottomgap `""""'
+ local tab_ssl `"`macval(fixed_ssl)'"'
+ local tab_lsl `"`macval(fixed_lsl)'"'
+ local tab_starlevels `"`macval(fixed_starlevels)'"'
+ local tab_starlevlab `""'
+ local tab_begin `""'
+ local tab_delimiter `"_tab"'
+ local tab_end `""'
+ local tab_incelldel `"" ""'
+ local tab_varwidth `""'
+ local tab_modelwidth `""'
+ local tab_abbrev `""'
+ local tab_substitute `""'
+ local tab_tstatlab `"`macval(fixed_tstatlab)'"'
+ local tab_zstatlab `"`macval(fixed_zstatlab)'"'
+ local tab_pvallab `"`macval(fixed_pvallab)'"'
+ local tab_cilab `"`macval(fixed_cilab)'"'
+// - csv
+ local csv_open0 `"`"\`csvlhs'% `cdate' `ctime'""'"'
+ local csv_close0 `""""'
+ local csv_open `""'
+ local csv_close `""'
+ local csv_caption `"`"\`csvlhs'@title""'"'
+ local csv_open2 `""'
+ local csv_close2 `""'
+ local csv_topgap `""""'
+ local csv_midgap `""""'
+ local csv_bottomgap `""""'
+ local csv_ssl `"`macval(fixed_ssl)'"'
+ local csv_lsl `"`macval(fixed_lsl)'"'
+ local csv_starlevels `"`macval(fixed_starlevels)'"'
+ local csv_starlevlab `""'
+ local csv_begin `"`"\`csvlhs'"'"'
+ local csv_delimiter `"`"",\`csvlhs'"'"'
+ local scsv_delimiter `"`"";\`csvlhs'"'"'
+ local csv_end `"`"""'"'
+ local csv_incelldel `"" ""'
+ local csv_varwidth `""'
+ local csv_modelwidth `""'
+ local csv_abbrev `""'
+ local csv_substitute `""'
+ local csv_tstatlab `"`macval(fixed_tstatlab)'"'
+ local csv_zstatlab `"`macval(fixed_zstatlab)'"'
+ local csv_pvallab `"`macval(fixed_pvallab)'"'
+ local csv_cilab `"`macval(fixed_cilab)'"'
+// - rtf
+ local rtf_open0 `""'
+ local rtf_close0 `""'
+ local rtf_ct `"\yr`=year(d(`cdate'))'\mo`=month(d(`cdate'))'\dy`=day(d(`cdate'))'\hr`=substr("`ctime'",1,2)'\min`=substr("`ctime'",4,2)'"'
+ local rtf_open_l1 `"`"{\rtf1`=cond("`c(os)'"=="MacOSX", "\mac", "\ansi")'\deff0 {\fonttbl{\f0\fnil Times New Roman;}}"'"'
+ local rtf_open_l2 `" `"{\info {\author .}{\company .}{\title .}{\creatim`rtf_ct'}}"'"'
+ local rtf_open_l3 `" `"\deflang1033\plain\fs24"'"'
+ local rtf_open_l4 `" `"{\footer\pard\qc\plain\f0\fs24\chpgn\par}"'"'
+ local rtf_open `"`rtf_open_l1'`rtf_open_l2'`rtf_open_l3'`rtf_open_l4'"'
+ local rtf_close `""{\pard \par}" "}""'
+ local rtf_caption `"`"{\pard\keepn\ql @title\par}"'"'
+ local rtf_open2 `""{""'
+ local rtf_close2 `""}""'
+ local rtf_toprule `""'
+ local rtf_midrule `""'
+ local rtf_bottomrule `""'
+ local rtf_topgap `""'
+ local rtf_midgap `"{\trowd\trgaph108\trleft-108@rtfemptyrow\row}"'
+ local rtf_bottomgap `""'
+ local rtf_eqrule `"begin("{\trowd\trgaph108\trleft-108@rtfrowdefbrdrt\pard\intbl\ql {") replace"'
+ local rtf_ssl `""{\i N}" "{\i R}{\super 2}" "adj. {\i R}{\super 2}" "pseudo {\i R}{\super 2}" "{\i AIC}" "{\i BIC}""'
+ local rtf_lsl `"Observations "{\i R}{\super 2}" "Adjusted {\i R}{\super 2}" "Pseudo {\i R}{\super 2}" "{\i AIC}" "{\i BIC}""'
+ local rtf_starlevels `""{\super *}" 0.05 "{\super **}" 0.01 "{\super ***}" 0.001"'
+ local rtf_starlevlab `", label(" {\i p} < ")"'
+ local rtf_rowdef `"\`=cond("\`lines'"=="", "@rtfrowdef", "@rtfrowdefbrdr")'"'
+ local rtf_begin `"{\trowd\trgaph108\trleft-108\`rtf_rowdef'\pard\intbl\ql {"'
+ local rtf_delimiter `"}\cell \pard\intbl\q\`=cond(`"\`alignment'"'!="", `"\`alignment'"', "c")' {"'
+ local rtf_end `"}\cell\row}"'
+ local rtf_incelldel `""\line ""'
+ local rtf_varwidth `"\`= cond("\`label'"=="", 12, 20)'"'
+ local rtf_modelwidth `"12"'
+ local rtf_abbrev `""'
+ local rtf_substitute `""'
+ local rtf_tstatlab `"{\i t} statistics"'
+ local rtf_zstatlab `"{\i z} statistics"'
+ local rtf_pvallab `"{\i p}-values"'
+ local rtf_cilab `"\`level'% confidence intervals"'
+// - html
+ local html_open0 `" "`=cond(`"\`macval(title)'"'=="","estimates table, created `cdate' `ctime'","@title")'" """'
+ local html_close0 `""" """'
+ local html_open `"`""'"'
+ local html_close `""
""'
+ local html_caption `""@title""'
+ local html_open2 `""'
+ local html_close2 `""'
+ local html_toprule `""
|
""'
+ local html_midrule `""
|
""'
+ local html_bottomrule `""
|
""'
+ local html_topgap `""'
+ local html_midgap `"" |
""'
+ local html_bottomgap `""'
+ local html_eqrule `"begin("
|
" "")"'
+ local html_ssl `"N R2 "adj. R2" "pseudo R2" AIC BIC"'
+ local html_lsl `"Observations R2 "Adjusted R2" "Pseudo R2" AIC BIC"'
+ local html_starlevels `"* 0.05 ** 0.01 *** 0.001"'
+ local html_starlevlab `", label(" p < ")"'
+ local html_begin `""'
+ local html_delimiter `" | "'
+ local html_end `" |
"'
+ local html_incelldel `"
"'
+ local html_varwidth `"\`= cond("\`label'"=="", 12, 20)'"'
+ local html_modelwidth `"12"'
+ local html_abbrev `""'
+ local html_substitute `""'
+ local html_tstatlab `"t statistics"'
+ local html_zstatlab `"z statistics"'
+ local html_pvallab `"p-values"'
+ local html_cilab `"\`level'% confidence intervals"'
+// - tex
+ local tex_open0 `""% `cdate' `ctime'" \documentclass{article} \`texpkgs' \`=cond("\`longtable'"!="","\usepackage{longtable}","")' \begin{document} """'
+ local tex_close0 `""" \end{document} """'
+ local tex_open `"\`=cond("\`longtable'"=="", "\begin{table}[htbp]\centering", `"{"')'"'
+ local tex_close `"\`=cond("\`longtable'"=="", "\end{table}", "}")'"'
+ local tex_caption `"\caption{@title}"'
+ local tex_open2 `"\`=cond("\`longtable'"!="", "\begin{longtable}", "\begin{tabular" + cond("\`width'"=="", "}", "*}{\`width'}"))'"'
+ local tex_close2 `"\`=cond("\`longtable'"!="", "\end{longtable}", "\end{tabular" + cond("\`width'"=="", "}", "*}"))'"'
+ local tex_toprule `"\`="\hline\hline" + cond("\`longtable'"!="", "\endfirsthead\hline\endhead\hline\endfoot\endlastfoot", "")'"'
+ local tex_midrule `""\hline""'
+ local tex_bottomrule `""\hline\hline""'
+ local tex_topgap `""'
+ local tex_midgap `"[1em]"' // `"\\\"'
+ local tex_bottomgap `""'
+ local tex_eqrule `"begin("\hline" "")"'
+ local tex_ssl `"\(N\) \(R^{2}\) "adj. \(R^{2}\)" "pseudo \(R^{2}\)" \textit{AIC} \textit{BIC}"'
+ local tex_lsl `"Observations \(R^{2}\) "Adjusted \(R^{2}\)" "Pseudo \(R^{2}\)" \textit{AIC} \textit{BIC}"'
+ local tex_starlevels `"\sym{*} 0.05 \sym{**} 0.01 \sym{***} 0.001"'
+ local tex_starlevlab `", label(" \(p<@\)")"'
+ local tex_begin `""'
+ local tex_delimiter `"&"'
+ local tex_end `"\\\"'
+ local tex_incelldel `"" ""'
+ local tex_varwidth `"\`= cond("\`label'"=="", 12, 20)'"'
+ local tex_modelwidth `"12"'
+ local tex_abbrev `""'
+ local tex_tstatlab `"\textit{t} statistics"'
+ local tex_zstatlab `"\textit{z} statistics"'
+ local tex_pvallab `"\textit{p}-values"'
+ local tex_cilab `"\`level'\% confidence intervals"'
+ local tex_substitute `"_ \_ "\_cons " \_cons"'
+// - booktabs
+ local booktabs_open0 `""% `cdate' `ctime'" \documentclass{article} \`texpkgs' \usepackage{booktabs} \`=cond("\`longtable'"!="","\usepackage{longtable}","")' \begin{document} """'
+ local booktabs_close0 `"`macval(tex_close0)'"'
+ local booktabs_open `"`macval(tex_open)'"'
+ local booktabs_close `"`macval(tex_close)'"'
+ local booktabs_caption `"`macval(tex_caption)'"'
+ local booktabs_open2 `"`macval(tex_open2)'"'
+ local booktabs_close2 `"`macval(tex_close2)'"'
+ local booktabs_toprule `"\`="\toprule" + cond("\`longtable'"!="", "\endfirsthead\midrule\endhead\midrule\endfoot\endlastfoot", "")'"'
+ local booktabs_midrule `""\midrule""'
+ local booktabs_bottomrule `""\bottomrule""'
+ local booktabs_topgap `"`macval(tex_topgap)'"'
+ local booktabs_midgap `"\addlinespace"'
+ local booktabs_bottomgap `"`macval(tex_bottomgap)'"'
+ local booktabs_eqrule `"begin("\midrule" "")"'
+ local booktabs_ssl `"`macval(tex_ssl)'"'
+ local booktabs_lsl `"`macval(tex_lsl)'"'
+ local booktabs_starlevels `"`macval(tex_starlevels)'"'
+ local booktabs_starlevlab `"`macval(tex_starlevlab)'"'
+ local booktabs_begin `"`macval(tex_begin)'"'
+ local booktabs_delimiter `"`macval(tex_delimiter)'"'
+ local booktabs_end `"`macval(tex_end)'"'
+ local booktabs_incelldel `"`macval(tex_incelldel)'"'
+ local booktabs_varwidth `"`macval(tex_varwidth)'"'
+ local booktabs_modelwidth `"`macval(tex_modelwidth)'"'
+ local booktabs_abbrev `"`macval(tex_abbrev)'"'
+ local booktabs_tstatlab `"`macval(tex_tstatlab)'"'
+ local booktabs_zstatlab `"`macval(tex_zstatlab)'"'
+ local booktabs_pvallab `"`macval(tex_pvallab)'"'
+ local booktabs_cilab `"`macval(tex_cilab)'"'
+ local booktabs_substitute `"`macval(tex_substitute)'"'
+
+// syntax
+ syntax [anything] [using] [ , ///
+ /// coefficients and t-stats, se, etc.
+ b Bfmt(string) ///
+ noT Tfmt(string) ///
+ z Zfmt(string) ///
+ se SEfmt(string) ///
+ p Pfmt(string) ///
+ ci CIfmt(string) ///
+ BEta BEtafmt(string) ///
+ main(string) /// syntax: name format
+ aux(string) /// syntax: name format
+ abs /// absolute t-values
+ wide ///
+ NOSTAr STAR STAR2(string asis) ///
+ staraux ///
+ NOCONstant CONstant ///
+ COEFlabels(string asis) ///
+ /// summary statistics
+ noOBS obslast ///
+ r2 R2fmt(string) ar2 AR2fmt(string) pr2 PR2fmt(string) ///
+ aic AICfmt(string) bic BICfmt(string) ///
+ SCAlars(string asis) /// syntax: "name1 [label1]" "name2 [label2]" etc.
+ sfmt(string) ///
+ /// layout
+ NOMTItles MTItles MTItles2(string asis) ///
+ NOGAPs GAPs ///
+ NOLInes LInes ///
+ ADDNotes(string asis) ///
+ COMpress ///
+ plain ///
+ smcl FIXed tab csv SCsv rtf HTMl tex BOOKTabs ///
+ Fragment ///
+ page PAGE2(str) ///
+ ALIGNment(str asis) ///
+ width(str asis) ///
+ /// other
+ Noisily ///
+ * ]
+ _more_syntax , `macval(options)'
+ _estout_options , `macval(options)'
+
+// matrix mode
+ MatrixMode, `anything'
+
+// syntax consistency etc
+ gettoken chunk using0: using
+ if `"`macval(star2)'"'!="" local star star
+ foreach opt in constant gaps lines star abbrev depvars numbers parentheses ///
+ notes mtitles type outfilenoteoff {
+ NotBothAllowed "``opt''" `no`opt''
+ }
+ NotBothAllowed "`staraux'" `nostar'
+ if `"`macval(mtitles2)'"'!="" NotBothAllowed "mtitles" `nomtitles'
+ if `"`page2'"'!="" local page page
+ NotBothAllowed "`fragment'" `page'
+ if `"`pfmt'"'!="" local p p
+ if `"`zfmt'"'!="" local z z
+ if `"`sefmt'"'!="" local se se
+ if `"`cifmt'"'!="" local ci ci
+ if `"`betafmt'"'!="" local beta beta
+ if "`level'"=="" local level $S_level
+ if ((("`margin'"!="" | `"`margin2'"'!="") & "`nomargin'"=="") | ///
+ ("`beta'"!="") | ("`eform'"!="" & "`noeform'"=="")) ///
+ & "`constant'"=="" local noconstant noconstant
+ if `"`r2fmt'"'!="" local r2 r2
+ if `"`ar2fmt'"'!="" local ar2 ar2
+ if `"`pr2fmt'"'!="" local pr2 pr2
+ if `"`aicfmt'"'!="" local aic aic
+ if `"`bicfmt'"'!="" local bic bic
+ if "`type'"=="" & `"`using'"'!="" local notype notype
+ local nocellsopt = `"`macval(cells)'"'==""
+ if `"`width'"'!="" & `"`longtable'"'!="" {
+ di as err "width() and longtable not both allowed"
+ exit 198
+ }
+
+// format modes
+ local mode `smcl' `fixed' `tab' `csv' `scsv' `rtf' `html' `tex' `booktabs'
+ if `:list sizeof mode'>1 {
+ di as err "only one allowed of smcl, fixed, tab, csv, scsv, rtf, html, tex, or booktabs"
+ exit 198
+ }
+ if `"`using'"'!="" {
+ _getfilename `"`using0'"'
+ local fn `"`r(filename)'"'
+ _getfilesuffix `"`fn'"'
+ local suffix `"`r(suffix)'"'
+ }
+ if "`mode'"=="" {
+ if `"`using'"'!="" {
+ if inlist(`"`suffix'"', ".html", ".htm") local mode html
+ else if `"`suffix'"'==".tex" local mode tex
+ else if `"`suffix'"'==".csv" local mode csv
+ else if `"`suffix'"'==".rtf" local mode rtf
+ else if `"`suffix'"'==".smcl" local mode smcl
+ else local mode fixed
+ }
+ else local mode smcl
+ }
+ else {
+ if "`mode'"=="scsv" {
+ local csv_delimiter `"`macval(`mode'_delimiter)'"'
+ local mode "csv"
+ }
+ }
+ if `"`using'"'!="" & `"`suffix'"'=="" {
+ if inlist("`mode'","fixed","tab") local suffix ".txt"
+ else if inlist("`mode'","csv","scsv") local suffix ".csv"
+ else if "`mode'"=="rtf" local suffix ".rtf"
+ else if "`mode'"=="html" local suffix ".html"
+ else if inlist("`mode'","tex","booktabs") local suffix ".tex"
+ else if "`mode'"=="smcl" local suffix ".smcl"
+ local using `"using `"`fn'`suffix'"'"'
+ local using0 `" `"`fn'`suffix'"'"'
+ }
+ if "`mode'"=="smcl" local smcltags smcltags
+ local mode0 `mode'
+ if "`mode0'"=="booktabs" local mode0 tex
+ else if "`mode0'"=="csv" {
+ if "`plain'"=="" local csvlhs `"=""'
+ else local csvlhs `"""'
+ }
+ if "`compress'"!="" {
+ if "``mode'_modelwidth'"!="" {
+ local `mode'_modelwidth = ``mode'_modelwidth' - 3
+ }
+ if "``mode'_varwidth'"!="" {
+ local `mode'_varwidth = ``mode'_varwidth' - cond("`label'"!="", 4, 2)
+ }
+ }
+ if `"`modelwidth'"'=="" {
+ if `nocellsopt' & `"``mode'_modelwidth'"'!="" & "`ci'"!="" {
+ local modelwidth = 2*``mode'_modelwidth' - 2
+ if "`wide'"!="" local modelwidth "``mode'_modelwidth' `modelwidth'"
+ }
+ else {
+ local modelwidth "``mode'_modelwidth'"
+ }
+ }
+ if `"`varwidth'"'=="" {
+ local varwidth "``mode'_varwidth'"
+ }
+ if "`plain'"=="" & `matrixmode'==0 {
+ foreach opt in star depvars numbers parentheses notes {
+ SwitchOnIfEmpty `opt' `no`opt''
+ }
+ if "`wide'"=="" & ("`t'"=="" | "`z'`se'`p'`ci'`aux'"!="") & `nocellsopt'==1 ///
+ SwitchOnIfEmpty gaps `nogaps'
+ }
+ if "`plain'"=="" {
+ SwitchOnIfEmpty lines `nolines'
+ }
+ if `"`lines'"'!="" {
+ SwitchOnIfEmpty eqlines `noeqlines'
+ }
+ if inlist("`mode0'", "tab", "csv") {
+ local lines
+ local eqlines
+ }
+ if "`notes'"!="" & "`nolegend'"=="" & `nocellsopt'==1 & `matrixmode'==0 local legend legend
+ if "`plain'"!="" {
+ if "`bfmt'"=="" local bfmt %9.0g
+ if "`tfmt'"=="" local tfmt `bfmt'
+ if "`zfmt'"=="" local zfmt `bfmt'
+ if "`sefmt'"=="" local sefmt `bfmt'
+ if "`pfmt'"=="" local pfmt `bfmt'
+ if "`cifmt'"=="" local cifmt `bfmt'
+ if "`betafmt'"=="" local betafmt `bfmt'
+ }
+ //if "`nomtitles'"!="" local depvars
+ //else if "`depvars'"=="" local mtitles mtitles
+
+// prepare append for rtf, tex, and html
+ local outfilenoteoff2 "`outfilenoteoff'"
+ if "`outfilenoteoff2'"=="" local outfilenoteoff2 "`nooutfilenoteoff'"
+ if `"`using'"'!="" & "`append'"!="" & ///
+ (("`mode0'"=="rtf" & "`fragment'"=="") | ///
+ ("`page'"!="" & inlist("`mode0'", "tex", "html"))) {
+ capture confirm file `using0'
+ if _rc==0 {
+ tempfile appendfile
+ if "`mode'"=="rtf" local `mode'_open
+ else local `mode'_open0
+ local append
+ if "`outfilenoteoff2'"=="" local outfilenoteoff2 outfilenoteoff
+ }
+ }
+
+// cells() option
+ if "`notes'"!="" {
+ if ("`margin'"!="" | `"`margin2'"'!="") & "`nomargin'"=="" ///
+ local thenote "`thenote'Marginal effects"
+ if "`eform'"!="" & "`noeform'"=="" ///
+ local thenote "`thenote'Exponentiated coefficients"
+ }
+ if "`bfmt'"=="" local bfmt a3
+ if `nocellsopt' & `matrixmode'==0 {
+ if "`star'"!="" & "`staraux'"=="" local bstar star
+ if "`beta'"!="" {
+ if "`main'"!="" {
+ di as err "beta() and main() not allowed both"
+ exit 198
+ }
+ if "`betafmt'"=="" local betafmt 3
+ local cells fmt(`betafmt') `bstar'
+ local cells beta(`cells')
+ if "`notes'"!="" {
+ if `"`thenote'"'!="" local thenote "`thenote'; "
+ local thenote "`thenote'Standardized beta coefficients"
+ }
+ }
+ else if "`main'"!="" {
+ tokenize "`main'"
+ if "`2'"=="" local 2 "`bfmt'"
+ local cells fmt(`2') `bstar'
+ local cells `1'(`cells')
+ if "`notes'"!="" {
+ if `"`thenote'"'!="" local thenote "`thenote'; "
+ local thenote "`thenote'`1' coefficients"
+ }
+ }
+ else {
+ local cells fmt(`bfmt') `bstar'
+ local cells b(`cells')
+ }
+ if "`t'"=="" | "`z'`se'`p'`ci'`aux'"!="" {
+ if "`onecell'"!="" {
+ local cells `cells' &
+ }
+// parse aux option
+ tokenize "`aux'"
+ local auxname `1'
+ local auxfmt `2'
+// type of auxiliary statistic
+ local aux `z' `se' `p' `ci' `auxname'
+ if `"`aux'"'=="" local aux t
+ else {
+ if `:list sizeof aux'>1 {
+ di as err "only one allowed of z, se, p, ci, and aux()"
+ exit 198
+ }
+ }
+ if !inlist(`"`aux'"', "t", "z") local abs
+// parentheses/brackets
+ if "`parentheses'"!="" | "`brackets'"!="" {
+ if `"`aux'"'=="ci" {
+ local brackets brackets
+ if "`mode'"!="smcl" | "`onecell'"!="" local paren par
+ else local paren `"par("{ralign @modelwidth:{txt:[}" "{txt:,}" "{txt:]}}")"'
+ }
+ else if "`brackets'"!="" {
+ if "`mode'"!="smcl" | "`onecell'"!="" local paren "par([ ])"
+ else local paren `"par("{ralign @modelwidth:{txt:[}" "{txt:]}}")"'
+ }
+ else {
+ if "`mode'"!="smcl" | "`onecell'"!="" local paren par
+ else local paren `"par("{ralign @modelwidth:{txt:(}" "{txt:)}}")"'
+ }
+ }
+// compose note
+ if "`notes'"!="" {
+ if `"`thenote'"'!="" local thenote "`thenote'; "
+ if `"`auxname'"'!="" {
+ local thenote `"`macval(thenote)'`auxname'"'
+ }
+ else if inlist(`"`aux'"', "t", "z") {
+ if "`abs'"!="" local thenote `"`macval(thenote)'Absolute "'
+ local thenote `"`macval(thenote)'``mode'_`aux'statlab'"'
+ }
+ else if `"`aux'"'=="se" {
+ local thenote `"`macval(thenote)'Standard errors"'
+ }
+ else if `"`aux'"'=="p" {
+ local thenote `"`macval(thenote)'``mode'_pvallab'"'
+ }
+ else if `"`aux'"'=="ci" {
+ local thenote `"`macval(thenote)'``mode'_cilab'"'
+ }
+ if "`parentheses'"=="" {
+ if "`wide'"=="" local thenote `"`macval(thenote)' in second row"'
+ else local thenote `"`macval(thenote)' in second column"'
+ }
+ else if "`brackets'"!="" {
+ local thenote `"`macval(thenote)' in brackets"'
+ }
+ else local thenote `"`macval(thenote)' in parentheses"'
+ }
+// formats
+ if "`tfmt'"=="" local tfmt 2
+ if "`zfmt'"=="" local zfmt 2
+ if "`sefmt'"=="" local sefmt `bfmt'
+ if "`pfmt'"=="" local pfmt 3
+ if "`cifmt'"=="" local cifmt `bfmt'
+ if `"`auxfmt'"'=="" local auxfmt `bfmt'
+ if `"`auxname'"'=="" {
+ local auxfmt ``aux'fmt'
+ }
+// stars
+ if "`staraux'"!="" local staraux star
+// put together
+ local temp fmt(`auxfmt') `paren' `abs' `staraux'
+ local cells `cells' `aux'(`temp')
+ }
+ if "`wide'"!="" local cells cells(`"`cells'"')
+ else local cells cells(`cells')
+ }
+
+// stats() option
+ if `"`macval(stats)'"'=="" & `matrixmode'==0 {
+ if `"`sfmt'"'=="" local sfmt `bfmt'
+ if `"`r2fmt'"'=="" local r2fmt = cond("`plain'"!="", "`bfmt'", "3")
+ if `"`ar2fmt'"'=="" local ar2fmt = cond("`plain'"!="", "`bfmt'", "3")
+ if `"`pr2fmt'"'=="" local pr2fmt = cond("`plain'"!="", "`bfmt'", "3")
+ if `"`aicfmt'"'=="" local aicfmt `bfmt'
+ if `"`bicfmt'"'=="" local bicfmt `bfmt'
+ if "`label'"=="" {
+ local stalabs `"``mode'_ssl'"'
+ }
+ else {
+ local stalabs `"``mode'_lsl'"'
+ }
+ gettoken obslab stalabs: stalabs
+ if "`obs'"=="" & "`obslast'"=="" {
+ local sta N
+ local stalab `"`"`macval(obslab)'"'"'
+ local stafmt %18.0g
+ }
+ local i 0
+ foreach s in r2 ar2 pr2 aic bic {
+ local ++i
+ if "``s''"!="" {
+ local sta `sta' `:word `i' of r2 r2_a r2_p aic bic'
+ local chunk: word `i' of `macval(stalabs)'
+ local stalab `"`macval(stalab)' `"`macval(chunk)'"'"'
+ local stafmt `stafmt' ``s'fmt'
+ }
+ }
+ local i 0
+ CheckScalarOpt `macval(scalars)'
+ foreach addstat of local scalars {
+ local ++i
+ gettoken addstatname addstatlabel: addstat
+ local addstatlabel = substr(`"`macval(addstatlabel)'"',2,.)
+ if `: list posof `"`addstatname'"' in sta' continue
+ if `"`addstatname'"'=="N" & "`obs'"=="" & "`obslast'"!="" continue
+ if trim(`"`macval(addstatlabel)'"')=="" local addstatlabel `addstatname'
+ local addstatfmt: word `i' of `sfmt'
+ if `"`addstatfmt'"'=="" {
+ local addstatfmt: word `: list sizeof sfmt' of `sfmt'
+ }
+ local sta `sta' `addstatname'
+ local stalab `"`macval(stalab)' `"`macval(addstatlabel)'"'"'
+ local stafmt `stafmt' `addstatfmt'
+ }
+ if "`obs'"=="" & "`obslast'"!="" {
+ local sta `sta' N
+ local stalab `"`macval(stalab)' `"`macval(obslab)'"'"'
+ local stafmt `stafmt' %18.0g
+ }
+ if "`sta'"!="" {
+ local stats stats(`sta', fmt(`stafmt') labels(`macval(stalab)'))
+ }
+ }
+
+// table header
+ if `"`macval(mlabels)'"'=="" {
+ if "`mode0'"=="tex" local mspan " span prefix(\multicolumn{@span}{c}{) suffix(})"
+ if `"`depvars'"'!="" {
+ local mlabels `"mlabels(, depvar`mspan')"'
+ }
+ if `"`nomtitles'"'!="" local mlabels `"mlabels(none)"'
+ if "`mtitles'"!="" {
+ local mlabels `"mlabels(, titles`mspan')"'
+ }
+ if `"`macval(mtitles2)'"'!="" {
+ local mlabels `"mlabels(`macval(mtitles2)', titles`mspan')"'
+ }
+ }
+ if `"`macval(collabels)'"'=="" & `nocellsopt' & `matrixmode'==0 & "`plain'"=="" {
+ local collabels `"collabels(none)"'
+ }
+ if "`mode0'"=="tex" & "`numbers'"!="" {
+ local numbers "numbers(\multicolumn{@span}{c}{( )})"
+ }
+
+// pre-/posthead, pre-/postfoot, gaps and lines
+// - complete note
+ if `"`macval(thenote)'"'!="" {
+ local thenote `"`"`macval(thenote)'"'"'
+ }
+ if `"`macval(note)'"'!="" {
+ local thenote `""@note""'
+ }
+ if `"`macval(addnotes)'"'!="" {
+ if index(`"`macval(addnotes)'"', `"""')==0 {
+ local addnotes `"`"`macval(addnotes)'"'"'
+ }
+ local thenote `"`macval(thenote)' `macval(addnotes)'"'
+ }
+ if "`legend'"!="" {
+ if ("`margin'"!="" | `"`margin2'"'!="") & ///
+ "`nomargin'"=="" & "`nodiscrete'"=="" {
+ local thenote `"`macval(thenote)' "@discrete""'
+ }
+ if "`star'"!="" | `nocellsopt'==0 {
+ local thenote `"`macval(thenote)' "@starlegend""'
+ }
+ }
+// - mode specific settings
+ if "`star'"!="" {
+ if `"`macval(star2)'"'!="" {
+ FormatStarSym "`mode0'" `"`macval(star2)'"'
+ local `mode'_starlevels `"`macval(star2)'"'
+ }
+ if `"`macval(starlevels)'"'=="" {
+ local starlevels `"starlevels(`macval(`mode'_starlevels)'`macval(`mode'_starlevlab)')"'
+ }
+ }
+ foreach opt in begin delimiter end substitute {
+ if `"`macval(`opt')'"'=="" & `"``mode'_`opt''"'!="" {
+ local `opt' `"`opt'(``mode'_`opt'')"'
+ }
+ }
+ if "`onecell'"!="" {
+ if `"`macval(incelldelimiter)'"'=="" {
+ local incelldelimiter `"incelldelimiter(``mode'_incelldel')"'
+ }
+ }
+ if "`noabbrev'`abbrev'"=="" {
+ local abbrev ``mode'_abbrev'
+ }
+ if `"`fragment'"'=="" {
+ if "`page'"!="" {
+ if `"`page2'"'!="" {
+ local texpkgs `""\usepackage{`page2'}""'
+ }
+ local opening `"``mode'_open0'"'
+ }
+ if `"`macval(title)'"'!="" {
+ local opening `"`macval(opening)' ``mode'_open'"'
+ if "`mode0'"=="tex" & "`star'"!="" {
+ local opening `"`macval(opening)' "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}""'
+ }
+ if !("`longtable'"!="" & "`mode0'"=="tex") {
+ local opening `"`macval(opening)' ``mode'_caption'"'
+ }
+ }
+ else if "`mode0'"=="tex" & "`star'"!="" {
+ local opening `"`macval(opening)' "{" "\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}""'
+ }
+ else if "`mode0'"!="tex" {
+ local opening `"`macval(opening)' ``mode'_open'"'
+ }
+ local opening `"`macval(opening)' ``mode'_open2'"'
+ if "`mode0'"=="tex" {
+ if `"`labcol2'"'!="" local lstubtex "lc"
+ else local lstubtex "l"
+ if `"`width'"'!="" local extracolsep "@{\hskip\tabcolsep\extracolsep\fill}"
+ if `"`macval(alignment)'"'!="" {
+ local opening `"`macval(opening)'{`extracolsep'`lstubtex'*{@E}{`macval(alignment)'}}"'
+ }
+ else {
+ if `nocellsopt' {
+ MakeTeXColspec "`wide'" "`not'" "`star'" "`stardetach'" "`staraux'"
+ }
+ else {
+ MakeTeXColspecAlt, `cells'
+ }
+ local opening `"`macval(opening)'{`extracolsep'`lstubtex'*{@E}{`value'}}"'
+ }
+ if "`longtable'"!="" {
+ if `"`macval(title)'"'!="" {
+ local opening `"`macval(opening)' ``mode'_caption'\\\"'
+ }
+ }
+ }
+ if "`mode0'"=="html" {
+ local brr
+ foreach chunk of local thenote {
+ local closing `"`macval(closing)' `"`brr'`macval(chunk)'"'"'
+ local brr "
"
+ }
+ if `"`macval(closing)'"'!="" {
+ local closing `""" `macval(closing)' " |
""'
+ }
+ }
+ else if "`mode0'"=="tex" {
+ foreach chunk of local thenote {
+ local closing `"`macval(closing)' `"\multicolumn{@span}{l}{\footnotesize `macval(chunk)'}\\\"'"'
+ }
+ }
+ else if "`mode0'"=="csv" {
+ foreach chunk of local thenote {
+ local closing `"`macval(closing)' `"`csvlhs'`macval(chunk)'""'"'
+ }
+ }
+ else if "`mode0'"=="rtf" {
+ foreach chunk of local thenote {
+ local closing `"`macval(closing)' `"{\pard\ql\fs20 `macval(chunk)'\par}"'"'
+ }
+ }
+ else {
+ local closing `"`macval(thenote)'"'
+ }
+ local closing `"`macval(closing)' ``mode'_close2'"'
+ if `"`macval(title)'"'!="" | "`mode0'"!="tex" {
+ local closing `"`macval(closing)' ``mode'_close'"'
+ }
+ else if "`mode0'"=="tex" & "`star'"!="" {
+ local closing `"`macval(closing)' }"'
+ }
+ if "`page'"!="" {
+ local closing `"`macval(closing)' ``mode'_close0'"'
+ }
+ local toprule `"``mode'_toprule'"'
+ local bottomrule `"``mode'_bottomrule'"'
+ local topgap `"``mode'_topgap'"'
+ local bottomgap `"``mode'_bottomgap'"'
+ }
+ local midrule `"``mode'_midrule'"'
+ local midgap `"``mode'_midgap'"'
+ local eqrule `"``mode'_eqrule'"'
+// - compose prehead()
+ if `"`macval(prehead)'"'=="" {
+ if `"`lines'"'!="" {
+ local opening `"`macval(opening)' `macval(toprule)'"'
+ }
+ else if `"`gaps'"'!="" {
+ local opening `"`macval(opening)' `macval(topgap)'"'
+ }
+ SaveRetok `macval(opening)'
+ local opening `"`macval(value)'"'
+ if `"`macval(opening)'"'!="" {
+ local prehead `"prehead(`macval(opening)')"'
+ }
+ }
+// - compose posthead()
+ if `"`macval(posthead)'"'=="" {
+ if `"`lines'"'!="" {
+ local posthead `"posthead(`macval(midrule)')"'
+ }
+ else if `"`gaps'"'!="" {
+ local posthead `"posthead(`macval(midgap)')"'
+ }
+ }
+// - compose prefoot()
+ if `"`macval(prefoot)'"'=="" & `"`macval(stats)'"'!="" {
+ if `"`lines'"'!="" {
+ local prefoot `"prefoot(`macval(midrule)')"'
+ }
+ else if `"`gaps'"'!="" {
+ local prefoot `"prefoot(`macval(midgap)')"'
+ }
+ if `"`cells'"'=="cells(none)" local prefoot
+ }
+// - compose postfoot()
+ if `"`macval(postfoot)'"'=="" {
+ if `"`lines'"'!="" {
+ local closing `"`macval(bottomrule)' `macval(closing)'"'
+ }
+ else if `"`gaps'"'!="" {
+ local closing `"`macval(bottomgap)' `macval(closing)'"'
+ }
+ SaveRetok `macval(closing)'
+ local closing `"`macval(value)'"'
+ if `"`macval(closing)'"'!="" {
+ local postfoot postfoot(`macval(closing)')
+ }
+ }
+// - varlabels
+ if `"`macval(varlabels)'"'=="" {
+ if `"`gaps'"'!="" {
+ local varl `", end("" `macval(midgap)') nolast"'
+ }
+ if "`label'"!="" {
+ local varl `"_cons Constant`macval(varl)'"'
+ }
+ if `"`macval(coeflabels)'"'!="" {
+ local varl `"`macval(coeflabels)' `macval(varl)'"'
+ }
+ if trim(`"`macval(varl)'"')!="" {
+ local varlabels varlabels(`macval(varl)')
+ }
+ }
+// - equation labels
+ if ("`eqlines'"!="" | `"`gaps'"'!="") & "`unstack'"=="" {
+ if trim(`"`eqlabels'"')!="none" {
+ ParseEqLabels `macval(eqlabels)'
+ if `eqlabelsok' {
+ _parse comma eqllhs eqlrhs : eqlabels
+ if `"`eqlrhs'"'=="" local eqlabelscomma ", "
+ else local eqlabelscomma " "
+ if "`eqlines'"!=""{
+ local eqlabels `"`macval(eqlabels)'`eqlabelscomma'`macval(eqrule)' nofirst"'
+ }
+ else if `"`gaps'"'!="" {
+ local eqlabels `"`macval(eqlabels)'`eqlabelscomma'begin(`macval(midgap)' "") nofirst"'
+ }
+ }
+ }
+ }
+ if `"`macval(eqlabels)'"'!="" {
+ local eqlabels `"eqlabels(`macval(eqlabels)')"'
+ }
+
+// noconstant option
+ if `"`drop'"'=="" {
+ if "`noconstant'"!="" {
+ local drop drop(_cons, relax)
+ }
+ }
+
+// compute beta coefficients (run estadd to add e(beta))
+ if "`beta'"!="" {
+ local estnames `"`anything'"'
+ if `"`estnames'"'=="" {
+ capt est_expand $eststo
+ if !_rc {
+ local estnames `"$eststo"'
+ }
+ }
+ version `caller': estadd beta, replace: `estnames'
+ }
+
+// use tempfile for new table
+ if `"`appendfile'"'!="" {
+ local using `"using `"`appendfile'"'"'
+ }
+
+// execute estout
+ if `"`varwidth'"'!="" local varwidth `"varwidth(`varwidth')"'
+ if `"`modelwidth'"'!="" local modelwidth `"modelwidth(`modelwidth')"'
+ if `"`style'"'=="" local style "style(esttab)"
+ CleanEstoutCmd `anything' `using' , ///
+ `macval(cells)' `drop' `nomargin' `margin' `margin2' `noeform' `eform' ///
+ `nodiscrete' `macval(stats)' `stardetach' `macval(starlevels)' ///
+ `varwidth' `modelwidth' `noabbrev' `abbrev' `unstack' `macval(begin)' ///
+ `macval(delimiter)' `macval(end)' `macval(incelldelimiter)' `smcltags' ///
+ `macval(title)' `macval(prehead)' `macval(posthead)' `macval(prefoot)' ///
+ `macval(postfoot)' `label' `macval(varlabels)' `macval(mlabels)' `nonumbers' ///
+ `numbers' `macval(collabels)' `macval(eqlabels)' `macval(mgroups)' ///
+ `macval(note)' `macval(labcol2)' `macval(substitute)' `append' ///
+ `notype'`type' `outfilenoteoff2' level(`level') `style' `macval(options)'
+ if "`noisily'"!="" {
+ gettoken chunk rest: cmd, parse(",")
+ di as txt _asis `"`chunk'"' _c
+ gettoken chunk rest: rest, bind
+ while `"`macval(chunk)'"'!="" {
+ di as txt _asis `" `macval(chunk)'"'
+ gettoken chunk rest: rest, bind
+ }
+ }
+ `macval(cmd)'
+
+// insert new table into existing document (tex, html, rtf)
+ if `"`appendfile'"'!="" {
+ local enddoctex "\end{document}"
+ local enddochtml "