-
Notifications
You must be signed in to change notification settings - Fork 0
/
TVEM_Mix_Normal.sas
1907 lines (1907 loc) · 90.3 KB
/
TVEM_Mix_Normal.sas
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
%MACRO TVEM_Mix_Normal( MyData,
Time,
Dep,
ID,
Latent_Classes,
Cov=,
SCov=,
TCov=,
Knots=,
Num_Starts=50,
Convergence=1e-8 ,
Coverage=0.95 ,
Deg=3,
Initial_Seed=100000,
Max_Iterations=1000,
Max_Variance_Ratio=10,
Penalty_Max=.,
Ref=1,
Scale=1000,
Std_Err_Option=yes);
/***************************************************************
| MixTVEM macro Version 1.1
| By John DZIAK, Xianming TAN, and Runze LI
| Fits a mixture of nonparametric trajectories to longitudinal data.
|
| Copyright:
| (c) 2015 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
| de Boor, C. (1977). Package for calculating with B-splines.
| SIAM Journal on Numerical Analysis, 14, 441-72.
| 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.
| Some web resources which were helpful in writing this macro:
| SAS FAQ: How can I recode my ID variable to be short and numeric?.
| UCLA: Academic Technology Services, Statistical Consulting Group.
| Accessed at http://www.ats.ucla.edu/stat/sas/faq/enumerate_id.htm.
| Accessed Feb. 22, 2012 (and before).
| Statistical Computing Seminar: Proc Logistic and Logistic Regression Models.
| UCLA: Academic Technology Services, Statistical Consulting Group.
| Accessed at http://www.ats.ucla.edu/stat/sas/seminars/sas_logistic/logistic1.htm.
| Accessed Feb. 22, 2012 (and before).
| Deng, C. Q. (June 27, 2009). Spaghetti plot. Blog entry on "On Biostatistics
| and Clinical Trials: CQ's web blog on the issues in biostatistics and
| clinical trials." Accessed at
| http://onbiostatistics.blogspot.com/2009/06/spaghetti-plot.html.
| Some of the code is adapted from the TVEM macro suite:
| TVEM SAS Macro Suite (Version 2.1.0) [Software]. (2012). University
| Park: The Methodology Center, Penn State.
| Retrieved from http://methodology.psu.edu.
| Yang, J., Tan, X., Li, R., & Wagner, A. (2012). TVEM (time-varying
| effect model) SAS macro suite users' guide (Version 2.1.0). University
| Park: The Methodology Center, Penn State.
| Retrieved from http://methodology.psu.edu.
| 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, 377–403.
/***************************************************************/
OPTIONS NONOTES;
%LET MixTVEMDebug = 1;
%LET SEIgnoreInfoLoss=0; /* do not try to make calculations faster by leaving I2 matrix at zero */
/* First process the user input values. If these trigger an error
right away (i.e., they appear to be un-implementable or nonsensical)
then we do not do anything else. This part of the code goes through
the user-provided input arguments
and checks whether the values are unreasonable or impossible. If
it finds impossible values, it gives an error message. Otherwise,
the checked input values are processed and saved in new macro
variables and in a dataset named MixTVEMSettings. */
PROC IML;
MacroError = 0;
/* MyData */
MyData= "&MyData";
IF (LENGTH("_%TRIM(&MyData)")<2) THEN DO;
PRINT("Error -- The input dataset name must be provided.");
MacroError=1;
END;
/* Time */
Time = "&Time";
IF (LENGTH("_%TRIM(&Time)")<2) THEN DO;
PRINT("Error -- The time variable name must be provided.");
MacroError=1;
END;
IF (LENGTH("_%TRIM(&Time)")>25) THEN DO;
PRINT("Error -- The time variable name is too long.");
MacroError=1;
END;
/* Dep */
Dep = "&Dep";
IF (LENGTH("_%TRIM(&Dep)")<2) THEN DO;
PRINT("Error -- The response variable name must be provided.");
MacroError=1;
END;
/* ID */
ID = "&ID";
IF (LENGTH("_%TRIM(&ID)")<2) THEN DO;
PRINT("Error -- The subject ID variable name must be provided.");
MacroError=1;
END;
/* Latent_Classes */
IF (LENGTH("_%TRIM(&Latent_Classes)")<2) THEN DO;
PRINT("Error -- The number of classes must be provided.");
MacroError=1;
END;
NumClasses = &Latent_Classes;
IF (NumClasses < 1) THEN DO;
PRINT("Error -- There must be at least one class.");
MacroError = 1;
END;
IF (NumClasses > 19) THEN DO;
PRINT("Error -- Cannot fit that many classes.");
MacroError = 1;
END;
%GLOBAL MixTVEMNumClasses;
CALL SYMPUT("MixTVEMNumClasses",CHAR(NumClasses));
/* Ref */
IF (LENGTH("_%TRIM(&Ref)")<2) THEN RefClass = .;
ELSE RefClass = &Ref;
IF (RefClass < 1) THEN DO;
PRINT("Error -- Ref must be at least 1.");
MacroError = 1;
END;
IF (RefClass > NumClasses) THEN DO;
PRINT("Error -- Ref cannot be greater than the number of classes.");
MacroError = 1;
END;
/* Cov */
CovInput = " &Cov"; /* note the trailing space; it makes things work*/
Cov = TRANSLATE(STRIP(COMPBL(CovInput))," ",",");
IF Cov ="" THEN NumCov = 0; ELSE NumCov = 1 + COUNT(Cov," ");
%GLOBAL MixTVEMNumCov;
CALL SYMPUT("MixTVEMNumCov",CHAR(NumCov));
%GLOBAL MixTVEMCov;
IF NumCov>0 THEN DO;
CALL SYMPUT("MixTVEMCov",Cov);
END; ELSE DO;
CALL SYMPUT("MixTVEMCov","DummyPlaceholder");
END;
IF Cov ="" THEN Cov = .;
/* SCov */
SCovInput = " &SCov"; /* note the trailing space; it makes things work*/
SCov = TRANSLATE(STRIP(COMPBL(SCovInput))," ",",");
IF SCov ="" THEN NumSCov = 0; ELSE NumSCov = 1 + COUNT(SCov," ");
%GLOBAL MixTVEMNumSCov;
CALL SYMPUT("MixTVEMNumSCov",CHAR(NumSCov));
%GLOBAL MixTVEMSCov;
IF SCov ="" THEN SCov = .;
IF NumSCov>0 THEN DO;
CALL SYMPUT("MixTVEMSCov",SCov);
END; ELSE DO;
CALL SYMPUT("MixTVEMSCov","DummyPlaceholder");
END;
/* TCov */
TCovInput = " &TCov"; /* note the trailing space; it makes things work*/
TCov = TRANSLATE(STRIP(COMPBL(TCovInput))," ",",");
IF TCov ="" THEN NumTCov = 0; ELSE NumTCov = 1 + COUNT(TCov," ");
%GLOBAL MixTVEMNumTCov;
CALL SYMPUT("MixTVEMNumTCov",CHAR(NumTCov));
%GLOBAL MixTVEMTCov;
IF NumTCov>0 THEN DO;
CALL SYMPUT("MixTVEMTCov",TCov);
END; ELSE DO;
CALL SYMPUT("MixTVEMTCov","DummyPlaceholder");
END;
IF TCov ="" THEN TCov = .;
/* Knots */
Knots= "&Knots";
IF (NumTCov>0) THEN DO;
IF (LENGTH("_%TRIM(&Knots)")<2) THEN DO;
PRINT("Error -- Knot information must be provided.");
MacroError = 1;
END;
/* Have to create dataset of knots */
USE &MyData;
READ ALL VAR {&Time} INTO Time;
CLOSE &MyData;
KnotsString = TRANSLATE("'&Knots'"," ",",");
CALL SYMPUT("MixTVEMTemp",KnotsString);
NumKnotsVec = {. &Knots}`; /* The extra entry is here to prevent a macro error */
NumKnotsVec=NumKnotsVec[2:NROW(NumKnotsVec)];
IF NumKnotsVec[><]<1 THEN DO;
PRINT ("Error -- Please use at least one knot per time-varying coefficient.");
MacroError = 1;
END;
StartTime = Time[><];
StopTime = Time[<>];
IF (NumTCov^=NROW(NumKnotsVec)) THEN DO;
PRINT ("Error -- Please check the knots string.");
MacroError = 1;
END;
InteriorKnotsMatrix = J(NumKnotsVec[<>],NumTCov,.);
DO k = 1 TO NumTCov;
IF NumKnotsVec[k]>0 THEN DO;
InteriorKnotsMatrix[1:NumKnotsVec[k],k] = (StartTime + ((1:NumKnotsVec[k]))*
(StopTime-StartTime)/(NumKnotsVec[k]+1))`;
END;
END;
CREATE MixTVEMInteriorKnotsMatrix FROM InteriorKnotsMatrix;
APPEND FROM InteriorKnotsMatrix;
CLOSE MixTVEMInteriorKnotsMatrix;
KnotsDatasetName = "MixTVEMInteriorKnotsMatrix";
END;
/* Deg */
IF (LENGTH("_%TRIM(&Deg)")<2) THEN Deg = .;
Deg = &Deg;
IF (Deg = .) THEN DO;
Deg = 1;
END;
IF (^((Deg=1)|(Deg=2)|(Deg=3))) THEN DO;
PRINT("Error -- Cannot fit that order of penalized spline.");
MacroError = 1;
END;
/* Standard error option */
StdErrOptionInput = "&Std_Err_Option";
IF ( SUBSTR(UPCASE(STRIP(StdErrOptionInput )),1,1) = "Y" |
SUBSTR(UPCASE(STRIP(StdErrOptionInput )),1,1) = "S" |
SUBSTR(UPCASE(STRIP(StdErrOptionInput )),1,1) = "1" ) THEN DO;
StdErrOption= 1;
END; ELSE IF ( SUBSTR(UPCASE(STRIP(StdErrOptionInput )),1,1) = "N" |
SUBSTR(UPCASE(STRIP(StdErrOptionInput )),1,1) = "0" ) THEN DO;
StdErrOption= 0;
END;
ELSE DO;
PRINT("Error -- Please provide yes or no for Std_Err_Option.");
MacroError = 1;
END;
IF (^((StdErrOption=0)|(StdErrOption=1))) THEN DO;
PRINT("Error -- This standard error option is not currently supported.");
MacroError = 1;
END;
/* Coverage */
/* "Coverage" here means nominal coverage. It is not to be taken too
literally, because the confidence intervals which are constructed are
only pointwise intervals and not a familywise confidence band for the
whole curve, and because the confidence intervals are conditional on
the regression model being correct (e.g., knots are in the right place,
response is normal with variance not a function of time). In reality
these assumptions will be at least slightly inaccurate. Also,
concerns about under-coverage of the sandwich matrix (see Kauermann
and Carroll (2001, JASA) should be considered.*/
IF (LENGTH("_%TRIM(&Coverage)")<2) THEN DO;
Coverage = .95;
END; ELSE DO;
Coverage = &Coverage;
IF (Coverage < 0.50) THEN DO;
PRINT("Error -- The specified coverage level is too low.");
MacroError = 1;
END;
IF (Coverage > 0.99999) THEN DO;
PRINT("Error -- The specified coverage level is too high.");
MacroError = 1;
END;
END;
/* Convergence */
IF (LENGTH("_%TRIM(&Convergence)")<2) THEN DO;
Convergence = 1e-8;
END; ELSE DO;
Convergence = &Convergence;
IF (Convergence < 1e-15) THEN DO;
PRINT("Error -- The specified convergence criterion is too small.");
MacroError = 1;
END;
IF (Convergence > 1e-4) THEN DO;
PRINT("Error -- The specified convergence criterion is too large.");
MacroError = 1;
END;
END;
/* MaxIterations */
MaxIterations = &Max_Iterations;
IF (MaxIterations < 50) THEN DO;
PRINT("Error -- The specified maximum number of iterations is too small.");
MacroError = 1;
END;
/* Max_Variance_Ratio */
MaxVarianceRatio = &Max_Variance_Ratio;
IF (MaxVarianceRatio = .) THEN MaxVarianceRatio = 1000;
IF (MaxVarianceRatio < 0) THEN DO;
PRINT("Error -- The value supplied for Max_Variance_Ratio should not be negative.");
MacroError = 1;
END;
/* Penalty_Max */
Penalty_Max = &Penalty_Max;
IF ((Penalty_Max < 0)&(Penalty_Max ^= .)) THEN DO;
PRINT("Error -- The value supplied for Penalty_Max should not be negative.");
MacroError = 1;
END;
/* Scale */
ScaleForGraph = &Scale;
IF (ScaleForGraph < 0) THEN DO;
PRINT("Error -- The value supplied for Scale should not be negative.");
MacroError = 1;
END;
/* Initial_Seed */
IF (LENGTH("_%TRIM(&Initial_Seed)")<2) THEN DO;
InitialSeed = .;
END;
InitialSeed = &Initial_Seed;
IF (InitialSeed = .) THEN DO;
InitialSeed = 0;
END;
IF (InitialSeed < 0) THEN DO;
PRINT("Error -- Need a nonnegative random seed.");
MacroError = 1;
END;
SelectedSeed = .;
/* Num_Starts */
IF (LENGTH("_%TRIM(&Num_Starts)")<2) THEN DO;
PRINT("Error -- The number of starting values must be provided.");
MacroError=1;
END;
NumStarts = &Num_Starts;
IF (NumStarts < 1) THEN DO;
PRINT("Error -- There must be at least one starting value.");
MacroError = 1;
END;
IF ((NumStarts=1)&(InitialSeed=0)) THEN DO;
PRINT("Error -- Please either specify a higher Num_Starts or a nonzero Initial_Seed.");
MacroError = 1;
END;
Iterations = .; /* Not filled in until later */
Lowest_Num_Observations = .; /* Not filled in until later */
Highest_Num_Observations = .; /* Not filled in until later */
CREATE MixTVEMSettings VAR {
Convergence
Cov
Coverage
Deg
Dep
Highest_Num_Observations
ID
InitialSeed
Iterations
Knots
Lowest_Num_Observations
MacroError
MaxIterations
MaxVarianceRatio
NumClasses
NumCov
NumSCov
NumStarts
NumTCov
Penalty_Max
RefClass
RoughnessPenalty
ScaleForGraph
SCov
StdErrOption
Tcov};
APPEND;
CLOSE MixTVEMSettings;
QUIT;
DATA MixTVEMData;
SET &MyData;
KEEP &ID &Time
%IF %EVAL(&MixTVEMNumCov>0) %THEN %DO; &MixTVEMCov %END;
%IF %EVAL(&MixTVEMNumSCov>0) %THEN %DO; &MixTVEMSCov %END;
%IF %EVAL(&MixTVEMNumTCov>0) %THEN %DO; &MixTVEMTCov %END;
&Dep;
WHERE ((&ID IS NOT MISSING) &
(&Time IS NOT MISSING) &
%DO MixTVEMThisVarIndex = 1 %TO &MixTVEMNumCov;
(%QSCAN(&MixTVEMCov,&MixTVEMThisVarIndex," ") IS NOT MISSING) &
%END;
%DO MixTVEMThisVarIndex = 1 %TO &MixTVEMNumSCov;
(%QSCAN(&MixTVEMSCov,&MixTVEMThisVarIndex," ") IS NOT MISSING) &
%END;
%DO MixTVEMThisVarIndex = 1 %TO &MixTVEMNumTCov;
(%QSCAN(&MixTVEMTCov,&MixTVEMThisVarIndex," ") IS NOT MISSING) &
%END;
(&Dep ^= .));
RUN;
PROC IML;
USE MixTVEMData; READ ALL INTO MixTVEMData; CLOSE MixTVEMData;
USE MixTVEMSettings; READ VAR {InitialSeed
MacroError
MaxIterations
NumStarts
StdErrOption };
CLOSE MixTVEMSettings;
%GLOBAL MixTVEMInitialSeed; CALL SYMPUT("MixTVEMInitialSeed",CHAR(InitialSeed));
%GLOBAL MixTVEMMacroError; CALL SYMPUT("MixTVEMMacroError",CHAR(MacroError));
%GLOBAL MixTVEMMaxIterations; CALL SYMPUT("MixTVEMMaxIterations",CHAR(MaxIterations));
%GLOBAL MixTVEMNumStarts; CALL SYMPUT("MixTVEMNumStarts",CHAR(NumStarts));
%GLOBAL MixTVEMNumTotal; CALL SYMPUT("MixTVEMNumTotal",CHAR(NROW(MixTVEMData)));
%GLOBAL MixTVEMStdErrOption; CALL SYMPUT("MixTVEMStdErrOption",CHAR(StdErrOption));
QUIT;
PROC SORT DATA=MixTVEMData TAGSORT NOTHREADS;
BY &ID;
RUN;
DATA MixTVEMData; SET MixTVEMData;
BY &ID;
RETAIN MixTVEMIntID 0;
IF first.&ID THEN MixTVEMIntID = MixTVEMIntID + 1;
/* This creates a recoded version of the subject ID variable,
called "MixTVEMIntID," that is composed of consecutive
integers starting with 1. This makes it possible for some
of the code in the macro to be simpler than if subjects could
have anything for ID's.
See http://www.ats.ucla.edu/stat/sas/faq/enumerate_id.htm; */
OUTPUT;
%GLOBAL MixTVEMNumSubjects;
CALL SYMPUT("MixTVEMNumSubjects",MixTVEMIntID);
RUN;
DATA MixTVEMSettings;
SET MixTVEMSettings;
NumTotal = &MixTVEMNumTotal;
NumSubjects = &MixTVEMNumSubjects;
IF (Penalty_Max = .) THEN Penalty_Max = NumTotal;
RUN;
/* Now create a datafile, MixTVEMSBySub, which contains
the S predictors if there are any. Unlike MixTVEMData and MixTVEMDataX,
which have one record per observation, this dataset will be much smaller,
having only one record per subject. This is because class membership is
considered to be a stable characteristic that does not change. Thus, its
predictors in the model are not expected to be time-varying either. */
%IF %EVAL(&MixTVEMDebug>0) %THEN %PUT Now prepare subject variables matrix;
PROC IML;
USE MixTVEMSettings;
READ VAR{ NumSCov } INTO NumSCov ;
READ VAR{ SCov } INTO SCov ;
READ VAR{ NumSubjects } INTO NumSubjects ;
READ VAR{ NumTotal } INTO NumTotal ;
READ VAR{ MacroError} INTO MacroError;
CLOSE MixTVEMSettings;
USE MixTVEMData;
READ ALL VAR{MixTVEMIntID} INTO IntID;
CLOSE MixTVEMData;
AvailableCov = CONTENTS(MixTVEMData) ;
SCovArray = "Intercept";
IF NumSCov>0 THEN DO;
DO i = 1 TO NumSCov;
ThisVariable = SCANQ(SCov,i);
VarFound = (COMPARE(ThisVariable,AvailableCov,"li")=0)[+];
IF VarFound = 0 THEN DO;
PRINT "Error -- Could not find this variable in the dataset:" ThisVariable;
MacroError = 1;
END;
IF (COMPARE(ThisVariable,"Intercept","li")=0) THEN DO;
PRINT("Error -- An intercept variable should not be included in the S variables.");
MacroError = 1;
/* The user should not have provided an intercept column for S,
since one will be provided automatically and we do not want
redundant columns. */
END;
SCovArray = SCovArray // ThisVariable;
END;
USE MixTVEMData; READ ALL VAR {&MixTVEMSCov} INTO SCov ; CLOSE MixTVEMSCov ;
IF (((SCov[<>]=SCov[><])[+])>0) THEN DO;
PRINT("Error -- An intercept or constant column should not be included in the S variables.");
MacroError = 1;
END;
IF (NROW(SCov)^=NumTotal) THEN DO;
PRINT("Error -- Unexpected amount of data in S variables.");
MacroError = 1;
END;
SByObs = J(NumTotal,1,1) || SCov;
END; ELSE DO;
SByObs = J(NumTotal,1,1);
END;
SNum = (1:(NumSCov+1))`;
SCovName = SCovArray;
CREATE MixTVEMSCovNames VAR{SNum SCovName};
APPEND;
CLOSE MixTVEMSCovNames;
IF (NROW(SByObs) ^= NumTotal)|(NCOL(SByObs) ^= NumSCov+1) THEN DO;
PRINT("Error -- Unexpected amount of data in S variables.");
MacroError = 1;
END;
IF (NROW(IntID) ^= NumTotal)|(NCOL(IntID) ^= 1) THEN DO;
PRINT("Error -- Unexpected amount of data in ID variable.");
MacroError = 1;
END;
IF (IntID[><] ^= 1)|(IntID[<>]^=NumSubjects) THEN DO;
PRINT("Error -- Unexpected values of data in ID variable.");
MacroError = 1;
END;
SBySub = J(NumSubjects,NCOL(SByObs),0);
ThisRowOkayForThisSubject = J(NumTotal,1,0);
sub = 1;
SBySub[sub,] = SByObs[1,];
GaveErrorMessage = 0;
/* The following loop is somewhat tricky but involves compressing
the dataset which the user provides (which has NumTotal rows,
one for each observation on each subject), into a new dataset
with NumSubject rows (having only NumSubject rows, i.e., one row
for each subject, where NumSubject is less than or equal to NumTotal.)
The loop also checks to try to make sure that this is meaningful and
does not cause confusion due to misspecified ID or S variables. In other
words, the subjects in MixTVEMData should have a one-to-one mapping
onto the subjects in MixTVEMSBySub, and the observations in MixTVEMData
should have a many-to-one mapping to the values in MixTVEMData.*/
DO obs = 2 TO NumTotal;
IF IntID[obs]<IntID[obs-1] THEN DO;
PRINT("Error -- Possible bug -- Internal ID variable not sorted.");
MacroError = 1;
END;
IF IntID[obs]>IntID[obs-1] THEN DO;
/* Start new subject */
sub = sub + 1;
SBySub[sub,] = SByObs[obs,];
END; ELSE DO;
/* Continuing old subject. Check to make sure that the S variables
are constant within-subject. */
IF SBySub[sub,] ^= SByObs[obs,] THEN DO;
IF (GaveErrorMessage=0) THEN DO;
PRINT("Error -- The S variables do not appear to be constant within subject.");
PRINT "Check observation # " obs " and subject # " sub "in the dataset.";
GaveErrorMessage = 1;
END;
MacroError = 1;
END;
END;
END;
IF((SBySub[<>,]=SBySub[><,])[+]>1) THEN DO;
PRINT("Error -- One of the S variables (not the intercept) seems to be a constant.");
MacroError = 1;
END;
IF(NCOL(SBySub)^=NROW(SCovArray)) THEN DO;
PRINT("Error -- Difficulty deciding number of S variable columns.");
MacroError = 1;
END;
IF MacroError>0 THEN DO;
EDIT MixTVEMSettings VAR{MacroError}; MacroError = MacroError; REPLACE; CLOSE MixTVEMSettings;
END;
CREATE MixTVEMSBySub FROM SBySub [ COLNAME = SCovArray ]; APPEND FROM SBySub; CLOSE MixTVEMSBySub;
QUIT;
%IF %EVAL(&MixTVEMDebug>0) %THEN %PUT Finished preparing S matrix;
%IF %EVAL(&MixTVEMDebug>0) %THEN %PUT Now prepare random seeds;
DATA MixTVEMRandomSeeds;
DO SeedID = 1 TO &MixTVEMNumStarts;
Seeds = ROUND(RANUNI(&MixTVEMInitialSeed)*1000000);
LogLik = .;
RSS = .;
GCV = .;
AIC = .;
BIC = .;
SmallestPrevalence = .;
LargestPrevalence = .;
Estim_ProportionNugget = .;
Estim_Rho = .;
OUTPUT;
END;
RUN;
%IF %EVAL(&MixTVEMDebug>0) %THEN %PUT Finished preparing random seeds;
PROC IML;
%IF %EVAL(&MixTVEMDebug>0) %THEN %PUT Start preparing regressor matrix;
START SafeExp(x);
y = .*x;
IF ((x< 30)[+]>0) THEN y[LOC(x< 30)] = EXP(x[LOC(x<30)]);
IF ((x>=30)[+]>0) THEN y[LOC(x>=30)] = EXP(30);
RETURN(y);
FINISH;
START nls_function(p) GLOBAL(crossprods,lags,weights);
propnonnugget = SafeExp(p[1])/(1+SafeExp(p[1]));
logrho = p[2];
f = (weights#((crossprods-propnonnugget*SafeExp(logrho*lags))##2))[+];
RETURN(f);
FINISH nls_function;
START CreateWeightingMatrices;
Inv_Y_CorrMats_Stacked = J(NumTotal,Highest_Num_Observations,0);
Det_Y_Covmats = J(NumSubjects,1,0);
DO i = 1 TO IntID[<>];
these=LOC(IntID=i);
ni = SUM(IntID=i);
ti = Time[these];
ti_matrix = REPEAT(ti,1,NROW(ti));
IF (Working_Rho>1E-5) THEN DO;
y_covmat_these = (1-Working_ProportionNugget)*(Working_Rho**(ABS(ti_matrix - ti_matrix`))) +
Working_ProportionNugget*I(NROW(ti));
Inv_Y_CorrMats_Stacked[these,1:ni] = INV(y_covmat_these);
Det_Y_Covmats[i] = DET(y_covmat_these);
END; ELSE DO;
Inv_Y_CorrMats_Stacked[these,1:ni] = I(NROW(ti));
Det_Y_Covmats[i] = 1;
END;
END;
CREATE Inv_Y_CorrMats_Stacked FROM Inv_Y_CorrMats_Stacked;
APPEND FROM Inv_Y_CorrMats_Stacked;
CLOSE Inv_Y_CorrMats_Stacked;
CREATE Det_Y_Covmats FROM Det_Y_Covmats;
APPEND FROM Det_Y_Covmats;
CLOSE Det_Y_Covmats;
FINISH CreateWeightingMatrices;
START my_Bspline(x, knots, d);
/* evaluate the values of (num of knots) + d +1 B-spline basis functions at x, x is a real number*/
/* output a vector of (num of knots) + 1 - d real numbers */
/* knots include both exterior and inner knots */
n_ext = ncol(knots);
all_knots = (1:(n_ext+2));
all_knots[1] = knots[1] - (1e-12);
all_knots[2:(n_ext+1)]= knots;
all_knots[n_ext+2] = knots[n_ext] + (1e-12);
n_ext =n_ext+2;
tmp=0.0*(1:(n_ext-1));
DO i = 1 TO (n_ext-1);
IF (x>=all_knots[i] & x<all_knots[i+1]) THEN tmp[i]=1.0;
END;
j=1;
DO WHILE (j<=d); /* the De Boor formula, refer to Eilers & Marx (1996) */
DO i = 1 TO (n_ext-j-1);
w1 = (x-all_knots[i])/(all_knots[i+j] - all_knots[i]);
w2 = (all_knots[i+j+1]-x)/(all_knots[i+j+1] - all_knots[i+1]);
tmp[i] = w1*tmp[i] +w2*tmp[i+1];
END;
j=j+1;
END;
RETURN(tmp[1:(n_ext-d-1)]);
FINISH my_Bspline;
START my_vec_Bspline(xx, knots, d);
/* evaluate the values of the (num of knots) + d +1 B-spline basis functions at xx */
/* xx is a vector of real numbers*/
/* output a real matrix with dim(xx) rows, and (num of knots) + d +1 columns */
n_row = ncol(xx);
n_col = ncol(knots)+2-d-1;
out = J(n_row, n_col, .);
DO i=1 TO n_row;
out[i, ] = t(my_Bspline(xx[i], knots, d));
END;
RETURN(out);
FINISH my_vec_Bspline;
START GenerateTimeBasis(TimeBasis,Time, InteriorKnots,deg);
* B-Spline basis;
numIntervals = NCOL(InteriorKnots)+1;
dx = (time[<>]-time[><])/numIntervals;
EarlyKnots = InteriorKnots[><]-dx*((deg):1);
LateKnots = InteriorKnots[<>]+dx*(1:(deg));
AllKnots = EarlyKnots || InteriorKnots || LateKnots;
CREATE MixTVEMAllBSplineKnots FROM AllKnots;
APPEND FROM AllKnots;
CLOSE MixTVEMAllBSplineKnots;
TimeBasis = my_vec_Bspline(Time`, AllKnots, deg);
FINISH GenerateTimeBasis;
START PrepareRegressionMatrix;
USE MixTVEMData;
READ ALL VAR {&time} INTO Time;
CLOSE MixTVEMData;
USE MixTVEMSettings;
READ ALL VAR {deg MacroError NumCov
NumTCov RoughnessPenalty};
CLOSE MixTVEMSettings;
USE MixTVEMInteriorKnotsMatrix;
READ ALL INTO InteriorKnotsMatrix;
CLOSE MixTVEMInteriorKnotsMatrix;
IF (NumCov > 0) THEN DO;
USE MixTVEMData;
READ ALL VAR{&MixTVEMCov} INTO Cov;
CLOSE MixTVEMData;
Regressors = Cov;
whichBeta = J(NCOL(Cov),1,.);
whichThetaWithinBeta = (1:NCOL(Cov))`;
END;
IF (NumTCov > 0) THEN DO;
USE MixTVEMData;
READ ALL VAR{&MixTVEMTCov} INTO TCov;
CLOSE MixTVEMData;
tcovStdDev = J(NCOL(TCov),1,1);
DO thisTCov = 1 TO NCOL(TCov);
IF NROW(TCov)>1 THEN DO;
TcovStdDev[thisTCov] = SQRT(((TCov[,thisTCov]-TCov[:,thisTCov])[##])/(NROW(TCov[,thisTCov])-1));
END;
IF (ABS(TcovStdDev[thisTCov])<1e-20) THEN DO;
IF tcov[<>,thisTCov]=1 THEN DO;
TcovStdDev[thisTCov] = 1; /* do not rescale intercept term */
END;
END;
InteriorKnots = InteriorKnotsMatrix[LOC(InteriorKnotsMatrix[,thisTCov]^=.), thisTCov]`;
CALL GenerateTimeBasis(TimeBasis,
Time,
InteriorKnots,
deg);
datasetName = COMPRESS(CONCAT("MixTVEMTimeBasis",CHAR(thisTCov)));
commandText = CONCAT("CREATE ",
datasetName,
" FROM TimeBasis;",
" APPEND FROM TimeBasis;",
" CLOSE ",
datasetName,
";");
CALL EXECUTE(commandText);
covariateTimesTimeBasis = TCov[,thisTCov]#TimeBasis;
IF ((NumCov=0)&(thisTCov =1)) THEN DO;
Regressors = covariateTimesTimeBasis;
whichBeta = J(NCOL(TimeBasis),1,thisTCov);
whichThetaWithinBeta = (1:NCOL(TimeBasis))`;
END; ELSE DO;
Regressors = Regressors || covariateTimesTimeBasis;
whichBeta = whichBeta // J(NCOL(TimeBasis),1,thisTCov);
whichThetaWithinBeta = whichThetaWithinBeta // (1:NCOL(TimeBasis))`;
END;
END;
END;
PenaltyMatrix = J(NROW(whichBeta),NROW(whichBeta),0);
IF whichBeta[<>]>0 THEN DO;
DO i = 1 TO whichBeta[<>];
IF (whichBeta[i] >0) THEN DO;
n_theta = NCOL(LOC(whichBeta=i));
PenaltyMatrix[LOC(whichBeta=i),LOC(whichBeta=i)] =
CreatePenaltyMatrix(n_theta);
END;
END;
END;
TVScales = J(nrow(whichBeta),1,1);
DO i = 1 TO whichBeta[<>];
IF tcovStdDev[i]>0 THEN TVScales[LOC(whichBeta=i)]=1/(tcovStdDev[i]+1e-20);
END;
PenaltyMatrix = TVScales#TVScales#PenaltyMatrix;
CREATE MixTVEMRegressors FROM Regressors; APPEND FROM Regressors; CLOSE MixTVEMRegressors;
CREATE MixTVEMWhichBeta FROM whichBeta; APPEND FROM whichBeta; CLOSE MixTVEMWhichBeta;
CREATE MixTVEMWhichThetaWithinBeta FROM whichThetaWithinBeta; APPEND FROM whichThetaWithinBeta; CLOSE MixTVEMWhichThetaWithinBeta;
CREATE MixTVEMPenaltyMatrix FROM PenaltyMatrix; APPEND FROM PenaltyMatrix; CLOSE MixTVEMPenaltyMatrix;
EDIT MixTVEMSettings VAR{MacroError};
MacroError = MacroError;
REPLACE;
CLOSE MixTVEMSettings;
FINISH PrepareRegressionMatrix;
START CreatePenaltyMatrix(n);
/* The R version is
crossprod(diff(diff(diag(as.vector(rep(1,n))))));
see Eilers & Marx (1996) p. 100 */
M = J(n,n,0);
IF n>2 THEN DO;
DO r = 1 TO n;
DO c = 1 TO n;
IF r = c THEN DO;
M[r,c] = 6;
IF ((r=1)|(r=n)) THEN M[r,c] = 1;
IF ((r=2)|(r=n-1)) THEN DO;
IF n>3 THEN M[r,c] = 5; ELSE M[r,c] = 4;
END;
END;
IF (ABS(r-c)=1) THEN DO;
M[r,c] = -4;
IF ((r=1)|(c=1)|(r=n)|(c=n)) THEN M[r,c] = -2;
END;
IF (ABS(r-c)=2) THEN DO;
M[r,c] = 1;
END;
END;
END;
END;
RETURN(M);
FINISH CreatePenaltyMatrix;
START WeightedLogistic(b,
w, /* w,x,y, are all for observations */
x,
y);
localw = w[LOC(y^=.)];
localx = x[LOC(y^=.),];
localy = y[LOC(y^=.)];
b = J(NCOL(localx),1,0);
MaxAbsDev = 10000000;
CriterionMaxAbsDev = 1e-8;
MaxIter=1000;
iter=0;
DO UNTIL((iter=maxIter) | (maxAbsDev<=criterionMaxAbsDev));
iter = iter + 1;
bOld = b;
expEta = EXP(((localx*b)><20)<>-20);
mu = expEta/(1+expEta);
b = b + SOLVE(localx`*(mu#(1-mu)#localw#localx),
localx`*(localw#(localy-mu)));
maxAbsDev = MAX(ABS(b-bOld));
END;
FINISH WeightedLogistic;
START WeightedRidgeRegression(b,
w, /* weights for subjects, not observations! */
x, /* x,y are for observations */
y,
sigsqtotal_thisclass,
RoughnessPenalty,
PenaltyMatrix,
intID,
Time) GLOBAL(Inv_Y_CorrMats_Stacked);
denominator = J(NCOL(x),NCOL(x),0);
numerator = J(NCOL(x),1,0);
DO i = 1 TO intID[<>];
these = LOC(IntID=i);
ti = Time[these,];
ti_matrix = REPEAT(ti,1,NROW(ti));
ni = SUM(IntID=i);
inv_y_covmat_these = Inv_Y_CorrMats_Stacked[these,1:ni]/sigsqtotal_thisclass;
xi = x[these,];
yi = y[these,];
denominator = denominator + w[i]*xi`*inv_y_covmat_these*(xi);
numerator = numerator + w[i]*xi`*inv_y_covmat_these*(yi);
END;
b = SOLVE( denominator + RoughnessPenalty*PenaltyMatrix,
numerator );
FINISH WeightedRidgeRegression;
START WeightedHatMatrixTrace(enrp_this_class,
wbysub,
wbyobs,
x,
y,
sigsqtotal_thisclass,
RoughnessPenalty,
PenaltyMatrix,
intID,
Time) GLOBAL(Inv_Y_CorrMats_Stacked);
/* Called once per class */
XTWX = J(NCOL(x),NCOL(x),0);
DO i = 1 TO intID[<>];
these = LOC(intID=i);
ni = SUM(IntID=i);
inv_y_covmat_these = Inv_Y_CorrMats_Stacked[these,1:ni]/sigsqtotal_thisclass;
xi = x[these,];
yi = y[these,];
XTWX = XTWX + wbysub[i]*xi`*inv_y_covmat_these*(xi);
END;
denominator = XTWX + RoughnessPenalty*PenaltyMatrix ;
inv_denominator = INV(denominator);
enrp_this_class = 0;
/* Effective number of regression parameters for this class */
DO i = 1 TO intID[<>];
these = LOC(intID=i);
ni = SUM(IntID=i);
inv_y_covmat_these = Inv_Y_CorrMats_Stacked[these,1:ni]/sigsqtotal_thisclass;
xi = x[these,];
temp = xi*inv_denominator*(xi`)*inv_y_covmat_these;
enrp_this_class = enrp_this_class + wbysub[i]*TRACE(temp);
END;
FINISH;
START CopyToLongForm(longTarget,shortSource,intID);
longTarget = J(NROW(intID),NCOL(shortSource),0);
DO I = 1 TO NROW(shortSource);
longTarget[LOC(intID=i),] = shortSource[i,] @ J(SUM(intID=i),1,1);
END;
FINISH CopyToLongForm;
START InitialRandomEStep;
postProbsBySubject = J(NumSubjects,NumClasses,0);
CALL RANDGEN(postProbsBySubject,"exponential");
postProbsBySubject = (1/postProbsBySubject[,+])#postProbsBySubject;
SigSqTotal = J(NumClasses,1,1); /* arbitrary initial values of 1 */
FINISH InitialRandomEStep;
START MStep;
/* ... for Theta ... */
Theta = J(NCOL(X),numClasses,.);
DO class = 1 TO numClasses;
CALL WeightedRidgeRegression(b,
postProbsBySubject[,class],
X,
Y,
SigSqTotal[class],
RoughnessPenalty,
PenaltyMatrix,
intID,
Time);
Theta[,class] = b;
END;
fittedY = X*Theta;
/* ... for sigma squareds ... */
sqdResidY = (fittedY - Y@J(1,numClasses,1))##2;
rssBySubjectAndClass = J(numSubjects,numClasses,0);
numObsBySubject = J(numSubjects,1,0);
DO i = 1 TO numSubjects;
rssBySubjectAndClass[i,] = (sqdResidY[LOC(intId=i),])[+,];
numObsBySubject[i] = NCOL(LOC(intId=i));
END;
SigSqTotal = ((rssBySubjectAndClass#postProbsBySubject)[+,])/
((numObsBySubject#postProbsBySubject)[+,]);
IF ((SigSqTotal[<>]/SigSqTotal[><])>maxVarianceRatio) THEN DO;
SigSqTotal[LOC(SigSqTotal<(SigSqTotal[<>]/maxVarianceRatio))]=SigSqTotal[<>]/maxVarianceRatio;
END;
/* ... and for gammas ... */
USE MixTVEMSBySub; READ ALL INTO S; CLOSE MixTVEMSCov;
SForLogisticRegression = S @ J(numClasses,1,1);
ClassForLogisticRegression = SHAPE((1:numClasses) @ J(numSubjects,1,1),
numClasses*numSubjects);
WeightsForLogisticRegression = SHAPE(PostProbsBySubject,numClasses*numSubjects);
IF (numClasses>1) THEN DO;
NonRefClasses = (1:numClasses)[LOC((1:numClasses)^=refClass)];
END;
gamma = J(NCOL(S),numClasses,0);
IF (NumClasses>1) THEN DO;
expEta = J(numSubjects,numClasses,1);
DO NonRefClassIndex = 1 TO NROW(NonRefClasses);
ThisNonRefClass = NonRefClasses[NonRefClassIndex];
OutcomeForLogisticRegression = 1*(ClassForLogisticRegression=ThisNonRefClass);
IF (NROW(LOC((ClassForLogisticRegression^=ThisNonRefClass)
&(ClassForLogisticRegression^=RefClass)))>0) THEN DO;
OutcomeForLogisticRegression[LOC((ClassForLogisticRegression^=ThisNonRefClass)
&(ClassForLogisticRegression^=RefClass))] = .;
END;
CALL WeightedLogistic(b,
WeightsForLogisticRegression,
SForLogisticRegression,
OutcomeForLogisticRegression);
gamma[,ThisNonRefClass] = b;
expEta[,ThisNonRefClass] = SafeExp(S*b);
END;
fittedProb = expEta / expEta[,+];
END; ELSE DO;
fittedProb = J(numSubjects,1,1);
END;
FINISH MStep;
START EStep;
/* Get new likelihood contributions and posterior probabilities; */
logProbabilityBySubjectAndClass = J(numSubjects,numClasses,0);
IF (Working_Rho<1e-20) THEN Working_Rho =1e-20;
/* This is mainly to avoid problems with raising 0 to the 0th power */
DO class = 1 TO numClasses;
DO i = 1 TO intID[<>];
these = LOC(intID=i);
numObs = NCOL(these);
ti = Time[these,];
mui = fittedY[these,class];
yi = y[these,];
ni = SUM(IntID=i);
inv_y_covmat_these = Inv_Y_CorrMats_Stacked[these,1:ni]/SigSqTotal[class];
thisWeightedSumSquares = (yi-mui)`*inv_y_covmat_these*(yi-mui);
determinant = (SigSqTotal[class]**ni)*Det_Y_Covmats[i];
logProbabilityBySubjectAndClass[i,class] = -(numObs/2)*LOG(2*3.1415926535) -
0.5*(LOG(determinant+1e-30)) -
0.5*thisWeightedSumSquares;
END;
END;
tempMatrix = logProbabilityBySubjectAndClass + LOG(fittedProb+1e-30);
logLik = (LOG((EXP(tempMatrix))[,+]))[+];
tempMax = tempMatrix[,<>];
tempMatrix = tempMatrix-tempMax;
expTempMatrix = EXP(tempMatrix);
postProbsBySubject = expTempMatrix / expTempMatrix[,+];
FINISH EStep;
START EMLoop;
OldTheta = 1e20;
OldGamma = 1e20;
maxAbsDev = 1e20;
iteration = 0;
Converged = 0;
DO UNTIL ((maxAbsDev<Convergence)|(iteration > MaxIterationsToUse));
iteration = iteration + 1;
postProbsByObservation = J(NumTotal,NumClasses,0);
CALL CopyToLongForm(postProbsByObservation,postProbsBySubject,intID);
CALL MStep;
CALL EStep;
maxAbsDev = MAX( (ABS(gamma-oldGamma))[<>,<>], (ABS(theta-oldTheta))[<>,<>]);
oldGamma = Gamma;
oldTheta = Theta;
END;
IF (maxAbsDev<Convergence) THEN DO;
Converged = 1;