********************************************************************
********************************************************************
****		Online supplement: Code for MAIHDA analysis																
****  		Title manuscript: "Intersectional inequalities in 
****		mental health by education, income, gender, and age 
****		before and during the COVID-19 pandemic in the 
****		Netherlands: A longitudinal study"
****
****		Author: S.E. Verra													
****		Adapted from: code developed by C. Evans
********************************************************************
********************************************************************
   
*************************************
****    CODEBOOK FOR VARIABLES    ***
*************************************
/*

1157 observations in 53 strata (of 54 possible)

Gender
		1 = 'female'
		2 = 'male'
		
education
		1 = 'low'
		2 = 'intermediate'
		3 = 'high'

income
		1 = 'low income'
		2 = 'intermediate income'
		3 = 'high income'

age
		1 = '25 to 39 yrs'
		2 = '40 to 64 yrs'
		3 = '65 yrs and older' 

Mentalhealth14 = score in 2014
mentalhealth21 = score in 2021
ChangeMH = score 2021 - score 2014

*/

**************************************************************
******											
****** 		 Prep Log and Other Setup Stuff 			
******												
**************************************************************	

clear

cd "Z:\Stata"

capture log close
log using "Z:\MAIHDA", replace

set more off

set cformat %9.1f

sysdir set PLUS "Z:\plus"
global MLwiN_path "C:\Program Files\MLwiN v3.06\mlwin.exe"
global MLwiNScript_path "C:\Program Files\MLwiN v3.06\mlnscript.exe"

**************************************************************
******													
****** 		 Examine Data and Set Key Values			
******													
**************************************************************

use "Z:\Data aangepast\GLOBE n=1157.dta", clear

*** Generate variable which records stratum size
bysort stratum: generate n = _N
order stratum n 

*** Construct individual ID variable
generate individual = _n
order individual, after(stratum)

*** Construct Constant and Denomincator Vectors for use in MLwiN ***
generate cons = 1
generate denomintator = 1

recast float mentalhealth14 mentalhealth21 ChangeMH, force 

*** Construct Dummy Variables for Main Effects for Use Later ***
tabulate Gender14, gen(dum)
	rename dum1 female
	rename dum2 male
tabulate age3, gen(dum)
	rename dum1 young_age
	rename dum2 mid_age
	rename dum3 old_age
tabulate Edu3_14, gen(dum)
	rename dum1 low_edu
	rename dum2 mid_edu
	rename dum3 high_edu
tabulate Inc3_14, gen(dum)
	rename dum1 low_inc
	rename dum2 mid_inc
	rename dum3 high_inc

save, replace


******************************************************************
******														
****** 		Create Temp Data Set						 	
******														
******************************************************************

use "Z:\Data aangepast\GLOBE n=1157.dta", clear
by stratum, sort: generate selectfromlist = (_n==1) 
drop if selectfromlist == 0 
keep stratum low_edu mid_edu high_edu low_inc mid_inc high_inc male female young_age mid_age old_age ChangeMH mentalhealth14 n mentalhealth21
save "strata.dta", replace

* count number of strata
tab stratum, nofreq 
display r(r)
* 53 strata

******************************************************************
******														
****** 		DESCRIPTIVE STATISTICS					 	
******														
******************************************************************

use "Z:\Data aangepast\GLOBE n=1157.dta", clear

sort stratum individual 

*** Examine distribution of outcome variables 
histogram mentalhealth14, bin(25) percent ytitle(Percentage of participants) xtitle(Mental health score 2014) title(Distribution of mental health score 2014) 
histogram mentalhealth21, bin(25) percent ytitle(Percentage of participants) xtitle(Mental health score 2021) title(Distribution of mental health score 2021) 
histogram ChangeMH, bin(25) percent ytitle(Percentage of participants) xtitle(Change in mental health status 2014-2021) title(Distribution of change in mental health score (2014-2021)) 

*** Examine categories 
tabulate Gender14 
tabulate age3 
tabulate Edu3_14 
tabulate Inc3_14 

*** Distribution of sample across intersectional strata 
tabulate stratum 

******************************************************************
******														
****** 		TABLE 1				 	
******														
******************************************************************

*** Summarize the outcomes across total sample
tabstat mentalhealth14, statistics(n mean p50 sd median min max ) format(%3.1f)
tabstat mentalhealth21, statistics(n mean p50 sd median min max ) format(%3.1f)
tabstat ChangeMH, statistics(n mean p50 sd median min max ) format(%3.1f)

*** Summarize the outcomes across each variable of interest
sort Gender14
by Gender14: tabstat mentalhealth14, statistics(mean sd)
by Gender14: tabstat mentalhealth21, statistics(mean sd)
by Gender14: tabstat ChangeMH, statistics(mean sd)
sort age3
by age3: tabstat mentalhealth14, statistics(mean sd)
by age3: tabstat mentalhealth21, statistics(mean sd)
by age3: tabstat ChangeMH, statistics(mean sd)
sort Edu3_14
by Edu3_14: tabstat mentalhealth14, statistics(mean sd)
by Edu3_14: tabstat mentalhealth21, statistics(mean sd)
by Edu3_14: tabstat ChangeMH, statistics(mean sd)
sort Inc3_14
by Inc3_14: tabstat mentalhealth14, statistics(mean sd)
by Inc3_14: tabstat mentalhealth21, statistics(mean sd)
by Inc3_14: tabstat ChangeMH, statistics(mean sd)

*** Compare to stratum means

collapse (sum) n = cons ///
		 (mean) CMH_stratum_mean = ChangeMH ///
		 (mean) MH14_stratum_mean = mentalhealth14 ///
		 (mean) MH21_stratum_mean = mentalhealth21 , ///
		 by(stratum Gender14 age3 Edu3_14 Inc3_14)

tabstat CMH_stratum_mean, statistics(n mean sd median min max)
tabstat MH14_stratum_mean, statistics(n mean sd median min max)
tabstat MH21_stratum_mean, statistics(n mean sd median min max)


******************************************************************
******														
****** 		TABLE 2: stratum-level descriptive statistics				 	
******														
******************************************************************

*** Load the stratum-level data
use "strata.dta", clear

*** Generate binary indicators for whether each stratum has more than X individuals

generate nlessthan5 = (n < 5)
generate nmorethan5 = (n >= 5)
generate n5to9 = (n >= 5 & n<10)
generate n10to14 = (n >= 10 & n<15)
generate n15to19 = (n >= 15 & n<20)
generate n20to24 = (n >= 20 & n<25)
generate n25to29 = (n >= 25 & n<30)
generate n30plus = (n >= 30)

*** Tabulate the binary indicators

tabulate nlessthan5
tabulate n5to9
tabulate n10to14
tabulate n15to19
tabulate n20to24
tabulate n25to29
tabulate n30plus
tabulate nmorethan5

sort n

list stratum n if n < 10
list stratum n if n < 5

******************************************************************
******														
****** 		Fit models using Bayesian MCMC in MLwiN 		
******														
******************************************************************

******************************************************************
******														
****** 		OUTCOME 1: MENTAL HEALTH SCORE 2014				
******														
******************************************************************
use "Z:\Data aangepast\GLOBE n=1157.dta", clear

recast float mentalhealth14
sort stratum individual

*** Fit model using PQL2/quasilikelohood to determine mcmc initialization
runmlwin mentalhealth14 cons , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls  ///
  nopause
 
*** Fit model using MCMC
runmlwin mentalhealth14 cons , ///
  level2(stratum: cons, residuals(u, savechains("m14a_u.dta",replace))) /// saves residuals for each stratum
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m14a_beta.dta", replace)) initsprevious /// saves beta&variance parameters for the models
  nopause
  drop u0se
  
*** Calculate the VPC / ICC from the chains
use "m14a_beta.dta", clear
rename RP2_var_cons_ sigma2u14A
rename RP1_var_cons_ sigma2e14A
generate icc = sigma2u14A/(sigma2u14A + sigma2e14A)
mcmcsum icc, variables

***  store for PCV calculation 
summarize sigma2u14A
scalar sigma2u14A =r(mean)
di scalar(sigma2u14A)

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS 2014A
*------------------------------------------------------------------*
use "m14a_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m14a_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS 2014A
*------------------------------------------------------------------*
use "m14a_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m14a_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER 2014A
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m14a_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m14a_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m14a_data_prepped.dta", replace

*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST 2014A
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m14a_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = b_cons*cons + u
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = b_cons*cons
label var fixedeffect "Expected value based only on the intercept"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m14a_results.dta", replace 

********************************************************************
* MODEL 2 - MAIN EFFECTS MODEL 2014B
********************************************************************
*** Load the data
use "Z:\Data aangepast\GLOBE n=1157.dta", clear
 
recast float mentalhealth14
sort stratum individual 

*** Set output format of coefficients, SEs, and confidence limits to 1dp
set cformat %9.1f

*** Fit model using PQL2
runmlwin mentalhealth14 cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls ///
  nopause
  
*** Fit model using MCMC
runmlwin mentalhealth14 cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons, residuals(u, savechains("m14b_u.dta", replace))) /// 
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m14b_beta.dta", replace)) initsprevious /// 
  nopause
drop u0se

*** Calculate the VPC / ICC from the chains
use "m14b_beta.dta", clear
rename RP2_var_cons_ sigma2u14B
rename RP1_var_cons_ sigma2e14B
generate icc = 100*sigma2u14B/(sigma2u14B + sigma2e14B)
mcmcsum icc, variables

*** Calculate the Proportional Change in Variance (PCV) (as a percentage)
generate pcv = 100*((sigma2u14A - sigma2u14B) / sigma2u14A)
summarize pcv

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS 2014B
*------------------------------------------------------------------*

use "m14b_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m14b_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS 2014B
*------------------------------------------------------------------*

use "m14b_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m14b_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER 2014B
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m14b_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m14b_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m14b_data_prepped.dta", replace

*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST 2014B
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m14b_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						+ u )
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						)
label var fixedeffect "Expected value based only on main effects"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m14b_results.dta", replace 

*** List strata with statistically significant interaction effects 
use "m14b_results.dta", clear

list stratum  REmn RElo REhi if RElo<0
list stratum  REmn RElo REhi if RElo>0

******************************************************************
******														
****** 		OUTCOME 2: MENTAL HEALTH SCORE 2021				
******														
******************************************************************

******************************************************************
*** MODEL 1, Null MODEL for CHANGE IN MENTAL HEALTH 2021A
******************************************************************
*** Load the data
use "Z:\Data aangepast\GLOBE n=1157.dta", clear

sort stratum individual

*** Set output format of coefficients, SEs, and confidence limits to 1dp
set cformat %9.1f

*** Fit model using PQL2/quasilikelohood to determine mcmc initialization
runmlwin mentalhealth21 cons , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls ///
  nopause
  
*** Fit model using MCMC
runmlwin mentalhealth21 cons , ///
  level2(stratum: cons, residuals(u, savechains("m21a_u.dta",replace))) /// saves residuals for each stratum
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m21a_beta.dta", replace)) initsprevious /// saves beta&variance parameters for the models
  nopause
  drop u0se
  
*** Calculate the VPC / ICC from the chains
use "m21a_beta.dta", clear
rename RP2_var_cons_ sigma2u21A
rename RP1_var_cons_ sigma2e21A
generate icc = sigma2u21A/(sigma2u21A + sigma2e21A)
mcmcsum icc, variables

***  store for PCV calculation 
summarize sigma2u21A
scalar sigma2u21A =r(mean)
di scalar(sigma2u21A)

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS 2021A
*------------------------------------------------------------------*
use "m21a_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m21a_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS 2021A
*------------------------------------------------------------------*
use "m21a_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m21a_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER 2021A
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m21a_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m21a_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m21a_data_prepped.dta", replace

*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST 2021A
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m21a_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = b_cons*cons + u
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = b_cons*cons
label var fixedeffect "Expected value based only on the intercept"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m21a_results.dta", replace 

********************************************************************
* MODEL 2 - MAIN EFFECTS MODEL 2021B
********************************************************************

*** Load the data

use "Z:\Data aangepast\GLOBE n=1157.dta", clear
sort stratum individual 

*** Set output format of coefficients, SEs, and confidence limits to 1dp
set cformat %9.1f

*** Fit model using PQL2
runmlwin mentalhealth21 cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls ///
  nopause
  
*** Fit model using MCMC
runmlwin mentalhealth21 cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons, residuals(u, savechains("m21b_u.dta", replace))) /// 
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m21b_beta.dta", replace)) initsprevious /// 
  nopause
drop u0se

*** Calculate the VPC / ICC from the chains
use "m21b_beta.dta", clear
rename RP2_var_cons_ sigma2u21B
rename RP1_var_cons_ sigma2e21B
generate icc = sigma2u21B/(sigma2u21B + sigma2e21B)
mcmcsum icc, variables

*** Calculate the Proportional Change in Variance (PCV) (as a percentage)
generate pcv = 100*((sigma2u21A - sigma2u21B) / sigma2u21A)
summarize pcv

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS 2021B
*------------------------------------------------------------------*
use "m21b_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m21b_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS 2021B
*------------------------------------------------------------------*
use "m21b_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m21b_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER 2021B
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m21b_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m21b_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m21b_data_prepped.dta", replace

*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST 2021B
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m21b_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						+ u )
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						)
label var fixedeffect "Expected value based only on main effects"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m21b_results.dta", replace 

*** List strata with statistically significant interaction effects 
use "m21b_results.dta", clear
list stratum  REmn RElo REhi if REhi<0
list stratum  REmn RElo REhi if RElo>0

*** Creating data files for a figure of MH change per intersection
use "m21b_results.dta", clear
keep stratum n expmn explo exphi FEmn FElo FEhi REmn RElo REhi 
sort stratum 
compress
save "scores2021.dta", replace

use "m14b_results.dta", clear
keep stratum n expmn explo exphi FEmn FElo FEhi REmn RElo REhi 
sort stratum 
compress
save "scores2014.dta", replace

******************************************************************
******														
****** 		OUTCOME 3: CHANGE IN MENTAL HEALTH SCORE 		
******  				2014 - 2021							
******														
******************************************************************

******************************************************************
* MODEL 1, Null MODEL for CHANGE IN MENTAL HEALTH
******************************************************************
use "Z:\Data aangepast\GLOBE n=1157.dta", clear

sort stratum individual

*** Set output format of coefficients, SEs, and confidence limits to 1dp
set cformat %9.1f

*** Fit model using PQL2/quasilikelohood to determine mcmc initialization
runmlwin ChangeMH cons , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls ///
  nopause
  
*** Fit model using MCMC
runmlwin ChangeMH cons , ///
  level2(stratum: cons, residuals(u, savechains("m1_u.dta",replace))) /// saves residuals for each stratum
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m1_beta.dta", replace)) initsprevious /// saves beta&variance parameters for the models
  nopause
  drop u0se
  
*** Calculate the VPC / ICC from the chains
use "m1_beta.dta", clear
rename RP2_var_cons_ sigma2uCA
rename RP1_var_cons_ sigma2eCA
generate icc = sigma2uCA/(sigma2uCA + sigma2eCA)
mcmcsum icc, variables

***  store for PCV calculation 
summarize sigma2uCA
scalar sigma2uCA =r(mean)
di scalar(sigma2uCA)

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS CMHA
*------------------------------------------------------------------*
use "m1_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m1_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS CMHA
*------------------------------------------------------------------*
use "m1_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m1_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER CMHA
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m1_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m1_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m1_data_prepped.dta", replace


*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST CMHA
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m1_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = b_cons*cons + u
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = b_cons*cons
label var fixedeffect "Expected value based only on the intercept"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m1_results.dta", replace 

********************************************************************
* MODEL 2 - MAIN EFFECTS MODEL CMHB
********************************************************************
*** Load the data
use "Z:\Data aangepast\GLOBE n=1157.dta", clear
sort stratum individual 

*** Set output format of coefficients, SEs, and confidence limits to 1dp
set cformat %9.1f

*** Fit model using PQL2
runmlwin ChangeMH cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons) ///
  level1(individual: cons) ///
  rigls ///
  nopause
 
*** Fit model using MCMC
runmlwin ChangeMH cons female young_age mid_age low_edu mid_edu low_inc mid_inc , ///
  level2(stratum: cons, residuals(u, savechains("m2_u.dta", replace))) /// 
  level1(individual: cons) ///
  mcmc(burnin(5000) chain(50000) thinning(50) ///
    savechains("m2_beta.dta", replace)) initsprevious /// 
  nopause
drop u0se

*** Calculate the VPC / ICC from the chains
use "m2_beta.dta", clear
rename RP2_var_cons_ sigma2uCB
rename RP1_var_cons_ sigma2eCB
generate icc = sigma2uCB /(sigma2uCB + sigma2eCB)
mcmcsum icc, variables

*** Calculate the Proportional Change in Variance (PCV) (as a percentage)
generate pcv = 100*((sigma2uCA - sigma2uCB) / sigma2uCA)
summarize pcv

*------------------------------------------------------------------*
* PREPARE FIXED-PART PAREMETER CHAINS CMHB
*------------------------------------------------------------------*
use "m2_beta.dta", clear
drop deviance RP2_var_cons_ RP1_var_cons_
rename FP1_* b_*
format %9.2f b_*
compress
save "m2_beta_prepped.dta", replace
isid iteration
codebook iteration, compact

*------------------------------------------------------------------*
* PREPARE STRATUM RANDOM EFFECTS CHAINS CMHB
*------------------------------------------------------------------*
use "m2_u.dta", clear
drop residual idnum
rename value u
format %9.2f u
sort stratum iteration
order stratum iteration
compress
save "m2_u_prepped.dta", replace
isid stratum iteration
codebook iteration, compact

*------------------------------------------------------------------*
* MERGE DATA, FIXED-PART PARAMETER AND RANDOM EFFECT CHAINS TOGETHER CMHB
*------------------------------------------------------------------*
use "strata.dta", clear
isid stratum
cross using "m2_beta_prepped.dta"
isid stratum iteration
sort stratum iteration
merge 1:1 stratum iteration using "m2_u_prepped.dta", nogenerate assert(match)
isid stratum iteration
compress
save "m2_data_prepped.dta", replace


*------------------------------------------------------------------*
* CALCULATE VALUES OF INTEREST CMHB
*------------------------------------------------------------------*
*** Expected value based on fixed and random part
use "m2_data_prepped.dta", clear 
gen cons = 1 
generate expectedvalue = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						+ u )
label var expectedvalue "Expected value based on main effects and interactions"
format %9.3f expectedvalue

*** Expected value based only on the fixed-part
generate fixedeffect = (b_cons*cons ///
						+ b_female*female ///
						+ b_young_age*young_age ///
						+ b_mid_age*mid_age ///
						+ b_low_edu*low_edu ///
						+ b_mid_edu*mid_edu ///
						+ b_low_inc*low_inc ///
						+ b_mid_inc*mid_inc ///
						)
label var fixedeffect "Expected value based only on main effects"
format %9.3f fixedeffect

*** Expected value based only on the random-part  
generate randomeffect = u
label var randomeffect "Random Effect"
format %9.3f randomeffect

*** Calculate the mean, 2.5th and 97.5th percentiles of the MCMC chains
bysort stratum (iteration): egen expmn = mean(expectedvalue)
bysort stratum (iteration): egen explo = pctile(expectedvalue), p(2.5)
bysort stratum (iteration): egen exphi = pctile(expectedvalue), p(97.5)
format %9.3f expmn explo exphi

bysort stratum (iteration): egen FEmn = mean(fixedeffect)
bysort stratum (iteration): egen FElo = pctile(fixedeffect), p(2.5)
bysort stratum (iteration): egen FEhi = pctile(fixedeffect), p(97.5)
format %9.3f FEmn FElo FEhi

bysort stratum (iteration): egen REmn = mean(randomeffect)
bysort stratum (iteration): egen RElo = pctile(randomeffect), p(2.5)
bysort stratum (iteration): egen REhi = pctile(randomeffect), p(97.5)
format %9.3f REmn RElo REhi

*** Drop chains and just keep their summaries (mean, 2.5th and 97.5th)
drop iteration b* u* expectedvalue fixedeffect randomeffect
duplicates drop
isid stratum

*** Ranks
sort expmn
generate exprank = _n
order exprank, after(exphi)
sort FEmn
generate FErank = _n
order FErank, after(FEhi)
sort REmn
generate RErank = _n
order RErank, after(REhi)

*** Sort the data
sort stratum
isid stratum

*** Compress and save the data
compress
save "m2_results.dta", replace 

*** List strata with statistically significant interaction effects 
use "m2_results.dta", clear
list stratum  REmn RElo REhi if REhi<0
list stratum  REmn RElo REhi if RElo>0

*** Close log file
capture log close

********************************************************************************
exit





