forked from djangraw/MoodDrift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProduceAllResults.py
1698 lines (1452 loc) · 74.2 KB
/
ProduceAllResults.py
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Produce all results for the Mood Drift Over Time paper.
To use, run whole script or cell-by-cell for specific results.
- Created 10/22/20 by DJ.
- Updated 3/31/21 by DJ - adapted for shared code structure.
- Updated 5/6/21 by DJ - added code to produce several figures found in paper
- Updated 3/8/22 by DJ - moved horizontal reference line to mean initial mood
- Updated 3/10/22 by DJ - added life happiness vs. LME mood slope jointplot
- Updated 9/29/22 by DJ - added descriptive statistics, switched to TRIMD in titles
- Updated 9/30/22 by DJ - save figures as both png and pdf
- Updated 10/7/22 by DJ - switched from TRIMD to "mood drift" in titles
"""
# Import packages
import MoodDrift.Analysis.PlotMmiData as pmd
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from MoodDrift.Analysis.CompareMmiRatings import CompareMmiRatings
import MoodDrift.Analysis.PlotPytorchPenaltyTuning as ppt
from MoodDrift.Analysis.CalculatePytorchModelError import CalculatePytorchModelError
from MoodDrift.Analysis.PlotAgeVsCoeffs import PlotAgeVsCoeffs
from MoodDrift.Analysis.PlotTimeOfDayVsSlopeAndIntercept import PlotTimeOfDayVsSlopeAndIntercept
from MoodDrift.Analysis.PlotPymerFits import PlotPymerHistosJoint
import MoodDrift.Analysis.GetMmiIcc as gmi
from scipy import stats
import seaborn as sns
# Use exploratory (True) or Confirmatory (False) mobile app participants?
IS_EXPLORE = False # GbeExplore (True) or GbeConfirm (False)
dataDir = '../Data/OutFiles' # path to processed data
pytorchDir = '../Data/GbePytorchResults' # path to model fitting results
outFigDir = '../Figures' # where model fitting figures should be saved
have_gbe = True
# function to control how figures get saved
def save_figure(filename,**kwargs):
"""
Save a figure as both .png and .eps files.
INPUTS:
-------
filename: str
The filename where you want to save the figure (with no extension).
**kwargs: dict
Any other inputs you want to send to plt.savefig
OUTPUTS:
--------
None.
"""
# save both png and eps versions
for extension in ['png', 'pdf']:
outFig = f'{filename}.{extension}'
print('Saving figure as %s...'%outFig)
plt.savefig(outFig,format=extension,**kwargs)
print('Done!')
# %% Print Cohen's D for original cohort and others
first_and_lasts = []
for batchName in ['Recovery(Instructed)1', 'AdultOpeningRest', 'RecoveryNimh-run1','AllOpeningRestAndRandom']:
dfRating = pd.read_csv('%s/Mmi-%s_Ratings.csv'%(dataDir,batchName), index_col=0)
#dfMeanRating = pmd.GetMeanRatings(dfRating.loc[dfRating.iBlock==0,:],nRatings=-1,participantLabel='mean')
nSubj = len(np.unique(dfRating.participant))
first_trial = dfRating.loc[(dfRating.iBlock == 0)].groupby('participant').first().reset_index()
last_trial = dfRating.loc[dfRating.iBlock == 0].groupby('participant').last().reset_index()
first_and_last = first_trial.merge(last_trial, how='left', on='participant', suffixes=['_first', '_last'])
first_and_last['dif'] = first_and_last.rating_last - first_and_last.rating_first
first_and_last['time_dif'] = first_and_last.time_last - first_and_last.time_first
first_and_last['batch'] = batchName
first_and_lasts.append(first_and_last)
M0 = first_and_last.rating_first.mean()
M1 = first_and_last.rating_last.mean()
SD0 = first_and_last.rating_first.std()
SD1 = first_and_last.rating_last.std()
t1 = (first_and_last.time_last - first_and_last.time_first).mean()/60
SDpooled = np.sqrt((SD0**2+SD1**2)/2)
cohensD = (M1-M0)/SDpooled
md_se = first_and_last.dif.std()/np.sqrt(len(first_and_last))
print(f"Batch {batchName} (n={nSubj}): After {t1:.1f} minutes, difference is {(M1-M0)*100:0.2f} +- {md_se*100:0.2f}, Cohen's D = {cohensD:.3g}")
first_and_lasts = pd.concat(first_and_lasts)
adult_difs = first_and_lasts.loc[first_and_lasts.batch == 'AdultOpeningRest'].dif
adolescent_difs = first_and_lasts.loc[first_and_lasts.batch == 'RecoveryNimh-run1'].dif
stat, pvalue = stats.ttest_ind(adult_difs, adolescent_difs)
print(f"Difference between adult and adolescent: n = {len(adult_difs) + len(adolescent_difs)} dof = {len(adult_difs) + len(adolescent_difs) - 2}, stat= {stat:.3g}, pvalue= {pvalue:.3g}")
# %% Plot all naive opening rest batches separately
batchNames = ['Recovery(Instructed)1', 'Expectation-7min','Expectation-12min','RestDownUp','Stability01-Rest','COVID01']
batchLabels = ['15sRestBetween','Expectation-7mRest','Expectation-12mRest','RestDownUp','Daily-Rest-01','Weekly-Rest-01']
plt.figure(500,figsize=(10,12),dpi=180);
plt.subplot(3,1,1)
CompareMmiRatings(batchNames,batchLabels=batchLabels,iBlock=0,doInterpolation=True,makeNewFig=False)
# Annotate plot
plt.title('Mood drift persists across all MTurk cohorts receiving opening rest')
plt.gca().set_axisbelow(True)
plt.ylim([0.4,0.8])
plt.grid()
plt.text(-0.1, 1.1, 'a', transform=plt.gca().transAxes,
size=40)#, weight='bold')
# Save figure
# outFig = '%s/Mmi_%s_Comparison'%(outFigDir,'-'.join(batchNames))
# save_figure(outFig)
# %% Plot simple task cohorts
batchNames = ['Recovery(Instructed)1','MotionFeedback','Stability01-RandomVer2']
#batchLabels = ['Rest','Visuomotor task','Random gambling']
batchLabels = ['15sRestBetween','Visuomotor-Feedback','Daily-Random-01']
plt.subplot(3,1,2)
CompareMmiRatings(batchNames,batchLabels=batchLabels,iBlock='all',doInterpolation=True,makeNewFig=False)
# Annotate plot
plt.title('Mood drift persists in presence of simple tasks')
plt.gca().set_axisbelow(True)
plt.ylim([0.4,0.8])
plt.xlim([-20,500])
plt.grid()
plt.text(-0.1, 1.1, 'b', transform=plt.gca().transAxes,
size=40)#, weight='bold')
# Save figure
# outFig = '%s/Mmi_%s_Comparison'%(outFigDir,'-'.join(batchNames))
# save_figure(outFig)
# %% Plot online adult vs. in-person adolescent cohort
batchNames = ['AdultOpeningRest','RecoveryNimh-run1']
batchLabels = ['MTurk cohorts','In-person adolescent cohort']
plt.subplot(3,1,3)
CompareMmiRatings(batchNames,batchLabels=batchLabels,iBlock=0,doInterpolation=True,makeNewFig=False)
# Annotate plot
plt.title('Mood drift generalizes to different age group & recruitment method')
plt.gca().set_axisbelow(True)
plt.ylim([0.4,0.8])
plt.grid()
# Save figure
# outFig = '%s/Mmi_%s_Comparison'%(outFigDir,'-'.join(batchNames))
# save_figure(outFig)
plt.text(-0.1, 1.1, 'c', transform=plt.gca().transAxes,
size=40)#, weight='bold')
plt.tight_layout()
outFig = '%s/PotdTimecourses'%(outFigDir)
save_figure(outFig)
# %% LME results: Mean decline and Cohen's D with time
# Load LME results
batchName = 'AllOpeningRestAndRandom'
stage = 'full'
inFile = '%s/Mmi-%s_pymerCoeffs-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfCoeffs = pd.read_csv(inFile)
print('Done!')
# Cohen's D for LME results
moodSlope = dfCoeffs.Time
mood10 = moodSlope*10.0 # decline in mood after 10 minutes
D = np.mean(mood10)/np.std(mood10)
stat,p = stats.wilcoxon(moodSlope)
print('===LME RESULTS FOR ONLINE PARTICIPANTS:===')
print('Decline in mood = %.3g +/- %.3g %%/min'%(np.mean(moodSlope*100),np.std(moodSlope*100)/np.sqrt(moodSlope.size)))
print('Decline in mood after 10 minutes: %.3g%% +/- %.3g, Cohen''s D=%.3g'%(np.mean(mood10)*100, np.std(mood10*100)/np.sqrt(mood10.size),D))
print('Wilcoxon signed rank vs. 0: W=%.3g, p=%.3g'%(stat,p))
slope_range = dfCoeffs.Time.quantile([0.025,0.975]).values*100
print(f"2.5percentile slope = {slope_range[0]:0.3f}, 97.5percentile slope = {slope_range[1]:0.3f}")
# %% Test difference between adolescents and not
isAdolescent = dfCoeffs.Subject<0
T,p = stats.ttest_ind(dfCoeffs.loc[isAdolescent,'Time'],dfCoeffs.loc[~isAdolescent,'Time'])
print('Adolescents vs. not: T=%.3g, p=%.3g'%(T,p))
# Do same with mood slope in AllOpeningRestAndRandom adolescents vs. not
stage = 'full'
batchName = 'AllOpeningRestAndRandom'
inFile = '%s/Mmi-%s_pymerCoeffs-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfCoeffs = pd.read_csv(inFile)
print('Done!')
# Get inferential statistics
isAdolescent = dfCoeffs.Subject<0
T,p = stats.ttest_ind(dfCoeffs.loc[isAdolescent,'Time'],dfCoeffs.loc[~isAdolescent,'Time'])
# get descriptive statistics
n0 = np.sum(isAdolescent)
n1 = np.sum(~isAdolescent)
dof = n0 + n1 - 2
mean0 = np.mean(dfCoeffs.loc[isAdolescent,'Time']*100)
ste0 = np.std(dfCoeffs.loc[isAdolescent,'Time']*100)/np.sqrt(n0)
mean1 = np.mean(dfCoeffs.loc[~isAdolescent,'Time']*100)
ste1 = np.std(dfCoeffs.loc[~isAdolescent,'Time']*100)/np.sqrt(n1)
CI = stats.norm.interval(alpha=0.95, loc=mean0-mean1, scale=np.sqrt(ste0**2 + ste1**2))
# print statistics
# print(f' {batchNames[0]}: mean +/- ste = {mean0:.3g} +/- {ste0:.3g}')
# print(f' {batchNames[1]}: mean +/- ste = {mean1:.3g}. +/- {ste1:.3g}')
print('*** %s (n=%d) vs. %s (n=%d): T=%.3g, dof=%.3g p=%.3g'%('Adolescent',n0,'Adult',n1,T,dof,p))
print(f' {mean0:.3g} vs. {mean1:.3g}, 95\%CI= {CI[0]:.3g} to {CI[1]:.3g}')
# %% Get impacts of gender, IRI, winnings, & RPEs from the LME results table
batchName = 'AllOpeningRestAndRandom'
stage = 'full'
inFile = '%s/Mmi-%s_PymerFit-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfFits = pd.read_csv(inFile,index_col=0)
print('Done!')
m = dfFits.loc['Time:isMaleTRUE','Estimate']*100
se = dfFits.loc['Time:isMaleTRUE','SE']*100
T = dfFits.loc['Time:isMaleTRUE','T-stat']
dof = dfFits.loc['Time:isMaleTRUE', 'DF']
p = dfFits.loc['Time:isMaleTRUE','P-val']
print('Gender x slope in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
m = dfFits.loc['Time:meanIRIOver20','Estimate']*100
se = dfFits.loc['Time:meanIRIOver20','SE']*100
T = dfFits.loc['Time:meanIRIOver20','T-stat']
dof = dfFits.loc['Time:meanIRIOver20', 'DF']
p = dfFits.loc['Time:meanIRIOver20','P-val']
print('Inter-Rating Interval x slope in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
m = dfFits.loc['Time:totalWinnings','Estimate']*100
se = dfFits.loc['Time:totalWinnings','SE']*100
T = dfFits.loc['Time:totalWinnings','T-stat']
dof = dfFits.loc['Time:totalWinnings', 'DF']
p = dfFits.loc['Time:totalWinnings','P-val']
print('Total Winnings x slope in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
m = dfFits.loc['Time:meanRPE','Estimate']*100
se = dfFits.loc['Time:meanRPE','SE']*100
T = dfFits.loc['Time:meanRPE','T-stat']
dof = dfFits.loc['Time:meanRPE', 'DF']
p = dfFits.loc['Time:meanRPE','P-val']
print('Mean RPE x slope in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
# %% Table02
print('Table 2 comes from %s.'%inFile)
# %% Plot mood over time with various IRIs
batchNames = ['RecoveryInstructed1Freq0p25','RecoveryInstructed1Freq0p5','Recovery(Instructed)1','RecoveryInstructed1Freq2']
#batchLabels = ['60 s rest between ratings','30 s rest between ratings','15 s rest between ratings','7.5 s rest between ratings']
batchLabels = ['60sRestBetween','30sRestBetween','15sRestBetween','7.5sRestBetween']
CompareMmiRatings(batchNames,batchLabels=batchLabels,iBlock=0,doInterpolation=True)
# Annotate plot
plt.title('Mood rating frequency does not affect mood drift slope')
plt.gca().set_axisbelow(True)
plt.ylim([0.4,0.8])
plt.grid()
# Save figure
#outFig = '%s/Mmi_%s_Comparison'%(outFigDir,'-'.join(batchNames))
outFig = '%s/Mmi_RatingFrequency_Comparison'%outFigDir
save_figure(outFig)
# %% Rating Method, Expectations, Task, Random Gambling
inFile = '%s/Mmi-%s_PymerCoeffs-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer coefficients from %s...'%inFile)
dfCoeffs = pd.read_csv(inFile)
print('Done!')
inFile = '%s/Mmi-%s_PymerInput-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer input from %s...'%inFile)
dfPymerIn = pd.read_csv(inFile,index_col=0)
dfPymerIn.loc[dfPymerIn.Cohort=='Recovery1','Cohort'] = 'Recovery(Instructed)1'
dfPymerIn.loc[dfPymerIn.Cohort=='RecoveryInstructed1','Cohort'] = 'Recovery(Instructed)1'
for batchNames in [['Numbers','Recovery(Instructed)1'],
['Expectation-7min','Expectation-12min'],
['MotionFeedback','Recovery(Instructed)1'],
['Stability01-RandomVer2','Recovery(Instructed)1']]:
cohort0 = np.unique(dfPymerIn.loc[dfPymerIn.Cohort==batchNames[0],'Subject'])
isIn0 = [x in cohort0 for x in dfCoeffs.Subject]
cohort1 = np.unique(dfPymerIn.loc[dfPymerIn.Cohort==batchNames[1],'Subject'])
isIn1 = [x in cohort1 for x in dfCoeffs.Subject]
# get inferential statistics
T,p = stats.ttest_ind(dfCoeffs.loc[isIn0,'Time'],dfCoeffs.loc[isIn1,'Time'])
n0 = np.sum(isIn0)
n1 = np.sum(isIn1)
dof = n0 + n1 - 2
# get descriptive statistics
mean0 = np.mean(dfCoeffs.loc[isIn0,'Time']*100)
ste0 = np.std(dfCoeffs.loc[isIn0,'Time']*100)/np.sqrt(n0)
mean1 = np.mean(dfCoeffs.loc[isIn1,'Time']*100)
ste1 = np.std(dfCoeffs.loc[isIn1,'Time']*100)/np.sqrt(n1)
CI = stats.norm.interval(alpha=0.95, loc=mean0-mean1, scale=np.sqrt(ste0**2 + ste1**2))
# print statistics
# print(f' {batchNames[0]}: mean +/- ste = {mean0:.3g} +/- {ste0:.3g}')
# print(f' {batchNames[1]}: mean +/- ste = {mean1:.3g}. +/- {ste1:.3g}')
print('*** %s (n=%d) vs. %s (n=%d): T=%.3g, dof=%.3g p=%.3g'%(batchNames[0],n0,batchNames[1],n1,T,dof,p))
print(f' {mean0:.3g} vs. {mean1:.3g}, 95\%CI= {CI[0]:.3g} to {CI[1]:.3g}')
if have_gbe:
for is_late in [False,True]:
print(f'=== Pytorch Penalty Tuning: is_late={is_late}')
# %% Pytorch: including beta_T improves fit to testing data
CalculatePytorchModelError(IS_EXPLORE, IS_LATE=is_late, dataDir = dataDir, pytorchDir = pytorchDir, outFigDir = outFigDir)
# %% Plot penalty tuning
for suffix in ['_tune-Oct2020', '_tune-noBetaT']:
print(f'=== Pytorch Penalty Tuning: {suffix}')
ppt.PlotPenaltyTuning(suffix,dataDir=pytorchDir,outFigDir=outFigDir)
# %% Penalty tuning excluding first rating (12/19/20)
for suffix in ['_tune-late','_tune-late-noBetaT']:
print(f'=== Pytorch Penalty Tuning: {suffix}')
ppt.PlotPenaltyTuning(suffix,dataDir=pytorchDir,outFigDir=outFigDir)
# %% Plot parameter distributions
if IS_EXPLORE:
suffix = '_GbeExplore'
else:
suffix = '_GbeConfirm'
for stage in ['full','late']:
if stage=='late':
suffix = suffix + '-late'
# Load results
paramInFile = '%s/PyTorchParameters%s.csv'%(pytorchDir,suffix)
print('Loading pyTorch best parameters from %s...'%paramInFile)
best_pars = pd.read_csv(paramInFile,index_col=0).drop('participant',axis=1);
params = best_pars.columns; # exclude lifeHappiness
paramLabelDict = {'m0': r'$M_0$',
'lambda': r'$\lambda$',
'beta_E': r'$\beta_E$',
'beta_A': r'$\beta_A$',
'beta_T': r'$\beta_T$',
'SSE': 'SSE',
'lifeHappy':'life happiness'}
print('Done!')
# Add lifeHappy to best_pars and beta_T to dfSummary
if IS_EXPLORE:
summaryFile = '%s/Mmi-GbeExplore_Summary.csv'%(dataDir)
else:
summaryFile = '%s/Mmi-GbeConfirm_Summary.csv'%(dataDir)
dfSummary = pd.read_csv(summaryFile,index_col=0)
best_pars['lifeHappy'] = dfSummary['lifeHappy'].values
dfSummary['beta_T'] = best_pars['beta_T'].values
isTop = best_pars.lifeHappy>=np.median(best_pars.lifeHappy)
# Plot parameter histograms
plt.figure(264,figsize=(14,6)); plt.clf()
nRows = 2
nCols = 3
for i,col in enumerate(params):
# plot
plt.subplot(nRows,nCols,i+1)
plt.hist(best_pars[col],50)
# annotate axis
plt.xlabel(paramLabelDict[col])
plt.ylabel('Number of subjects (n=%d)'%dfSummary.shape[0])
plt.grid()
# annotate figure
plt.tight_layout(rect=(0,0,1.0,0.93))
plt.suptitle('Computational model parameter fits')
# save results
outFile = '%s/PytorchParamHistos%s'%(outFigDir,suffix)
save_figure(outFile)
# %% Get stats on beta_T vs. 0
for stage in ['full','late']:
print('=== STAGE %s ==='%stage)
# Load pytorch results
if IS_EXPLORE:
suffix = '_GbeExplore'
else:
suffix = '_GbeConfirm'
if stage=='late':
suffix = suffix + '-late'
inFile = '%s/PyTorchParameters%s.csv'%(pytorchDir,suffix)
print('Loading best parameters from %s...'%inFile)
best_pars = pd.read_csv(inFile);
#stat,p = stats.ttest_1samp(best_pars['beta_T'],0)
print('mean +/- SE beta_T: %.3g%% mood/min +/- %.3g'%(np.mean(best_pars['beta_T'])*100,np.std(best_pars['beta_T'])*100/np.sqrt(best_pars.shape[0])))
#print('2-tailed t-test on beta_T vs. 0: T=%.3g, p=%.3g'%(stat,p))
stat,p = stats.wilcoxon(best_pars['beta_T'])
print(f'beta_T median={np.median(best_pars["beta_T"]*100):.3g}, IQR={stats.iqr(best_pars["beta_T"]*100):.3g} \%mood/min')
print(f'2-sided wilcoxon sign-rank test on beta_T vs. 0: n={len(best_pars)}, dof={len(best_pars) - 1}, stat={stat:0.3g}, p={p:.3g}')
print(f'stat in full {stat}')
# %% Get stats on Mobile app LME slopes vs. 0
batchName_online = 'AllOpeningRestAndRandom'
if IS_EXPLORE:
batchName_app = 'GbeExplore'
else:
batchName_app = 'GbeConfirm'
for stage in ['full','late']:
print('=== STAGE = %s ==='%stage)
#dfPymerFit = pd.read_csv('%s/Mmi-%s_pymerFit-full.csv'%(dataDir,batchName),index_col=0)
dfPymerCoeffs_online = pd.read_csv('%s/Mmi-%s_pymerCoeffs-%s.csv'%(dataDir,batchName_online,stage),index_col=0)
dfPymerCoeffs_app = pd.read_csv('%s/Mmi-%s_pymerCoeffs-%s.csv'%(dataDir,batchName_app,stage),index_col=0)
#stat,p = stats.ttest_1samp(best_pars['beta_T'],0)
print('mean +/- SE LME slope param: %.3g%% mood/min +/- %.3g'%(np.mean(dfPymerCoeffs_app["Time"])*100,np.std(dfPymerCoeffs_app["Time"])*100/np.sqrt(dfPymerCoeffs_app.shape[0])))
#print('2-tailed t-test on beta_T vs. 0: T=%.3g, p=%.3g'%(stat,p))
stat,p = stats.wilcoxon(dfPymerCoeffs_app['Time'])
print(f'2-sided wilcoxon sign-rank test on {batchName_app} LME slope vs. 0: n={len(dfPymerCoeffs_app["Time"])}, dof={len(dfPymerCoeffs_app["Time"]) - 1}, stat={stat:.3g}, p={p:.3g}')
print(f'{batchName_app} beta_T median={np.median(dfPymerCoeffs_app["Time"]*100):.3g}, IQR={stats.iqr(dfPymerCoeffs_app["Time"]*100):.3g} \%mood/min')
# Print ranksum comparison
stat,p = stats.ranksums(dfPymerCoeffs_online.Time, dfPymerCoeffs_app.Time)
nonline = len(dfPymerCoeffs_online.Time)
napp = len(dfPymerCoeffs_app.Time)
dof = nonline + napp - 2
print(f'Ranksum of LME time coeff for online ({batchName_online}) vs. mobile app ({batchName_app}): nonline={nonline}, napp={napp}, ndof={dof}, stat={stat:.3g}, p={p:.3g}')
print(f'{batchName_online} beta_T median={np.median(dfPymerCoeffs_online["Time"]*100):.3g}, IQR={stats.iqr(dfPymerCoeffs_online["Time"]*100):.3g} \%mood/min')
print(f'{batchName_app} beta_T median={np.median(dfPymerCoeffs_app["Time"]*100):.3g}, IQR={stats.iqr(dfPymerCoeffs_app["Time"]*100):.3g} \%mood/min')
# %% Compare LME and comp model
# Load pytorch results
if IS_EXPLORE:
suffix = '_GbeExplore'
else:
suffix = '_GbeConfirm'
inFile = '%s/PyTorchParameters%s.csv'%(pytorchDir,suffix)
print('Loading best parameters from %s...'%inFile)
best_pars = pd.read_csv(inFile);
for stage in ['full','late']:
print('=== STAGE = %s ==='%stage)
# Load LME results
batchName = 'AllOpeningRestAndRandom'
inFile = '%s/Mmi-%s_pymerCoeffs-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfCoeffs = pd.read_csv(inFile)
print('Done!')
# Print ranksum comparison
stat,p = stats.ranksums(dfCoeffs.Time, best_pars.beta_T)
nonline = len(dfCoeffs.Time)
napp = len(best_pars.beta_T)
dof = nonline + napp - 2
print(f'Ranksum of LME time coeff for online ({batchName}) vs. PyTorch beta_T for mobile app ({suffix}): nonline={nonline}, napp={napp}, ndof={dof}, stat={stat:.3g}, p={p:.3g}')
print(f'{batchName} beta_T median={np.median(dfCoeffs["Time"]*100):.3g}, IQR={stats.iqr(dfCoeffs["Time"]*100):.3g} \%mood/min')
print(f'GBE{suffix} beta_T median={np.median(best_pars["beta_T"]*100):.3g}, IQR={stats.iqr(best_pars["beta_T"]*100):.3g} \%mood/min')
# %% Plot histograms of LME slopes from online and mobile app data
# Set up figure
plt.close(632);
plt.figure(632,figsize=(6,4),dpi=180, facecolor='w', edgecolor='k')
plt.clf();
batchName_online = 'AllOpeningRestAndRandom'
if IS_EXPLORE:
batchName_app = 'GbeExplore'
else:
batchName_app = 'GbeConfirm'
#dfPymerFit = pd.read_csv('%s/Mmi-%s_pymerFit-full.csv'%(dataDir,batchName),index_col=0)
dfPymerCoeffs_online = pd.read_csv('%s/Mmi-%s_pymerCoeffs-full.csv'%(dataDir,batchName_online),index_col=0)
dfPymerCoeffs_app = pd.read_csv('%s/Mmi-%s_pymerCoeffs-full.csv'%(dataDir,batchName_app),index_col=0)
# Plot histograms
xHist = np.linspace(-10.0,10.0,100)
nSubj_online = dfPymerCoeffs_online.shape[0]
weights = np.ones(nSubj_online)/nSubj_online*100
plt.hist(dfPymerCoeffs_online['Time']*100.0,xHist,weights=weights,alpha=0.5,label='All online participants (n=%d), LME'%nSubj_online)
nSubj_app = dfPymerCoeffs_app.shape[0]
weights = np.ones(nSubj_app)/nSubj_app*100
if IS_EXPLORE:
plt.hist(dfPymerCoeffs_app['Time']*100.0,xHist,weights=weights,alpha=0.5,label='Exploratory mobile app participants (n=%d), LME'%nSubj_app)
else:
plt.hist(dfPymerCoeffs_app['Time']*100.0,xHist,weights=weights,alpha=0.5,label='Confirmatory mobile app participants (n=%d), LME'%nSubj_app)
# add median lines
online_lme_median = np.percentile(dfPymerCoeffs_online['Time']*100.0, 50)
app_lme_median = np.percentile(dfPymerCoeffs_app['Time']*100.0, 50)
plt.plot([online_lme_median,online_lme_median],[0,7.25],c='tab:blue')
plt.plot([app_lme_median,app_lme_median],[0,7.25],c='tab:orange')
# check significance
stat,p = stats.ranksums(dfPymerCoeffs_online.Time, dfPymerCoeffs_app.Time)
nonline = len(dfPymerCoeffs_online.Time)
napp = len(dfPymerCoeffs_app.Time)
dof = nonline + napp - 2
print(f'Ranksum of LME time coeff for online ({batchName_online}) vs. mobile app ({batchName_app}): nonline={nonline}, napp={napp}, ndof={dof}, stat={stat:.3g}, p={p:.3g}')
# add star
if p<0.05:
plt.plot(np.array([online_lme_median,online_lme_median,app_lme_median,app_lme_median]),np.array([0,.25,.25,0])+7.5,'k-')
plt.plot((online_lme_median + app_lme_median)/2, 8,'k*')
# Annotate plot
plt.grid(True)
plt.xlabel('LME slope parameter (% mood/min)')
plt.ylabel('Percent of participants')
plt.legend()
plt.ylim([0,10])
plt.title('LME mood slope parameter histograms')
# Save figure
#outFile = '%s/Mmi-Vs-Gbe-Slopes'%outFigDirƒ%%
outFile = '%s/LmeSlopeHistograms_OnlineVsApp_%s_2grp'%(outFigDir,batchName_app)
save_figure(outFile)
# print info
lme_dif = online_lme_median - app_lme_median
app_pytorch_median = np.percentile(best_pars.beta_T * 100.0, 50)
lme_app_dif = online_lme_median - app_pytorch_median
print(f'Online LME median slope = {online_lme_median}, app lme median = {app_lme_median}, dif = {lme_dif}')
print(f'Online LME median slope = {online_lme_median}, app pyTorch median = {app_pytorch_median}, dif = {lme_app_dif}')
# %% Get impacts of fracRiskScore from the LME results table
batchName = 'AllOpeningRestAndRandom'
stage = 'full'
inFile = '%s/Mmi-%s_PymerFit-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfFits = pd.read_csv(inFile,index_col=0)
print('Done!')
m = dfFits.loc['fracRiskScore','Estimate']*100
se = dfFits.loc['fracRiskScore','SE']*100
T = dfFits.loc['fracRiskScore','T-stat']
dof = dfFits.loc['fracRiskScore', 'DF']
p = dfFits.loc['fracRiskScore','P-val']
print('Depression Risk Score x intercept in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
m = dfFits.loc['Time:fracRiskScore','Estimate']*100
se = dfFits.loc['Time:fracRiskScore','SE']*100
T = dfFits.loc['Time:fracRiskScore','T-stat']
dof = dfFits.loc['Time:fracRiskScore', 'DF']
p = dfFits.loc['Time:fracRiskScore','P-val']
print('Depression Risk Score x slope in LME: T=%.3g, p=%.3g'%(T,p))
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
# %% Get mean slope in depressed and non-depressed participants
# load pymer fits
batchName = 'AllOpeningRestAndRandom'
stage = 'full'
inFile = '%s/Mmi-%s_PymerCoeffs-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfCoeffs = pd.read_csv(inFile)
# load fracRiskScore from same cohort
inFile = '%s/Mmi-%s_pymerInput-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer input from %s...'%inFile)
dfPymerInput = pd.read_csv(inFile)
print('Done!')
participants = np.unique(dfCoeffs.Subject)
nSubj = len(participants)
fracRiskScore = np.zeros(nSubj)
slope = np.zeros(nSubj)
for i,participant in enumerate(participants):
fracRiskScore[i] = dfPymerInput.loc[dfPymerInput.Subject==participant,'fracRiskScore'].values[0]
slope[i] = dfCoeffs.loc[dfCoeffs.Subject==participant,'Time'].values[0]
#ms
isAtRisk = fracRiskScore>=1
print('Mean +/- ste slope when fracRiskScore>=1: %.3f +/- %.3f \%%mood/min'
%(np.mean(slope[isAtRisk])*100, np.std(slope[isAtRisk]*100)/np.sqrt(np.sum(isAtRisk))))
print('Median slope when fracRiskScore>=1: %.3f \%%mood/min'
%(np.median(slope[isAtRisk])*100))
isNotAtRisk = fracRiskScore<1
print('Mean +/- ste slope when fracRiskScore<1: %.3f +/- %.3f \%%mood/min'
%(np.mean(slope[isNotAtRisk])*100, np.std(slope[isNotAtRisk]*100)/np.sqrt(np.sum(isNotAtRisk))))
# %% Depression risk vs. not
dfRating = pd.read_csv('%s/Mmi-AllOpeningRestAndRandom_pymerInput-full.csv'%(dataDir),index_col=0)
cols = dfRating.columns.tolist()
cols[cols.index('Subject')] = 'participant'
cols[cols.index('Time')] = 'time'
cols[cols.index('Mood')] = 'rating'
dfRating.columns = cols
dfRating['iBlock'] = 0
dfRating['iTrial'] = np.nan
dfRating['time'] = dfRating['time']*60
participants = np.unique(dfRating.participant)
nSubj = len(participants)
lastRatingTime = np.zeros(nSubj)
firstRatingTime = np.zeros(nSubj)
nRatings = 0
for i,participant in enumerate(participants):
firstRatingTime[i] = dfRating.loc[dfRating.participant==participant,'time'].values[0]
lastRatingTime[i] = dfRating.loc[dfRating.participant==participant,'time'].values[nRatings-1]
# isShortSubj = lastRatingTime-firstRatingTime<410
isMediumSubj = lastRatingTime>410
isLongSubj = lastRatingTime-firstRatingTime>600
isMedium = np.isin(dfRating.participant,participants[isMediumSubj])
isLong = np.isin(dfRating.participant,participants[isLongSubj])
isAtRisk = dfRating.fracRiskScore>=1
dfTrialMean = []
# Set up figure
plt.close(511)
fig = plt.figure(511,figsize=(8,3),dpi=180, facecolor='w', edgecolor='k');
plt.clf()
# Plot results
ax1 = plt.subplot(131)
dfRatingMean0 = pmd.GetMeanRatings(dfRating.loc[~isAtRisk,:],nRatings=-1,participantLabel='Not at risk',doInterpolation=True)
dfRatingMean1 = pmd.GetMeanRatings(dfRating.loc[isAtRisk,:],nRatings=-1,participantLabel='At risk of depression',doInterpolation=True)
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean0,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean0.participant[0])
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean1,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean1.participant[0])
# Annotate plot
meanInitialMood = np.mean([dfRatingMean0['rating'].values[0], dfRatingMean1['rating'].values[0]])
plt.axhline(meanInitialMood,c='k',ls='--',zorder=-6)#,label='mean initial mood')
# plt.axhline(0.5,c='k',ls='--',zorder=-6)#,label='neutral mood')
#plt.legend(loc='upper right')
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.65))
plt.grid(True)
titleStr = 'Short runs \n (duration > 294 s)'
plt.title(titleStr)
# Plot results
plt.subplot(132,sharey=ax1)
dfRatingMean0 = pmd.GetMeanRatings(dfRating.loc[~isAtRisk & isMedium,:],nRatings=-1,participantLabel='Not at risk',doInterpolation=True)
dfRatingMean1 = pmd.GetMeanRatings(dfRating.loc[isAtRisk & isMedium,:],nRatings=-1,participantLabel='At risk of depression',doInterpolation=True)
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean0,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean0.participant[0])
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean1,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean1.participant[0])
# Annotate plot
meanInitialMood = np.mean([dfRatingMean0['rating'].values[0], dfRatingMean1['rating'].values[0]])
plt.axhline(meanInitialMood,c='k',ls='--',zorder=-6)#,label='mean initial mood')
# plt.axhline(0.5,c='k',ls='--',zorder=-6)#,label='neutral mood')
#plt.legend(loc='upper right')
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.65))
plt.grid(True)
titleStr = 'Medium runs \n (duration > 410 s)'
plt.title(titleStr)
# Plot results
plt.subplot(133,sharey=ax1)
dfRatingMean0 = pmd.GetMeanRatings(dfRating.loc[~isAtRisk & isLong,:],nRatings=-1,participantLabel='Not at risk',doInterpolation=True)
dfRatingMean1 = pmd.GetMeanRatings(dfRating.loc[isAtRisk & isLong,:],nRatings=-1,participantLabel='At risk of depression',doInterpolation=True)
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean0,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean0.participant[0])
pmd.PlotMmiRatings(dfTrialMean,dfRatingMean1,'line',autoYlim=True, doBlockLines=False, ratingLabel=dfRatingMean1.participant[0])
# Annotate plot
meanInitialMood = np.mean([dfRatingMean0['rating'].values[0], dfRatingMean1['rating'].values[0]])
plt.axhline(meanInitialMood,c='k',ls='--',zorder=-6)#,label='mean initial mood')
# plt.axhline(0.5,c='k',ls='--',zorder=-6)#,label='neutral mood')
#plt.legend(loc='upper right')
plt.legend(loc="lower center", bbox_to_anchor=(0.5, -0.65))
plt.grid(True)
titleStr = 'Long runs \n (duration > 600 s)'
plt.title(titleStr)
plt.ylim([0.3,0.8])
# Annotate figure
plt.tight_layout(rect=[0,0,1,0.93])
fig.subplots_adjust(bottom=0.25)
plt.suptitle('Depression risk affects mean mood ratings over time')
# Save figure
outFig = '%s/Mmi_%s_Comparison'%(outFigDir,'-'.join(['NotAtRisk','AtRisk']))
save_figure(outFig, bbox_inches="tight")
#%%
if have_gbe:
# %% Plot beta_T against life happiness score
sns.set(font_scale=0.8)
sns.set_style("whitegrid")
alpha = 0.2
nGrps = 2
paramToPlot = 'beta_T'
param = 'beta_A'
for stage in ['full','late']:
print('=== STAGE %s ==='%stage)
# Load pytorch results
if IS_EXPLORE:
suffix = '_GbeExplore'
else:
suffix = '_GbeConfirm'
if stage=='late':
suffix = suffix + '-late'
inFile = '%s/PyTorchParameters%s.csv'%(pytorchDir,suffix)
print('Loading best parameters from %s...'%inFile)
best_pars = pd.read_csv(inFile);
if IS_EXPLORE:
summaryFile = '%s/Mmi-GbeExplore_Summary.csv'%(dataDir)
else:
summaryFile = '%s/Mmi-GbeConfirm_Summary.csv'%(dataDir)
print('Loading summary from %s..'%summaryFile)
dfSummary = pd.read_csv(summaryFile,index_col=0)
dfSummary['beta_T'] = best_pars['beta_T'].values
best_pars['lifeHappy'] = dfSummary['lifeHappy'].values
plt.close(621)
plt.figure(621,figsize=(7,4),dpi=120)
plt.clf()
plt.subplot(1,2,1)
rs,ps = stats.spearmanr(best_pars[param],best_pars[paramToPlot])
print('%s vs. %s: r_s = %.3g, p_s = %.3g'%(param,paramToPlot,rs,ps))
print('Plotting %s vs. %s with best fit line...'%(param,paramToPlot))
sns.regplot(x=param, y=paramToPlot, data=best_pars,scatter_kws={'alpha':alpha});
plt.xlabel(paramLabelDict[param])
plt.ylabel(paramLabelDict[paramToPlot])
plt.title('%s vs. %s:\n'%(paramLabelDict[param],paramLabelDict[paramToPlot]) +
r'$r_s = %.3g, p_s = %.3g$'%(rs,ps))
plt.subplot(1,2,2)
topCutoff = np.median(best_pars.lifeHappy)
botCutoff = np.median(best_pars.lifeHappy)
if nGrps==2:
isTop = best_pars.lifeHappy>=topCutoff
isBot = best_pars.lifeHappy<botCutoff
elif nGrps==4:
topCutoff = 0.8
botCutoff = 0.6
elif nGrps==11:
topCutoff = 0.9
botCuotff = 0.1
nTop = np.sum(isTop)
nBot = np.sum(isBot)
# Run spearman corr's
rs_top,ps_top = stats.spearmanr(best_pars.loc[isTop,param],best_pars.loc[isTop,paramToPlot])
print('%s vs. %s (lifeHappy>=%g): r_s = %.3g, p_s = %.3g'%(param,paramToPlot,topCutoff,rs_top,ps_top))
rs_bot,ps_bot = stats.spearmanr(best_pars.loc[isBot,param],best_pars.loc[isBot,paramToPlot])
print('%s vs. %s (lifeHappy<%g): r_s = %.3g, p_s = %.3g'%(param,paramToPlot,botCutoff,rs_bot,ps_bot))
# Is the diff between the two significant?
zs_top = np.arctanh(rs_top)
zs_bot = np.arctanh(rs_bot)
se_diff_r = np.sqrt(1.0/(nTop - 3) + 1.0/(nBot - 3))
diff = zs_top - zs_bot
z = abs(diff / se_diff_r)
p = (1 - stats.norm.cdf(z))
# if twotailed:
# p *= 2
print('correlation difference between top & bottom: z=%.3g, p=%.3g'%(z,p))
print('Plotting %d-group %s vs. %s with best fit lines...'%(nGrps,param,paramToPlot))
if param=='lifeHappy':
plt.xlim([-0.06,1.06])
topLabel = 'Life happiness >= %g (n = %d)\n'%(topCutoff,nTop) + r'$r_s=%.3g, p_s=%.3g$'%(rs_top,ps_top)
botLabel = 'Life happiness < %g (n = %d)\n'%(botCutoff,nBot) + r'$r_s=%.3g, p_s=%.3g$'%(rs_bot,ps_bot)
g1 = sns.regplot(x=param, y=paramToPlot, data=best_pars.loc[isTop,:], line_kws={'color':'tab:blue','label':topLabel},scatter_kws={'color':'tab:blue','alpha':alpha});
g2 = sns.regplot(x=param, y=paramToPlot, data=best_pars.loc[isBot,:], line_kws={'color':'tab:orange','label':botLabel},scatter_kws={'color':'tab:orange','alpha':alpha});
plt.xlabel(paramLabelDict[param])
plt.ylabel(paramLabelDict[paramToPlot])
plt.title('%s vs. %s: group correlation difference\n'%(paramLabelDict[param],paramLabelDict[paramToPlot]) +
r'$z = %.3g, p = %.3g$'%(z,p))
plt.legend()
# plot b_T against life happiness
# rs,ps = stats.spearmanr(dfSummary['lifeHappy'],dfSummary['beta_T'])
# print('lifeHappy vs. beta_T: r_s = %.3g, p_s = %.3g'%(rs,ps))
#
# print('Plotting lifeHappy vs. beta_T with best fit line...')
# plt.subplot(1,3,1)
# sns.regplot(x='lifeHappy', y='beta_T', data=dfSummary);
# # Annotate plot
# plt.xlabel('Life happiness rating (0-1)')
# plt.ylabel(r'$\beta_T$')
# plt.title(r'Life happiness vs. $\beta_T$:' + '\n' + r'$r_s = %.3g, p_s = %.3g$'%(rs,ps))
plt.tight_layout()
outFig = '%s/PyTorch_betaT-vs-BetaA%s'%(outFigDir,suffix)
save_figure(outFig)
# %% Plot each parameters vs. betaT
sns.set(font_scale=0.8)
sns.set_style("whitegrid")
alpha = 0.2
paramToPlot = 'beta_T'
colsToPlot = ['m0','lambda','beta_E','beta_A','SSE','lifeHappy']
for stage in ['full','late']:
print('=== STAGE %s ==='%stage)
# Load pytorch results
if IS_EXPLORE:
suffix = '_GbeExplore'
else:
suffix = '_GbeConfirm'
if stage=='late':
suffix = suffix + '-late'
inFile = '%s/PyTorchParameters%s.csv'%(pytorchDir,suffix)
print('Loading best parameters from %s...'%inFile)
best_pars = pd.read_csv(inFile);
if IS_EXPLORE:
summaryFile = '%s/Mmi-GbeExplore_Summary.csv'%(dataDir)
else:
summaryFile = '%s/Mmi-GbeConfirm_Summary.csv'%(dataDir)
print('Loading summary from %s..'%summaryFile)
dfSummary = pd.read_csv(summaryFile,index_col=0)
dfSummary['beta_T'] = best_pars['beta_T'].values
best_pars['lifeHappy'] = dfSummary['lifeHappy'].values
for nGrps in [1,2]:
plt.close(621)
plt.figure(621,figsize=(13,8),dpi=120)
plt.clf()
for i,param in enumerate(colsToPlot):
plt.subplot(2,3,i+1)
if nGrps==1:
rs,ps = stats.spearmanr(best_pars[param],best_pars[paramToPlot])
print('lifeHappy vs. beta_T: r_s = %.3g, p_s = %.3g'%(rs,ps))
print('Plotting %s vs. %s with best fit line...'%(param,paramToPlot))
rs,ps = stats.spearmanr(best_pars[param],best_pars[paramToPlot])
print('%s vs. %s: r_s = %.3g, p_s = %.3g'%(param,paramToPlot,rs,ps))
print('Plotting %s vs. %s with best fit line...'%(param,paramToPlot))
sns.regplot(x=param, y=paramToPlot, data=best_pars,scatter_kws={'alpha':alpha});
plt.xlabel(paramLabelDict[param])
plt.ylabel(paramLabelDict[paramToPlot])
plt.title('%s vs. %s:\n'%(paramLabelDict[param],paramLabelDict[paramToPlot]) +
r'$r_s = %.3g, p_s = %.3g$'%(rs,ps))
elif nGrps==2:
topCutoff = np.median(best_pars.lifeHappy)
botCutoff = np.median(best_pars.lifeHappy)
if nGrps==2:
isTop = best_pars.lifeHappy>=topCutoff
isBot = best_pars.lifeHappy<botCutoff
elif nGrps==4:
topCutoff = 0.8
botCutoff = 0.6
elif nGrps==11:
topCutoff = 0.9
botCuotff = 0.1
nTop = np.sum(isTop)
nBot = np.sum(isBot)
# Run spearman corr's
rs_top,ps_top = stats.spearmanr(best_pars.loc[isTop,param],best_pars.loc[isTop,paramToPlot])
print('%s vs. %s (lifeHappy>=%g): r_s = %.3g, p_s = %.3g'%(param,paramToPlot,topCutoff,rs_top,ps_top))
rs_bot,ps_bot = stats.spearmanr(best_pars.loc[isBot,param],best_pars.loc[isBot,paramToPlot])
print('%s vs. %s (lifeHappy<%g): r_s = %.3g, p_s = %.3g'%(param,paramToPlot,botCutoff,rs_bot,ps_bot))
# Is the diff between the two significant?
zs_top = np.arctanh(rs_top)
zs_bot = np.arctanh(rs_bot)
se_diff_r = np.sqrt(1.0/(nTop - 3) + 1.0/(nBot - 3))
diff = zs_top - zs_bot
z = abs(diff / se_diff_r)
p = (1 - stats.norm.cdf(z))
# if twotailed:
# p *= 2
print('correlation difference between top & bottom: z=%.3g, p=%.3g'%(z,p))
print('Plotting %d-group %s vs. %s with best fit lines...'%(nGrps,param,paramToPlot))
if param=='lifeHappy':
plt.xlim([-0.06,1.06])
topLabel = 'Life happiness >= %g (n = %d)\n'%(topCutoff,nTop) + r'$r_s=%.3g, p_s=%.3g$'%(rs_top,ps_top)
botLabel = 'Life happiness < %g (n = %d)\n'%(botCutoff,nBot) + r'$r_s=%.3g, p_s=%.3g$'%(rs_bot,ps_bot)
g1 = sns.regplot(x=param, y=paramToPlot, data=best_pars.loc[isTop,:], line_kws={'color':'tab:blue','label':topLabel},scatter_kws={'color':'tab:blue','alpha':alpha});
g2 = sns.regplot(x=param, y=paramToPlot, data=best_pars.loc[isBot,:], line_kws={'color':'tab:orange','label':botLabel},scatter_kws={'color':'tab:orange','alpha':alpha});
plt.xlabel(paramLabelDict[param])
plt.ylabel(paramLabelDict[paramToPlot])
plt.title('%s vs. %s: group corr. diff.\n'%(paramLabelDict[param],paramLabelDict[paramToPlot]) +
r'$z = %.3g, p = %.3g$'%(z,p))
plt.legend()
plt.tight_layout()
plt.tight_layout()
outFig = '%s/PyTorch_betaT-vs-others%s-%dGrps'%(outFigDir,suffix,nGrps)
save_figure(outFig)
# %% Get impacts of fracRiskScore from the LME results table
batchName = 'AllOpeningRestAndRandom'
stage = 'full'
inFile = '%s/Mmi-%s_PymerFit-%s.csv'%(dataDir,batchName,stage)
print('Loading pymer fits from %s...'%inFile)
dfFits = pd.read_csv(inFile,index_col=0)
print('Done!')
m = dfFits.loc['isAge16to18TRUE','Estimate']*100
se = dfFits.loc['isAge16to18TRUE','SE']*100
T = dfFits.loc['isAge16to18TRUE','T-stat']
dof = dfFits.loc['isAge16to18TRUE','DF']
p = dfFits.loc['isAge16to18TRUE','P-val']
print('Age 16-18 x intercept in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
m = dfFits.loc['Time:isAge16to18TRUE','Estimate']*100
se = dfFits.loc['Time:isAge16to18TRUE','SE']*100
T = dfFits.loc['Time:isAge16to18TRUE','T-stat']
dof = dfFits.loc['Time:isAge16to18TRUE','DF']
p = dfFits.loc['Time:isAge16to18TRUE','P-val']
print('Age 16-18 x slope in LME:')
print('%.3g +/- %.3g %% mood, T=%.3g, dof=%0.3g, p=%.3g'%(m,se,T,dof,p))
# %% Link to age in adolescents
PlotAgeVsCoeffs('AllOpeningRestAndRandom')
# %% Get Stability plots
# Set up
plt.close(923)
plt.figure(923,figsize=(9,6),dpi=120); plt.clf()
intOrSlopes = ['Intercept','Slope']
cohortPairs = [['Stability01-Rest','Stability01-Rest_block2'],
['Stability01-Rest','Stability02-Rest'],
['COVID01','COVID03']]
pairTitles = ['Blocks','Days','Weeks']
# Calculate and plot ICCs
icc21 = {'Intercept':0,'Slope':0}
p21 = {'Intercept':0,'Slope':0}
for i,pair in enumerate(cohortPairs):
icc21['Intercept'],p21['Intercept'],icc21['Slope'],p21['Slope'] = gmi.GetMmiIcc(pair[0],pair[1],doPlot='None')
for j,intOrSlope in enumerate(intOrSlopes):
ax = plt.subplot(2,3,j*3+i+1);
gmi.PlotReliability(pair[0],pair[1],intOrSlope=intOrSlope)
if j==0:
plt.title('%s\nICC(2,1)=%.3g, p=%.3g'%(pairTitles[i],icc21[intOrSlope],p21[intOrSlope]))
else:
plt.title('ICC(2,1)=%.3g, p=%.3g'%(icc21[intOrSlope],p21[intOrSlope]))
# Save figure
plt.tight_layout()
outFile = '%s/Mmi_%s_Reliability'%(outFigDir,'-'.join(pairTitles))
save_figure(outFile)
# %% Check for time of day effects
PlotTimeOfDayVsSlopeAndIntercept('AllOpeningRestAndRandom')
# %% Impact of mood on gambling
def CompareGamblingBehavior(dataDir,outFigDir,batchNames,groupName,batchLabels,iGambleBlock,nGamble=4):
minNRatings=8 # -1 indicates all, but they must be the same
minNTrials=10 # -1 indicates all, but they must be the same
xlim=[0,90]
bar_ylim=[0.6,0.9]
hist_ybins = np.arange(nGamble+2)/nGamble - 0.5/nGamble
nChoseGamble = [0]* len(batchNames)
participants = [0]* len(batchNames)
#plt.rcParams.update({'font.size': 6})
plt.close(412)
plt.figure(412,figsize=(6,7.5),dpi=180, facecolor='w', edgecolor='k');
plt.clf();
fig, ax = plt.subplots(3,1,num=412)
meanGamble = np.zeros(len(batchNames))
steGamble = np.zeros(len(batchNames))
ratingLabels = list(batchLabels)
# initialize for 2d histos
xdata = np.zeros(0)
ydata = np.zeros(0)
weights = np.zeros(0)
# initialize lists of mood ratings
firstRatings = [0]*len(batchNames)
secondRatings = [0]*len(batchNames)
# Get gambling behavior for each
for iBatch, batchName in enumerate(batchNames):
dfRating = pd.read_csv('%s/Mmi-%s_Ratings.csv'%(dataDir,batchName))
dfTrial = pd.read_csv('%s/Mmi-%s_Trial.csv'%(dataDir,batchName))
# Limit to block
iBlock = iGambleBlock[iBatch]
if iBlock!='all':
dfRating = dfRating.loc[dfRating.iBlock==iBlock,:]
dfTrial = dfTrial.loc[dfTrial.iBlock==iBlock,:]
# Get averages