-
Notifications
You must be signed in to change notification settings - Fork 0
/
MixTVEM_OldVersion.r
1238 lines (1236 loc) · 67.2 KB
/
MixTVEM_OldVersion.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
TVEMMixNormal <- function( dep, # The dependent variable as a vector, one
# entry per assessment per subject
id, # The subject ID as a vector, one
# entry per assessment per subject
# (could be integers or strings)
numInteriorKnots, # The number of interior knots
# for the splines representing
# the time-varying coefficients.
# Assumed to be the same
# for each coefficient.
numClasses, # Number of classes in the mixture model
tcov, # Time-varying covariates as a matrix, one
# row per assessment per person. Usually,
# the first column should be a column of
# ones representing an intercept.
time, # Assessment time as a vector
# These arguments have default values, given after the equal sign for each:
convergenceCriterion=1e-8, # Convergence criterion for the
# maximum absolute deviation of parameter
# estimates between successive
# steps of the EM algorithm
deg=3, # Degree of the polynomial between
# successive knots for the time-
# varying coefficient functions.
doPlot=TRUE, # Whether to draw a plot of the time-
# varying coefficient functions.
equalVariance=FALSE, # Whether to assume equal error
# variance between classes
gammaPriorConstant=1, # Optional weight of a Bayesian
# prior used to keep class prevalences
# away from zero or one; similar to those
# used in LatentGOLD (Vermunt and Magidson,
# 2005a,b) and in PROC LCA (Lanza et al.,
# 2011)
getSEs=TRUE, # Whether to calculate standard errors.
# Setting this to FALSE would save
# computational time.
gridSize=1000, # The number of values of time for which
# to obtain estimates of the coefficient
# functions
maxIterations=5000, # Maximum number of EM iterations
# to attempt;
maxVarianceRatio=20, # Maximum ratio between estimated
# variances of different classes;
numStarts=50, # Number of random starting values to use.;
referenceClass=NA, # Reference class. If it is not
# specified here, then the last class
# (i.e., NumClasses) will be selected
# as the reference class. The logistic
# regression model for the class membership
# will predict the probability of being
# in each other class relative to this
# reference class as a baseline.
seed=NA, # The initial random seed. It will be used
# to fit the model (if numStarts=1) or to
# generate more seeds (if numStarts>1).
scov=NULL, # Subject-level class membership prediction
# covariates, as a matrix. A column of 1's
# should not be provided for scov because,
# unlike in the case of tcov, an intercept
# column is included automatically
# by the code. This should have the same
# number of rows as tcov, but should be
# identical on all observations within the
# same person.
useRoughnessPenalty=TRUE, # Whether or not to use
# a penalty function to make the estimated
# time-varying coefficients more smooth
xcov=NULL # Optional matrix of covariates assumed
# to have time-invariant effects.
) {
##################################################################
# MixTVEM macro Version 1.1
# By John DZIAK, Xianming TAN, and Runze LI
# Fits a mixture of nonparametric trajectories to longitudinal data.
#
# Copyright:
# (c) 2013 The Pennsylvania State University
#
# License:
# 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.
#
# Acknowledgments and references:
# We fit a mixture of nonparametric varying-coefficient models, using
# a penalized B-spline approach. See
# Eilers, P.H.C. and Marx, B.D. (1996). Flexible smoothing using
# B-splines and penalized likelihood. Statistical Science
# 11(2): 89-121.
# Hastie, T., & Tibshirani, R. (1993). Varying-coefficient models. Journal
# of the Royal Statistical Society, Series B, 55, 757-796.
# Shiyko, M. P., Lanza, S. T., Tan, X., Li, R., Shiffman, S. (2012). Using
# the Time-Varying Effect Model (TVEM) to Examine Dynamic Associations
# between Negative Affect and Self Confidence on Smoking Urges:
# Differences between Successful Quitters and Relapsers. Prevention
# Science, 13, 288-299.
# Ramsay, J., Hooker, G., & Graves, S. (2009). Functional Data Analysis with
# R and MATLAB. New York: Springer.
# Tan, X., Shiyko, M. P., Li, R., Li, Y., & Dierker, L. (2011, November 21).
# A time-varying effect model for intensive longitudinal data.
# Psychological Methods. Advance online publication. doi: 10.1037/a0025814.
# Estimation is done using the EM algorithm for finite mixtures.
# McLachlan, G. J., and Peel, D. (2000). Finite mixture models. New York: Wiley.
# Dempster, A. P., Laird, N. M., and Rubin, D. B. (1977). Maximum likelihood
# from incomplete data via the EM algorithm. Journal of the Royal
# Statistical Society, B, 39, 1-38.
# The standard error calculations for the mixture approach are based on
# those used by Turner (2000) and Turner's mixreg R package, which are based on the
# ideas of Louis (1982).
# Louis, T. A. (1982). Finding the Observed Information Matrix when Using
# the EM Algorithm. Journal of the Royal Statistical Society, B, 44, 226-233.
# Turner, T. R. (2000) Estimating the rate of spread of a viral infection of
# potato plants via mixtures of regressions. Applied Statistics, 49,
# pp. 371-384.
# Turner, R. (2009). mixreg: Functions to fit mixtures of regressions.
# R package version 0.0-3. http://CRAN.R-project.org/package=mixreg
# The use of a sandwich formula to adjust for within-subject correlation
# when calculating the standard errors is inspired by
# Liang, K.-Y., and Zeger, S. L. (1986). Longitudinal data analysis
# using generalized linear models. Biometrika, 73, 13-22.
# Clustering functional data modeled with splines is described in
# James, G., and Sugar, C. (2003) Clustering for sparsely sampled
# functional data. Journal of the American Statistical
# Association 98, 397-408.
# The optional gamma stabilization prior is similar to that used
# in Latent GOLD and PROC LCA. See
# Lanza, S. T., Dziak, J. J., Huang, L., Xu, S., & Collins, L. M. (2011).
# PROC LCA & PROC LTA users' guide (Version 1.2.7). University Park: The
# Methodology Center, Penn State. Retrieved from http://methodology.psu.edu.
# Chung, H., Flaherty, B. P., and Schafer, J. L. (2006). Latent class
# logistic regression: application to marijuana use and attitudes
# among high school seniors. Journal of the Royal Statitical
# Society, A, 169, 723-743.
# Clogg, C. C. and Goodman, L. A. (1984) Latent structure analysis of a
# set of multidimensional contingency tables. JASA, 79, 762771.
# The model fit criteria used are adapted versions of the standard AIC, BIC
# and GCV of:
# Akaike, H. (1973). Information theory and an extension of the maximum
# likelihood principle. In B. N. Petrov & F. Csaki (Eds.), Second
# international symposium on information theory (p. 267-281).
# Budapest, Hungary: Akademai Kiado.
# Schwarz, G. (1978). Estimating the dimension of a model. Annals of
# Statistics, 6, 461-464.
# Craven, P., and Wahba, G. (1978). Smoothing noisy data with spline
# functions: Estimating the correct degree of smoothing by the
# method of generalized cross-validation. Numerische
# Mathematik, 31, 377403.
##################################################################
library(splines);
library(nlme);
## Define required helper functions:
MixTVEMFitInner <- function(convergenceCriterion,
equalVariance=TRUE,
gammaPriorConstant=0,
intId,
maxIterations=5000,
maxVarianceRatio,
modelOrder,
numClasses,
penaltyMatrix=NULL,
referenceClass,
roughnessPenalty=0,
S,
useRoughnessPenalty=FALSE,
X,
Y ) {
## Prepare to begin loop;
theta <- matrix(0,ncol(X),numClasses);
oldGamma <- Inf;
oldtheta <- Inf;
maxAbsDev <- Inf;
numSubjects <- max(intId);
numTotal <- length(intId);
nonreferenceClasses <- (1:numClasses)[-referenceClass];
iteration <- 1;
numObsBySub <- table(intId); # assumes that intId
# consists of consecutive integers starting at 1;
stopifnot(length(Y)==numTotal);
stopifnot(length(unique(intId))==numSubjects);
stopifnot(all.equal(unique(intId),1:numSubjects));
stopifnot(as.integer(rownames(numObsBySub))==1:numSubjects);
stopifnot(identical(intId,sort(intId)));
stopifnot(length(numObsBySub)==numSubjects);
stopifnot(length(intId)==numTotal);
stopifnot(identical(intId,sort(intId)));
## Initial E step (generate random posterior probabilities;
temp <- matrix(rexp(numSubjects*numClasses),
numSubjects,
numClasses);
postProbsBySub <- (temp+gammaPriorConstant/numSubjects)/
(apply(temp,1,sum)+
numClasses*gammaPriorConstant/numSubjects);
## Begin loop;
while ((iteration<maxIterations)&
(maxAbsDev>convergenceCriterion)) {
## Initial work;
iteration <- iteration+1;
postProbsByAssessment <- matrix(0,numTotal,numClasses);
for (k in 1:numClasses) {
postProbsByAssessment[,k] <-
rep(postProbsBySub[,k],numObsBySub);
}
## M Step;
## Fit the model;
modelList <- list();
for (k in 1:numClasses) {
w <- postProbsByAssessment[,k];
if (!useRoughnessPenalty) {
theta[,k] <- solve(t(X)%*%(w*X),t(X)%*%(w*Y))
} else {
theta[,k] <- solve(t(X)%*%(w*X)+
roughnessPenalty*penaltyMatrix,t(X)%*%(w*Y));
}
}
fittedY <- X%*%theta; # one column for each class;
residY <- as.matrix(Y-fittedY);
## Get new sigma estimates;
f <- function(i) {
return(apply(residY[which(intId==i),,drop=FALSE]^2,
2,sum))};
rssBySubjectAndClass <- t(sapply(1:numSubjects,f));
if (equalVariance==TRUE) {
sigsq <- rep(sum(postProbsBySub*
rssBySubjectAndClass/numTotal),numClasses);
} else {
sigsq <- rep(0,numClasses);
for (k in 1:numClasses) {
sigsq[k] <- sum(rssBySubjectAndClass[,k]*
postProbsBySub[,k]) /
sum(numObsBySub*postProbsBySub[,k]);
}
}
if (!is.na(maxVarianceRatio)) {
if (max(sigsq)/min(sigsq)>maxVarianceRatio) {
sigsq[which(sigsq<(max(sigsq)
/maxVarianceRatio))] <-
max(sigsq)/maxVarianceRatio;
}
}
## Get new gamma estimates;
SExtended <- kronecker(S,rep(1,numClasses));
colnames(SExtended) <- colnames(S);
classForLR <- rep(1:numClasses,times=numSubjects);
weightForLR <- as.vector(t(postProbsBySub));
dataForLR <- cbind(rep(1:numSubjects,each=numClasses),
classForLR,
weightForLR,
SExtended);
numGamma <- ncol(SExtended);
gamma <- matrix(0,numGamma,numClasses);
eta <- matrix(0,numSubjects,numClasses);
for (k in nonreferenceClasses) {
outcomeForLogisticRegression <- 1*(classForLR==k);
outcomeForLogisticRegression[(classForLR!=k)&
(classForLR!=referenceClass)] <- NA;
warnOption <- getOption("warn");
options(warn=-1);
thisModel <- glm(outcomeForLogisticRegression~
SExtended+0,
family=binomial,
weights=weightForLR);
options(warn=warnOption);
gamma[,k] <- thisModel$coef;
eta[,k] <- S%*%gamma[,k];
}
fittedProb <- (exp(eta)+gammaPriorConstant/numSubjects)/
(apply(exp(eta),1,sum)+
numClasses*gammaPriorConstant/
numSubjects);
## E Step (get new likelihood contributions
## and posterior probabilities);
logProbability <- matrix(0,numSubjects,numClasses);
for (k in 1:numClasses) {
logProbability[,k] <- -(numObsBySub/2)*
log(2*3.1415926535*(sigsq[k]+1e-30)) -
rssBySubjectAndClass[,k]/(2*sigsq[k]+1e-30);
}
tempMatrix <- logProbability;
for (k in 1:numClasses) {
tempMatrix[,k] = tempMatrix[,k] + log(fittedProb[,k]+1e-30);
}
logLikelihoodBySubject <- log(apply(exp(tempMatrix),1,sum));
logLik <- sum(logLikelihoodBySubject);
tempMax <- apply(tempMatrix,1,max);
for (k in 1:numClasses) {
tempMatrix[,k] <- tempMatrix[,k] - tempMax;
}
expTempMatrix <- exp(tempMatrix);
for (k in 1:numClasses) {
postProbsBySub[,k] <- (expTempMatrix[,k]+
gammaPriorConstant/numSubjects)/
(apply(expTempMatrix,1,sum)+
numClasses*gammaPriorConstant/
numSubjects);
}
maxAbsDev <- max(abs(c(as.vector(theta)-oldtheta,
as.vector(gamma)-oldGamma)));
oldGamma <- as.vector(gamma);
oldtheta <- as.vector(theta);
}
if (useRoughnessPenalty) {
enrpByClass <- rep(NA,numClasses);
for (k in 1:numClasses) {
w <- postProbsByAssessment[,k];
enrpByClass[k] <- sum(diag(as.matrix((X*sqrt(w))%*%
solve(t(X)%*%(w*X)+
roughnessPenalty*penaltyMatrix)%*%
t(X*sqrt(w)))));
}
enrp <- sum(enrpByClass);
enp <- enrp +
ncol(S)*(numClasses-1)+
ifelse(equalVariance,1,numClasses);
np <- ncol(X)*numClasses + ncol(S)*(numClasses-1)+
ifelse(equalVariance,1,numClasses);
} else {
enrp <- ncol(X)*numClasses;
enp <- enrp + ncol(S)*(numClasses-1)+
ifelse(equalVariance,1,numClasses);
np <- enp;
}
converged <- maxAbsDev<=convergenceCriterion;
hardRSS <- 0;
weightedRSS <- sum(postProbsBySub*rssBySubjectAndClass);
stopifnot(nrow(postProbsByAssessment)==nrow(fittedY));
stopifnot(length(Y)==nrow(fittedY));
for (i in 1:nrow(fittedY)) {
hardRSS <- hardRSS + ((Y[i]-
fittedY[i,which.max(postProbsByAssessment[i,])])^2);
weightedRSS <- weightedRSS + sum(postProbsByAssessment[i,]*((Y[i]-fittedY[i,])^2));
}
return(list(aic=-2*logLik+2*enrp,
# A statistic similar to AIC (Akaike, 1973)
# but using the effective (penalized) number of
# parameters instead of a count of parameters
# (see Eilers and Marx, 1996)
hardRSS=hardRSS,
# The hard-classified residual sum of squares
# error measure. It is like the classic
# regression sum of squared residuals
# (sum(y-yhat)^2), but it uses yhat for the
# class with the highest posterior probability
# for each subject.
weightedRSS=weightedRSS,
# The weighted residual sum of squares
# error measure. It is like the classic
# regression sum of squared residuals
# (sum(y-yhat)^2), but it is weighted
# by the posterior probabilities estimated
# for each individual and class.
bic=-2*logLik+log(numTotal)*enrp,
# A statistic somewhat analogous to BIC
# (Schwarz, 1978). The effective (penalized)
# number of parameters is used instead of a
# count of parameters (see Eilers and Marx,
# 1996). Also, in order to select a simpler
# model, the total number of observations is
# used as the sample size rather than the
# number of subjects.
converged=converged,
# Indicates whether the EM algorithm converged
enp=enp,
# The effective number of regression
# parameters (enrp) plus the number of free
# gamma parameters plus the number of free
# sigma parameters, summed across classes.
enrp=enrp,
# The effective number of regression
# parameters (see Eilers and Marx, 1996)
fittedProb=fittedProb,
# The fitted values for class probabilities
# given the S covariates for each subject,
# as given by the logistic regression model
# for class membership.
fittedY=fittedY,
# The fitted values for the dependent
# variable at each assessment.
gamma=gamma,
# The estimated logistic regression
# parameters in the model for class
# membership.
hardGCV=hardRSS/(numTotal*((1-(enrp/numTotal))**2)),
# A statistic similar to GCV (see Wahba, 1990;
# Eilers and Marx, 1996) but calculated
# with the hardRSS instead of an ordinary
# residual sum of squares.
iteration=iteration,
# The number of iterations run by the EM
# algorithm.
lambda=roughnessPenalty,
# The current candidate value of the penalty
# weight for the roughness penalty
logLik=logLik,
# The fitted log-likelihood
np=np,
# The counted number of parameters,
# ignoring shrinkage imposed by the penalty
postProbsBySub=postProbsBySub,
# Each subject's estimated posterior
# probability of belonging to each class.
# As a caveat, these posterior probabilities
# assume local independence within
# subject conditional upon the class mean.
# They are likely to exaggerate differences
# between classes and overstate certainty
# of class assignment.
postProbsByAssessment=postProbsByAssessment,
# The same as postProbsBySub, except that
# they are repeated within subject so that
# there is one row per assessment rather than
# only one row per subject.
sigsq=sigsq,
# Estimated sigma squared (variance)
# parameters for each class.
theta=theta,
# Estimated regression coefficients for each
# of the regression coefficients, including
# spline basis coefficients
weightedGCV=weightedRSS/(numTotal*((1-(enrp/numTotal))**2))
# A statistic similar to GCV (see Wahba, 1990;
# Eilers and Marx, 1996) but calculated
# with the weightedRSS instead of an ordinary
# residual sum of squares.
));
}
MixTVEMCovMats <- function( equalVariance,
fittedProb,
gamma,
intId,
mu,
numSubjects,
numTotal,
postProb,
referenceClass,
S,
sigsq,
theta,
X,
Y) {
numthetas <- nrow(theta);
numClasses <- ncol(theta);
stopifnot(numthetas==ncol(X));
numGammas <- nrow(gamma);
stopifnot(numClasses==ncol(mu));
nonreferenceClasses <- (1:numClasses)[-referenceClass];
if (!equalVariance) {
numParams <- (numClasses*numthetas) +
(numClasses-1)*numGammas + numClasses;
} else {
numParams <- (numClasses*numthetas) +
(numClasses-1)*numGammas + 1;
}
thetaIndex <- matrix(0,numthetas,numClasses);
if (numClasses>1) {
gammaIndex <- matrix(0,numGammas,numClasses-1);
}
if (equalVariance) {
for (k in 1:numClasses) {
thetaIndex[,k] <- (((k-1)*numthetas+(k-1)*numGammas) +
(1:numthetas));
if (k < numClasses) {
gammaIndex[,k] <- (k*numthetas+(k-1)*numGammas) +
(1:numGammas);
}
}
sigmaIndex <- matrix(numClasses*numthetas+
(numClasses-1)*numGammas+1,1,numClasses);
# same index for each class;
} else {
sigmaIndex <- matrix(0,1,numClasses);
for (k in 1:numClasses) {
thetaIndex[,k] <- ( ((k-1)*numthetas+(k-1)*numGammas+(k-1)) +
(1:numthetas) );
if (k < numClasses) {
gammaIndex[,k] <- ( (k*numthetas+(k-1)*numGammas+(k-1)) +
(1:numGammas) );
sigmaIndex[k] <- (k*numthetas+k*numGammas+(k-1)) + 1;
} else {
sigmaIndex[k] <- (k*numthetas+(k-1)*numGammas+(k-1)) + 1;
}
}
}
# These calculations are based on the mixreg package in Turner
# (2009) with some modifications as described in our paper;
I1 <- matrix(0,numParams,numParams);
I2 <- matrix(0,numParams,numParams);
I3 <- matrix(0,numParams,numParams);
# Calculate matrix I1
for (k in 1:numClasses) {
for (i in 1:numSubjects) {
xi <- X[which(intId==i),,drop=FALSE];
ni <- sum(intId==i);
contrib <- (1/sigsq[k])*postProb[i,k]*
t(as.matrix(xi))%*%(as.matrix(xi));
I1[thetaIndex[,k],thetaIndex[,k]] <-
I1[thetaIndex[,k],thetaIndex[,k]] + contrib;
I1[sigmaIndex[,k],sigmaIndex[,k]] <-
I1[sigmaIndex[k],sigmaIndex[k]] +
postProb[i,k]*ni/(2*sigsq[k]*sigsq[k]);
}
}
if (numClasses>1) {
for (k in 1:(numClasses-1)) {
for (m in 1:(numClasses-1)) {
for (i in 1:numSubjects) {
nonrefk <- nonreferenceClasses[k];
nonrefm <- nonreferenceClasses[m];
Si <- S[i,,drop=FALSE];
contrib <- fittedProb[i,nonrefk]*
(1*(nonrefk==nonrefm)-fittedProb[i,nonrefm])*
crossprod(Si);
I1[gammaIndex[,k],gammaIndex[,m]] <-
I1[gammaIndex[,k],gammaIndex[,m]] + contrib;
}
}
}
}
# Calculate matrix I2
for (k in 1:numClasses) {
#print(paste("k=",k));print(Sys.time());
for (m in 1:numClasses) {
#print(paste("m=",m));print(Sys.time());
for (i in 1:numSubjects) {
for (j in 1:numSubjects) {
ni <- sum(intId==i);
nj <- sum(intId==j);
xi <- X[which(intId==i),,drop=FALSE];
yi <- Y[which(intId==i),drop=FALSE];
xj <- X[which(intId==j),,drop=FALSE];
yj <- Y[which(intId==j),drop=FALSE];
Si <- S[i,,drop=FALSE];
Sj <- S[j,,drop=FALSE];
muik <- mu[which(intId==i),k,drop=FALSE];
mujm <- mu[which(intId==j),m,drop=FALSE];
hik <- (1/sigsq[k])*t(xi)%*%(yi-muik);
hjm <- (1/sigsq[m])*t(xj)%*%(yj-mujm);
tik <- -ni/(2*sigsq[k])+
(crossprod(yi-muik))/(2*sigsq[k]*sigsq[k]);
tjm <- -nj/
(2*sigsq[m])+(crossprod(yj-mujm))/
(2*sigsq[m]*sigsq[m]);
Gkmij <- postProb[i,k]*postProb[j,m] +
postProb[i,k]*(i==j)*((k==m)-postProb[j,m]);
I2[thetaIndex[,k],thetaIndex[,m]] <-
I2[thetaIndex[,k],thetaIndex[,m]] +
Gkmij * hik%*%t(hjm);
I2[thetaIndex[,k],sigmaIndex[m]] <-
I2[thetaIndex[,k],sigmaIndex[m]] +
Gkmij * hik%*%tjm;
I2[sigmaIndex[m],thetaIndex[,k]] <-
t(I2[thetaIndex[,k],sigmaIndex[m]]);
I2[sigmaIndex[k],sigmaIndex[m]] <-
I2[sigmaIndex[k],sigmaIndex[m]] +
Gkmij*tik*tjm;
if ((k < numClasses)&(m < numClasses)) {
nonrefk <- nonreferenceClasses[k];
nonrefm <- nonreferenceClasses[m];
Gnonrefkmij <- postProb[i,nonrefk]*postProb[j,m] +
postProb[i,nonrefk]*(i==j)*
((nonrefk==m)-postProb[j,m]);
Gknonrefmij <- postProb[i,k]*postProb[j, nonrefm] +
postProb[i,k]*(i==j)*
((k==nonrefm)-postProb[j,nonrefm]);
Gnonrefknonrefmij <- postProb[i,nonrefk]*
postProb[j,nonrefm]+
postProb[i,nonrefk]*(i==j)*
((nonrefk==nonrefm)-
postProb[j, nonrefm]);
contrib <- (Gnonrefknonrefmij-postProb[i,nonrefk]*
fittedProb[j,nonrefm]-
postProb[j,nonrefm]*
fittedProb[i,nonrefk] +
fittedProb[i,nonrefk]*
fittedProb[j,nonrefm])*
(t(Si)%*%Sj);
I2[gammaIndex[,k],gammaIndex[,m]] <-
I2[gammaIndex[,k],gammaIndex[,m]] +
contrib;
}
if (k < numClasses) {
nonrefk <- nonreferenceClasses[k];
Gnonrefkmij <- postProb[i,nonrefk]*postProb[j,m]+
postProb[i,nonrefk]*(i==j)*
((nonrefk==m)-postProb[j,m]);
contrib <- t(Gnonrefkmij%*%tjm%*%Si);
I2[gammaIndex[,k],sigmaIndex[m]] <-
I2[gammaIndex[,k],sigmaIndex[m]];
I2[sigmaIndex[m],gammaIndex[,k]] <-
t(I2[gammaIndex[,k],sigmaIndex[m]]);
}
if (m < numClasses) {
nonrefm <- nonreferenceClasses[m];
Gknonrefmij <- postProb[i,k]*postProb[j,nonrefm]+
postProb[i,k]*(i==j)*
((k==nonrefm)-postProb[j,nonrefm]);
contrib = Gknonrefmij*hik%*%Sj-
postProb[i,k]*fittedProb[j,m]*hik%*%Sj;
I2[thetaIndex[,k],gammaIndex[,m]] <-
I2[thetaIndex[,k],gammaIndex[,m]] +
contrib;
I2[gammaIndex[,m],thetaIndex[,k]] <-
t(I2[thetaIndex[,k],gammaIndex[,m]]);
}
}
}
}
}
# Calculate matrix I3
#print("Starting I3");print(Sys.time());
for (i in 1:numSubjects) {
scorei <- matrix(0,numParams,1);
for (k in 1:numClasses) {
ni <- sum(intId==i);
xi <- X[which(intId==i),,drop=FALSE];
yi <- Y[which(intId==i),drop=FALSE];
Si <- S[i,,drop=FALSE];
muik <- mu[which(intId==i),k];
hik <- (1/sigsq[k])*t(xi)%*%(yi-muik);
scorei[thetaIndex[,k]] <- postProb[i,k]*hik;
tik <- -ni/(2*sigsq[k]) + crossprod(yi-muik)/
(2*sigsq[k]*sigsq[k]);
scorei[sigmaIndex[k]] <- scorei[sigmaIndex[k]] +
postProb[i,k]%*%tik;
if (k < numClasses) {
nonrefk <- nonreferenceClasses[k];
scorei[gammaIndex[,k]] <- (postProb[i,nonrefk]-
fittedProb[i,nonrefk])*Si;
}
}
I3 <- I3 + crossprod(t(scorei));
}
# Calculate naiveCovarianceMatrix (in theta, gamma and sigma)
if (kappa(I1-I2)<Inf) {
naiveCovarianceMatrix <- solve(I1-I2);
} else {
naiveCovarianceMatrix <- matrix(NA,nrow(I1),ncol(I1));
}
# Calculate covarianceMatrix (in theta, gamma and sigma)
if (det(I3)>0) {
covarianceMatrix <- naiveCovarianceMatrix%*%
I3%*%naiveCovarianceMatrix;
}
stopifnot(min(eigen(covarianceMatrix)$values)>0);
# Calculate covarianceForPrevalences
if (numClasses > 1) {
allGammas <- as.vector(gammaIndex);
naiveCovGamma <- naiveCovarianceMatrix[allGammas,allGammas];
covGamma <- covarianceMatrix[allGammas,allGammas];
jacobian <- matrix(0,numClasses,(numClasses-1)*numGammas);
for (m in 1:(numClasses-1)) {
for (k in 1:numClasses) {
for (q in 1:numGammas) {
w <- (m-1)*numGammas + q;
nonrefm <- nonreferenceClasses[m];
# Jacobian[m,i] = derivative of lambda[k] in gamma[m,q], ;
# i.e., gamma[w] when the free gammas are all listed in a ;
# vector, one class on top of another, excluding the
# reference class. ;
temp <- sum(((1*(k==nonrefm))-fittedProb[,k])*
fittedProb[,nonrefm]*S[,q]);
jacobian[k,w] <- temp/numSubjects;
}
}
}
covForPrevalence <- jacobian %*% covGamma %*% t(jacobian);
naiveCovForPrevalence <- jacobian %*% naiveCovGamma %*%
t(jacobian);
}
return(list( naiveCovarianceMatrix=naiveCovarianceMatrix,
# The estimated covariance matrix for all of
# the model parameters, ignoring within-subject
# correlation entirely
covarianceMatrix=covarianceMatrix,
# The sandwich covariance matrix for the model
# parameters, which may be more robust to
# misspecification of the within-subject
# correlation (see Liang and Zeger 1986)
naiveCovForPrevalence=naiveCovForPrevalence,
# A naive covariance matrix for the estimated
# overall average class prevalences
covForPrevalence=covForPrevalence,
# A sandwich-based covariance matrix for the
# estimated overall average class prevalences
thetaIndex=thetaIndex,
# Tells which rows and columns of the covariance
# matrix refer to thetas (linear regression
# parameters)
gammaIndex=gammaIndex,
# Tells which rows and columns of the covariance
# matrix refer to gammas (logistic regression
# parameters)
sigmaIndex=sigmaIndex,
# Tells which rows and columns of the covariance
# matrix refer to sigmas (variance
# parameters)
I1=I1,
I2=I2,
I3=I3)); # I1, I2, and I3 are described in our paper
# (Dziak et al) and are based on combining
# the approach of Turner (2000) with a
# sandwich estimation approach
}
#####################################################################
## Main body of MixTVEM function
## Process the subject ID's;
if (!is.integer(id)) {
temporary.id <- as.integer(as.factor(id));
} else {
temporary.id <- id;
}
numTotal <- length(id);
intId <- rep(0,numTotal);
stopifnot(is.integer(unique(temporary.id)));
numSubjects <- length(unique(temporary.id));
for (i in 1:numSubjects) {
intId[which(temporary.id==unique(temporary.id)[i])] <- i;
}
stopifnot(length(unique(intId))==numSubjects);
stopifnot(all.equal(unique(intId),1:numSubjects));
## Decide on a reference class;
if (is.na(referenceClass)) {referenceClass <- numClasses;}
stopifnot(referenceClass>0);
stopifnot(referenceClass<=numClasses);
## Process the class membership predictor variables S;
if (!is.null(scov)) {
scov <- as.matrix(scov);
stopifnot(nrow(scov)==numTotal);
S <- matrix(0,numSubjects,1+ncol(scov));
for (i in 1:numSubjects) {
theseObs <- which(intId==i);
S[i,] <- c(1, scov[min(theseObs),]);
}
} else {
S <- matrix(1,numSubjects,1);
}
if (is.null(colnames(scov))) {
colnames(S) <- paste("S",0:(ncol(S)-1),sep="");
};
## Process the time variable;
stopifnot(!is.null(time));
stopifnot((deg==1)|(deg==2)|(deg==3));
time <- as.matrix(time);
stopifnot(nrow(time)==numTotal);
stopifnot(ncol(time)==1);
stopifnot(is.numeric(time));
if (is.null(colnames(time))) {
colnames(time) <- "Time";
}
timeBasis <- list();
designMatrix <- NULL;
whichBeta <- NULL;
## Construct the first part of the design matrix including ... ;
## ... the intercept column if there are no time-varying covariates;
if (is.null(tcov)) { interceptColumn <- matrix(1,numTotal,1);
colnames(interceptColumn) <- "Intercept";
designMatrix <- cbind(designMatrix,interceptColumn);
whichBeta <- c(whichBeta,0);
}
## ... and the covariates without time-varying effects;
if (!is.null(xcov)) {
if (min(apply(xcov,2,var))<1e-10) {
stop("Please do not include a constant column in xcov.");
}
xcov <- as.matrix(xcov);
stopifnot(nrow(xcov)==numTotal);
numXCov <- ncol(xcov);
if (is.null(colnames(xcov))) {
colnames(xcov) <- paste("X",1:ncol(xcov),sep="");
};
designMatrix <- cbind(designMatrix,xcov);
} else {
numXCov <- 0;
}
whichBeta <- c(whichBeta,rep(0,numXCov));
## Get the tcov matrix ready;
if (is.null(tcov)) {
numTCov <- 0;
stop(paste("tcov is null.",
"No time-varying betas or effects are in the model."));
} else {
tcov <- as.matrix(tcov);
stopifnot(nrow(tcov)==numTotal);
numTCov <- ncol(tcov);
if (is.null(colnames(tcov))) {
colnames(tcov) <- paste("TV",1:ncol(tcov),sep="");
};
## Create the scale vector to be used with the penalty for the time-varying
## covariates;
if (!identical(as.vector(tcov[,1]),rep(1,numTotal))) {
warning("tcov does not seem to contain an intercept (trajectory) column.");
}
tcov.scale <- apply(tcov,2,sd);
if (length(tcov.scale)>1) {
if (min(tcov.scale[-1])<1e-10) {
stop(paste("Please include the intercept column as the first",
"column in tcov, and do not include any other columns",
"which are constant across all",
"subjects and assessments."));
}
}
if (identical(as.vector(tcov[,1]),rep(1,numTotal))) {
tcov.scale[1] <- 1; # don't scale intercept column;
}
## Create the basis functions;
if (length(numInteriorKnots)!=1) {stop();}
stopifnot(numInteriorKnots>0);
num.intervals <- numInteriorKnots+1;
dx <- (max(time)-min(time))/num.intervals;
all.knot.locations <- seq(min(time)-(deg)*dx,
max(time)+(deg)*dx,
by=dx);
all.knot.locations[1] <- all.knot.locations[2]-1e-8;
all.knot.locations[length(all.knot.locations)] <-
all.knot.locations[length(all.knot.locations)-1]+1e-8;
interior.knot.locations <- seq(min(time)+dx,
max(time)-dx,
by=dx);
timeGrid <- seq(min(time),max(time),length=gridSize);
timeBasis <- spline.des(all.knot.locations,
time,
deg+1,
rep(0,length(time)))$design;
# Adapted from Eilers and Marx, 1996;
colnames(timeBasis) <- paste(colnames(time),".Spline.",
1:ncol(timeBasis),
sep="");
timeBasisByGrid <- spline.des(all.knot.locations,
timeGrid,
deg+1,
rep(0,length(timeGrid)))$design;
# Adapted from Eilers and Marx, 1996;
colnames(timeBasisByGrid) <- paste(colnames(time),".Spline.",
1:ncol(timeBasisByGrid),
sep="");
# Now generate regression matrix;
for (j in 1:numTCov) {
covariateTimesTimeBasis <- tcov[,j,drop=TRUE]*timeBasis;
# Elementwise product;
colnames(covariateTimesTimeBasis) <- paste(colnames(tcov)[j],
"times",
colnames(timeBasis),
sep=".");
designMatrix <- cbind(designMatrix, covariateTimesTimeBasis);
whichBeta <- c(whichBeta,rep(j,ncol(covariateTimesTimeBasis)));
}
stopifnot(sum(is.nan(designMatrix))==0);
stopifnot(sum(is.null(designMatrix))==0);
if(sum(is.na(designMatrix))>0) {
stop("Missing data is not yet supported in this software.");
}
}
## Create the penalty weight matrix (see Eilers and Marx, 1996)
diffMatrix <- crossprod(diff(diff(diag(rep(1,ncol(timeBasis))))));
penaltyMatrix <- matrix(0,ncol(designMatrix),ncol(designMatrix));
if (useRoughnessPenalty) {
for (j in 1:numTCov) {
indices <- numXCov+(j-1)*ncol(timeBasis)+(1:ncol(timeBasis));
stopifnot(length(indices)==nrow(diffMatrix));
stopifnot(length(indices)==ncol(diffMatrix));
penaltyMatrix[indices,indices] <- diffMatrix/(tcov.scale[j]^2);
}
}
#######################################################################
## Run a loop to find the best seed;
logLikBySeed <- rep(NA,numStarts);
hardRSSBySeed <- rep(NA,numStarts);
weightedRSSBySeed <- rep(NA,numStarts);
if (numStarts > 1) {
if (!is.na(seed)) {
};
seeds <- round(runif(numStarts)*1e8);
} else {
if (!is.na(seed)) {
seeds <- seed;
} else {
seeds <- round(runif(1)*1e8);
}
}
postProbsList <- list();
for (i in 1:numStarts) {
set.seed(seeds[i]);
thisFit <- MixTVEMFitInner(convergenceCriterion=convergenceCriterion,
equalVariance=equalVariance,
intId=intId,
gammaPriorConstant=gammaPriorConstant,
maxIterations=maxIterations,
maxVarianceRatio=maxVarianceRatio,
modelOrder=modelOrder,
numClasses=numClasses,
penaltyMatrix=penaltyMatrix,
referenceClass=referenceClass,
S=S,
useRoughnessPenalty=FALSE,
X=designMatrix,
Y=dep);
logLikBySeed[i] <- thisFit$logLik;
hardRSSBySeed[i] <- thisFit$hardRSS;
weightedRSSBySeed[i] <- thisFit$weightedRSS;
postProbsList[[i]] <- thisFit$postProbsBySub;
}
bestSeed <- seeds[which.max(logLikBySeed)];
#######################################################################
## Find the best tuning parameter;
if (useRoughnessPenalty) {
f <- function(p) {
set.seed(bestSeed);
lambda <- exp(p);
thisFit <- MixTVEMFitInner(convergenceCriterion=convergenceCriterion,
equalVariance=equalVariance,
intId=intId,
gammaPriorConstant=gammaPriorConstant,
maxIterations=maxIterations,
maxVarianceRatio=maxVarianceRatio,
modelOrder=modelOrder,
numClasses=numClasses,
penaltyMatrix=penaltyMatrix,
referenceClass=referenceClass,
roughnessPenalty=lambda,
S=S,
useRoughnessPenalty=TRUE,
X=designMatrix,
Y=dep);
return(thisFit$weightedGCV);
}
opt1 <- optimize(f,interval=c(log(1e-10),log(1e10)),tol=.01);
lambda <- exp(opt1$minimum);
} else {
lambda <- 0;
}
#######################################################################
## Finally do the analysis;
set.seed(bestSeed);
bestFit <- MixTVEMFitInner(convergenceCriterion=convergenceCriterion,
equalVariance=equalVariance,
intId=intId,
gammaPriorConstant=gammaPriorConstant,
maxIterations=maxIterations,
maxVarianceRatio=maxVarianceRatio,
modelOrder=modelOrder,
numClasses=numClasses,
penaltyMatrix=penaltyMatrix,
referenceClass=referenceClass,
roughnessPenalty=lambda,
S=S,
useRoughnessPenalty=useRoughnessPenalty,
X=designMatrix,
Y=dep);
## Now record the fitted values on the original assessment times;
fitted <- designMatrix%*%bestFit$theta;
fittedCoefficients <- list();
for (j in 1:numTCov) {
fittedCoefficients[[j]] <- timeBasis%*%
bestFit$theta[which(whichBeta==j),];
}
estimate <- list();
for (which.coef in 1:numTCov) {
estimate[[which.coef]] <- list();
for (which.class in 1:numClasses) {
estimate[[which.coef]][[which.class]] <-
fittedCoefficients[[which.coef]][order(time),which.class];
}
}
## Record the fitted values on the fit grid;
fittedCoefficientsByGrid <- list();
for (j in 1:numTCov) {
fittedCoefficientsByGrid[[j]] <- timeBasisByGrid%*%
bestFit$theta[which(whichBeta==j),];
}
estimate <- list();
for (which.coef in 1:numTCov) {
estimate[[which.coef]] <- list();
for (which.class in 1:numClasses) {
estimate[[which.coef]][[which.class]] <-
fittedCoefficientsByGrid[[which.coef]][order(timeGrid),which.class];
}
}
## Get the standard errors;
if (getSEs) {
covarMats <- MixTVEMCovMats(equalVariance=equalVariance,
fittedProb=bestFit$fittedProb,
gamma=bestFit$gamma,
intId=intId,
mu=bestFit$fittedY,
numSubjects=numSubjects,
numTotal=numTotal,
postProb=bestFit$postProbsBySub,
referenceClass=referenceClass,
S=S,
sigsq=bestFit$sigsq,
theta=bestFit$theta,
X=designMatrix,
Y=dep);