-
Notifications
You must be signed in to change notification settings - Fork 7
/
importMplus.R
244 lines (200 loc) · 7.33 KB
/
importMplus.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# A function that takes the output of Mplus and reads it to an mlVAR object. Can be used to make changes to codes.
importMplus <- function(outfile){
# Read output:
foo <- capture.output(output <- suppressMessages(suppressWarnings(readModels(outfile,what = "all"))))
# Read results into R:
# saveInfo <- suppressWarnings(getSavedata_Fileinfo(outfile))
saveInfo <- output$savedata_info
# Read samples into R:
bayesSamples <- output$bparameters$valid_draw
#suppressWarnings(getSavedata_Bparams(outfile) )
if (!is(bayesSamples,"mcmc")){
bayesSamples <- do.call(rbind,bayesSamples)
}
# Read data into R:
Data <- read.table(gsub("\\.out",".dat",outfile),na.strings = ".")
names(Data) <- unlist(strsplit(output$input$variable$names,split = " "))
# Read mlVAR model into R:
mlvarFile <- gsub("\\.out",".mlVARmodel",outfile)
if (!file.exists(mlvarFile)){
stop(paste0("mlVAR output not found, expected a file ",mlvarFile))
}
mlVARinfo <- read.table(mlvarFile,header=TRUE,stringsAsFactors=FALSE)
# Names of headers in samples:
sampleNames <- saveInfo$bayesVarNames
sampleNames <- gsub("^Parameter\\.\\d*\\_","",sampleNames)
### Collect the results ####
Results <- list()
# Outcomes:
Outcomes <- unique(mlVARinfo$dep)
nOut <- length(Outcomes)
# Predictors:
Predictors <- unique(mlVARinfo$pred)
nPred <- length(Predictors)
# Number of lags:
Lags <- sort(unique(mlVARinfo$lag))
Lags <- Lags[Lags>0]
nLag <- length(Lags)
# Number of samples:
nSample <- nrow(bayesSamples)
if (!identical(Outcomes,Predictors)){
stop("Mplus estimation with different predictors than outcomes is not yet supported.")
}
### BETWEEN SUBJECTS ###
# Always random
# Gather the variance--covariance matrices:
Omega_mu_cov_samples <- array(,c(nOut, nOut, nSample))
for (i in 1:nOut){
for (j in i:nOut){
# Name of column:
if (i == j){
colName <- paste0("%BETWEEN%:.",toupper(Outcomes[i]))
colID <- which(sampleNames == colName)
Omega_mu_cov_samples[i,j,] <- bayesSamples[,colID]
} else {
colName <- paste0("%BETWEEN%:.",toupper(Outcomes[j]),".WITH.",toupper(Outcomes[i]))
colID <- which(sampleNames == colName)
Omega_mu_cov_samples[i,j,] <- Omega_mu_cov_samples[j,i,] <- bayesSamples[,colID]
}
}
}
# Store to output:
Results[["Omega_mu"]] <- covSamples_Mplus(Omega_mu_cov_samples)
### TEMPORAL NETWORK ###
tempModel <- unique(mlVARinfo[mlVARinfo$model == "temporal","random"])
if (length(tempModel) > 1){
stop("Temporal model is a mixture of fixed/orthogonal/correlated")
}
subModel <- mlVARinfo %>% dplyr::filter(.data[['model']] == "temporal")
# Gather the parameter samples:
BetaFixed <- array(,c(nOut, nPred, nLag,nSample))
BetaSD <- array(0,c(nOut, nPred, nLag,nSample))
if (tempModel != "fixed"){
for (i in 1:nOut){
for (j in 1:nPred){
for (l in 1:nLag){
# Name of parameter:
parName <- mlVARinfo$par[mlVARinfo$dep == Outcomes[i] & mlVARinfo$pred == Predictors[j] & mlVARinfo$lag == Lags[l]]
if (length(parName) == 1){
# Fixed effect:
sampleParName <- paste0("%BETWEEN%:.MEAN.",toupper(parName))
sampleParID <- which(sampleNames == sampleParName)
BetaFixed[i,j,l,] <- bayesSamples[,sampleParID]
# Standard deviation:
sampleParName <- paste0("%BETWEEN%:.",toupper(parName))
sampleParID <- which(sampleNames == sampleParName)
BetaSD[i,j,l,] <- bayesSamples[,sampleParID]
}
}
}
}
} else {
### FIXED EFFECTS ###
for (i in 1:nOut){
for (j in 1:nPred){
for (l in 1:nLag){
# Name of column:
colName <- paste0("%WITHIN%:.",toupper(Outcomes[1]),".ON.",toupper(Predictors[j]),"&",Lags[l])
# Fixed effect:
sampleParID <- which(sampleNames == colName)
BetaFixed[i,j,l,] <- bayesSamples[,sampleParID]
}
}
}
}
# Store to output:
Results[["Beta"]] <- parSamples_Mplus(BetaFixed,BetaSD)
### CONTEMPORANEOUS EFFECTS ###
conModel <- unique(mlVARinfo[grepl("cont",mlVARinfo$model),"random"])
# Factor names:
submodel <- mlVARinfo[mlVARinfo$model == "cont cov",]
# For every cov, create a dummy factors with equal factor loadings:
dummyFactors <- paste0("Fac",seq_len(nrow(submodel)))
if (length(conModel) > 1){
stop("Contemporaneous model is a mixture of fixed/orthogonal/correlated")
}
if (conModel != "fixed"){
# First collect the matrix as is:
Theta_samples <- array(,c(nOut, nOut, nSample))
for (i in 1:nOut){
for (j in i:nOut){
# Name of column:
# Name of parameter:
parName <- mlVARinfo$par[mlVARinfo$dep == Outcomes[i] & mlVARinfo$pred == Predictors[j] & mlVARinfo$lag == 0]
if (length(parName) == 1){
# Fixed effect:
sampleParName <- paste0("%BETWEEN%:.MEAN.",toupper(parName))
sampleParID <- which(sampleNames == sampleParName)
Theta_samples[i,j,] <- Theta_samples[j,i,] <- exp(bayesSamples[,sampleParID])
}
}
}
# Read signs into R:
signsFile <- gsub("\\.out",".mlVARsigns",outfile)
if (!file.exists(signsFile)){
stop(paste0("mlVAR signs file not found, expected a file ",mlvarFile))
}
signs <- as.matrix(read.table(signsFile,header=FALSE,stringsAsFactors=FALSE))
# Now add sum of off-diagonals to each diagonal!
for (t in 1:dim(Theta_samples)[3]){
diag(Theta_samples[,,t]) <- colSums(Theta_samples[,,t])
# Multiply with signs:
Theta_samples[,,t] <- Theta_samples[,,t] * signs
}
} else {
# First collect the matrix as is:
Theta_samples <- array(,c(nOut, nOut, nSample))
for (i in 1:nOut){
for (j in i:nOut){
# Name of column:
if (i == j){
colName <- paste0("%WITHIN%:.",toupper(Outcomes[i]))
colID <- which(sampleNames == colName)
Theta_samples[i,j,] <- bayesSamples[,colID]
} else {
# Which dummy?
colName <- paste0("%WITHIN%:.",toupper(Outcomes[j]),".WITH.",toupper(Outcomes[i]))
colID <- which(sampleNames == colName)
Theta_samples[i,j,] <- Theta_samples[j,i,] <- bayesSamples[,colID]
}
}
}
}
# # Now add sum of off-diagonals to each diagonal!
# for (t in 1:dim(Theta_samples)[3]){
# diag(Theta_samples[,,t]) <- colSums(Theta_samples[,,t])
#
# # Multiply with signs:
# Theta_samples[,,t] <- Theta_samples[,,t] * signs
# }
# Store to output:
Results[["Theta"]] <- covSamples_Mplus(Theta_samples)
# Obtain DIC:
if (is.null(output$summaries$DIC)){
warning("No DIC obtained. Model might not have converged.")
DIC <- NA
pD <- NA
} else {
DIC <- output$summaries$DIC
pD <- output$summaries$pD
}
# Combine results:
Results <- list(
results = Results,
output = output,
fit = NULL,
data = Data,
model = mlVARinfo,
DIC = DIC,
pD = pD,
input = list(
vars = Outcomes,
lags = Lags,
temporal = tempModel,
contemporaneous = conModel,
estimator = sprintf("Mplus (version %s)",output$summaries$Mplus.version)
)
)
class(Results) <- "mlVAR"
return(Results)
}