forked from gretatuckute/drive_suppress_brains
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_utils.py
More file actions
2526 lines (2175 loc) · 109 KB
/
plot_utils.py
File metadata and controls
2526 lines (2175 loc) · 109 KB
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
import pandas as pd
import numpy as np
import os
from os.path import join
import matplotlib.pyplot as plt
import typing
from textwrap import wrap
from scipy.stats import pearsonr
import seaborn as sns
import matplotlib
# Import resources from the folder up one level
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from resources import *
# Set random seed for plot jitters and noise simulation
np.random.seed(0)
def groupby_coord(df: pd.DataFrame,
coord_col: str = 'item_id',
aggfunc: str = 'mean',
) -> pd.DataFrame:
"""
Group a pandas dataframe by the coordinates specified in coord_cols.
Most common use case: group by item_id (across several UIDs).
This function by default groups the numeric columns according to the aggfunc (mean by default).
For the string columns, the first value is kept. Importantly, we check whether all string columns are the same for
each item_id (or other coordinate). Then, we only keep the coords that are shared across all item_ids
(such that we avoid the scenario where we think we can use a string column as a coordinate, but in reality it was
different for each occurence of that item_id).
Args:
df (pd.DataFrame): dataframe to group
coord_col (str): column to group by (currently only supports one coord col)
aggfunc: aggregation function for numeric columns. If std/sem, always use n-1 for ddof
Returns:
df_grouped (pd.DataFrame): grouped dataframe
"""
df_to_return = df.copy(deep=True)
# Create df that is grouped by col coord using aggfunc
# Keep string columns as is (first)
if aggfunc == 'mean':
df_grouped = df_to_return.groupby(coord_col).agg(
lambda x: x.mean() if np.issubdtype(x.dtype, np.number) else x.iloc[0])
elif aggfunc == 'median':
df_grouped = df_to_return.groupby(coord_col).agg(
lambda x: x.median() if np.issubdtype(x.dtype, np.number) else x.iloc[0])
elif aggfunc == 'std':
df_grouped = df_to_return.groupby(coord_col).agg(
lambda x: x.std(ddof=1) if np.issubdtype(x.dtype, np.number) else x.iloc[0])
elif aggfunc == 'sem':
df_grouped = df_to_return.groupby(coord_col).agg(
lambda x: x.sem(ddof=1) if np.issubdtype(x.dtype, np.number) else x.iloc[0])
else:
raise ValueError(f'aggfunc {aggfunc} not supported')
# Check whether the string arguments were all the same (to ensure correct grouping and metadata for str cols) ###
shared_str_cols = []
not_shared_str_cols = []
for coord_val in df_grouped.index:
# Get the values of the coordinate of interest in df_to_return
df_test = df_to_return.loc[df_to_return[coord_col] == coord_val, :]
df_test_object = df_test.loc[:, df_test.dtypes == object] # Get the string cols
# If not nan, check that each col has unique values
if not df_test_object.isna().all().all():
for col in df_test_object.columns:
if len(df_test_object[col].unique()) > 1:
# print(f'Column {col} has multiple values for item_id {item_id}: {df_test_object[col].unique()}')
not_shared_str_cols.append(col)
else:
# print(f'Column {col} for item_id {coord_col} have the same value, i.e. we can retain the metadata when grouping by item_id')
shared_str_cols.append(col)
# Check that all shared_str_cols are the same for all item_ids
shared_str_cols_unique = np.unique(shared_str_cols)
not_shared_str_cols_unique = np.unique(not_shared_str_cols)
# Drop the not_shared_str_cols from df_item_id
df_grouped_final = df_grouped.drop(columns=not_shared_str_cols_unique)
return df_grouped_final
def get_roi_list_name(rois_of_interest: str):
"""
If roi exists in d_roi_lists_names, use the name in the dictionary otherwise use the string itself.
E.g. if we pass rois_of_interest = 'lang_LH_ROIs', we get back the list of ROIs in the language network.
We do retain the 'lang_LH_ROIs' as the name (for use in save string, etc.)
:param rois_of_interest:
:param d_roi_lists_names:
:return:
"""
rois_of_interest_name = rois_of_interest
if rois_of_interest in d_roi_lists_names.keys():
rois_of_interest = d_roi_lists_names[rois_of_interest]
else:
rois_of_interest = None # I.e. just use the string as the name, and pass a None such that we use all ROIs
return rois_of_interest, rois_of_interest_name
def cond_barplot(df: pd.DataFrame,
target_UIDs: typing.Union[list, np.ndarray],
rois_of_interest: str,
x_val: str = 'cond',
y_val: str = 'response_target',
ylim: typing.Union[list, None] = None,
yerr_type: str = 'std_over_UIDs',
individual_data_points: typing.Union[str, None] = None,
save: bool = False,
base_savestr: str = '',
add_savestr: str = '',
PLOTDIR: typing.Union[str, None] = None,
CSVDIR: typing.Union[str, None] = None,
):
"""
Plot barplots
Args
df (pd.DataFrame): Dataframe with rows = items (responses for individual participants) and cols with neural data and condition info.
target_UIDs (list): List of target UIDs to include in the plot
rois_of_interest: str, which ROIs to plot (uses the dictionary d_roi_lists_names)
x_val (str): Which column to use for x-axis
y_val (str): Which column to use for y-axis
ylim (list): List of two values, lower and upper limit for y-axis
yerr_type (str): Type of error bars to use. Options:
'std_over_items', 'sem_over_items',
'std_over_UIDs', 'sem_over_UIDs'
'std_within_UIDs', 'sem_within_UIDs'
individual_data_points (str): Whether to plot individual data points. Options: 'participant', 'item', None
save (bool): Whether to save the plot
base_savestr (str): Base savestr to use
add_savestr (str): Additional savestr to add to base savestr
PLTDIR (str): Directory to save plots to
CSVDIR (str): Directory to save csvs to
"""
# Define savestr
target_UIDs_str = '-'.join(target_UIDs)
# Filter data
df = df.copy(deep=True)[df['target_UID'].isin([int(x) for x in target_UIDs])]
rois_of_interest, rois_of_interest_name = get_roi_list_name(rois_of_interest=rois_of_interest)
ylim_str = '-'.join([str(x) for x in ylim]) if ylim is not None else 'None'
for roi in rois_of_interest:
savestr = f'cond-barplot_' \
f'X={x_val}_Y={y_val}_' \
f'y={ylim_str}_' \
f'YERR={yerr_type}_points={individual_data_points}_' \
f'{target_UIDs_str}_{roi}_' \
f'{base_savestr}{add_savestr}'
df_roi = df.copy(deep=True).query(f'roi == "{roi}"')
# Add error bars
if yerr_type == 'std_over_items':
yerr = df_roi.groupby(df_roi[x_val]).std(ddof=1)[y_val]
elif yerr_type == 'sem_over_items':
yerr = df_roi.groupby(df_roi[x_val]).sem(ddof=1)[y_val]
elif yerr_type == 'std_over_UIDs':
df_temp = df_roi.groupby([x_val, 'target_UID']).mean()
# Get std over participants for each cond (which is the multiindex)
yerr = df_temp.groupby(df_temp.index.get_level_values(0)).std(ddof=1)[y_val]
elif yerr_type == 'sem_over_UIDs':
df_temp = df_roi.groupby([x_val, 'target_UID']).mean()
# Get sem over participants for each cond (which is the multiindex)
yerr = df_temp.groupby(df_temp.index.get_level_values(0)).sem(ddof=1)[y_val]
elif yerr_type.endswith('within_UIDs'):
df_temp = df_roi.groupby([x_val, 'target_UID']).mean()
# Create [subject; cond] pivot table
df_piv = df_temp.pivot_table(index='target_UID', columns=x_val, values=y_val)
# Subtract the mean across conditions for each subject
df_demeaned = df_piv.sub(df_piv.mean(axis=1),
axis=0) # get a mean value for each subject across all conds, and subtract it from individual conds
# Take std or sem over subjects
if yerr_type == 'std_within_UIDs':
yerr = df_demeaned.std(axis=0, ddof=1)
elif yerr_type == 'sem_within_UIDs':
yerr = df_demeaned.sem(axis=0, ddof=1)
else:
raise ValueError('yerr_type not recognized')
print(f'\n\nPlotting: {savestr}\n'
f'Total number of data points across {len(df_roi.target_UID.unique())} participants: {len(df_roi)}')
df_cond = df_roi.groupby(df_roi[x_val]).mean()
# Reindex such that D, S, B
df_cond = df_cond.reindex(['D', 'S', 'B'])
yerr = yerr.reindex(['D', 'S', 'B'])
assert (yerr.index == df_cond.index).all()
# Plot min/max values in d_cond (take into account +- yerr)
print(f'Min value: {df_cond[y_val].min() - yerr.max():.2f}')
print(f'Max value: {df_cond[y_val].max() + yerr.max():.2f}')
# Plot with condition colors
color_order = [d_colors[x] for x in df_cond.index.values]
plt.figure(figsize=(5, 8))
plt.bar(df_cond.index,
df_cond[y_val],
yerr=yerr,
color=color_order,
zorder=0,
error_kw=dict(lw=2))
if individual_data_points is not None:
if individual_data_points == 'item':
jitter = 0.1
for i, cond in enumerate(df_cond.index):
plt.scatter(
np.random.uniform(i - jitter, i + jitter, len(df_roi.loc[df_roi[x_val] == cond, :].target_UID)),
df_roi.loc[df_roi[x_val] == cond, :][y_val],
s=40,
color='black', # color_order[i],
zorder=10,
edgecolors='none',
alpha=0.3)
elif individual_data_points == 'UID':
jitter = 0.05
for i, cond in enumerate(df_cond.index):
plt.scatter(np.random.uniform(i - jitter, i + jitter,
len(df_roi.loc[df_roi[x_val] == cond, :].target_UID.unique())),
df_roi.groupby([x_val, 'target_UID']).mean().loc[
df_roi.groupby([x_val, 'target_UID']).mean().index.get_level_values(0) == cond, :][
y_val],
s=90,
color='black', # color_order[i]
edgecolors='none',
zorder=10,
alpha=0.4)
# Make ticks and axis labels bigger
plt.xticks(fontsize=14)
plt.yticks(fontsize=18)
plt.xlabel(d_axes_legend[x_val], fontsize=20)
plt.ylabel(f'{d_axes_legend[y_val]} (mean ± {d_axes_legend[yerr_type]})', fontsize=18)
plt.title("\n".join(wrap(savestr, 33)), fontsize=14)
if ylim is not None:
plt.ylim(ylim)
plt.tight_layout()
if save:
savestr = shorten_savestr(savestr=savestr)
# Save plot
os.chdir(PLOTDIR) # Avoid too long path names
plt.savefig(savestr + '.pdf', dpi=180)
# Save data
df_cond[f'yerr_{yerr_type}'] = yerr # Add in the yerr values to df_cond
os.chdir(CSVDIR)
df_cond.to_csv(join(CSVDIR, savestr + '.csv'))
plt.show()
def condlevel_perc_inc(df: pd.DataFrame,
target_UIDs: typing.Union[list, np.ndarray],
response_target_col: str = 'response_target_non_norm',
rois_of_interest: str = 'lang_LH_netw',
perc_inc_from_cond: str = 'B',
compare_to_conds: typing.Union[list, np.ndarray] = ['D', 'S'],
save: bool = False,
base_savestr: str = '',
add_savestr: str = '',
CSVDIR: str = '',):
"""
Quantify the percent increase based on condition averages.
Performs this computation on the data that is averaged across target_UIDs (doesn't matter if we go straight from
trial-level or from averaged across participants trial-level data to compute the condition averages).
Args
df (pd.DataFrame): Dataframe with rows as items and column with response_target
target_UIDs (list): List of target_UIDs to include in the analysis
response_target_col (str): Column with the response target
rois_of_interest (str): ROI to include in the analysis
perc_inc_from_cond (str): Condition to compute the percent increase from
compare_to_conds (list): List of conditions to compare to
save (bool): Whether to save the plot
base_savestr (str): Base savestr to add to the plot
add_savestr (str): Additional savestr to add to the plot
CSVDIR (str): Directory to save the csv
Returns
df_cond with the percent increase computed across condition means
"""
# Define savestr
target_UIDs_str = '-'.join(target_UIDs)
# Filter data
df_target = df.copy(deep=True)[df['target_UID'].isin([int(x) for x in target_UIDs])]
rois_of_interest, rois_of_interest_name = get_roi_list_name(rois_of_interest=rois_of_interest)
for roi in rois_of_interest:
savestr = f'condlevel-perc-inc_' \
f'from-cond={perc_inc_from_cond}_' \
f'{target_UIDs_str}_{response_target_col}_{roi}_' \
f'{base_savestr}{add_savestr}'
df_roi = df_target.copy(deep=True).query(f'roi == "{roi}"')
print(f'\n\nPlotting: {savestr}\n'
f'Total number of data points across {len(df_roi.target_UID.unique())} participants: {len(df_roi)}')
# Create df that is grouped by item id. Keep string columns as is (we can perform the groupby cond directly too -- does not matter
# as long as we have the same number of items per participant)
df_item_id = groupby_coord(df=df_roi, coord_col='item_id', aggfunc='mean',)
# Get mean of the conditions
df_cond = df_item_id.groupby('cond').mean()
df_cond_from = df_cond.loc[df_cond.index == perc_inc_from_cond]
# Get perc increase from perc_inc_from_cond condition
# Compute percent increase from mean of perc_inc_from_cond condition to the mean of the other conditions (compare_to_conds)
for compare_to_cond in compare_to_conds:
df_cond_to = df_cond.loc[df_cond.index == compare_to_cond]
inc = (df_cond_to[response_target_col].values - df_cond_from[response_target_col].values) / df_cond_from[response_target_col].values * 100
print(f'Percent increase from {perc_inc_from_cond} to {compare_to_cond}: {inc[0]:.3f}%')
# Add to df_cond
df_cond.loc[compare_to_cond, f'perc_inc_from_{perc_inc_from_cond}'] = inc[0]
if save:
savestr = shorten_savestr(savestr=savestr)
# Store df_cond as csv
os.chdir(CSVDIR)
df_cond.to_csv(f'{savestr}.csv')
return df_cond
def condlevel_perc_inc_blocked(df: pd.DataFrame,
target_UIDs: typing.Union[list, np.ndarray],
response_target_col: str = 'response_target_non_norm',
rois_of_interest: str = 'lang_LH_netw',
perc_inc_from_cond: str = 'B',
compare_to_conds: typing.Union[list, np.ndarray]=['D', 'S'],
save: bool = False,
base_savestr: str = '',
add_savestr: str = '',
CSVDIR: str = '',):
"""
Quantify the percent increase based on condition averages. Same as condlevel_perc_inc but for blocked data.
(no item_ids, and neural data is called response and not response_target)
Args
df (pd.DataFrame): Dataframe with rows as items and column with response
target_UIDs (list): List of target_UIDs to include in the analysis (of str numbers)
response_target_col (str): Column with the response target
rois_of_interest (str): ROI to include in the analysis
perc_inc_from_cond (str): Condition to compute the percent increase from
compare_to_conds (list): List of conditions to compare to
save (bool): Whether to save the plot
base_savestr (str): Base savestr to add to the plot
add_savestr (str): Additional savestr to add to the plot
CSVDIR (str): Directory to save the csv
Returns
df_cond with the percent increase computed across condition means
"""
# Define savestr
target_UIDs_str = '-'.join(target_UIDs)
# Filter data
df_target = df.copy(deep=True)[df['target_UID'].isin([int(x) for x in target_UIDs])]
rois_of_interest, rois_of_interest_name = get_roi_list_name(rois_of_interest=rois_of_interest)
for roi in rois_of_interest:
savestr = f'condlevel-perc-inc-blocked_' \
f'from-cond={perc_inc_from_cond}_' \
f'{target_UIDs_str}_{response_target_col}_{roi}_' \
f'{base_savestr}{add_savestr}'
df_roi = df_target.copy(deep=True).query(f'roi == "{roi}"')
print(f'\n\nPlotting: {savestr}\n'
f'Total number of data points across {len(df_roi.target_UID.unique())} participants: {len(df_roi)}')
# Get mean of the conditions
df_cond = df_roi.groupby('cond').mean()
df_cond_from = df_cond.loc[df_cond.index == perc_inc_from_cond]
# Get perc increase from perc_inc_from_cond condition
# Compute percent increase from mean of perc_inc_from_cond condition to the mean of the other conditions (compare_to_conds)
for compare_to_cond in compare_to_conds:
df_cond_to = df_cond.loc[df_cond.index == compare_to_cond]
inc = (df_cond_to[response_target_col].values - df_cond_from[response_target_col].values) / df_cond_from[response_target_col].values * 100
print(f'Percent increase from {perc_inc_from_cond} to {compare_to_cond}: {inc[0]:.3f}%')
# Add to df_cond
df_cond.loc[compare_to_cond, f'perc_inc_from_{perc_inc_from_cond}'] = inc[0]
if save:
savestr = shorten_savestr(savestr=savestr)
# Store df_cond as csv
os.chdir(CSVDIR)
df_cond.to_csv(f'{savestr}.csv')
return df_cond
def item_scatter(df: pd.DataFrame,
target_UIDs: typing.Union[list, np.ndarray],
rois_of_interest: str,
x_val: str = f'encoding_model_pred',
y_val: str = 'response_target',
yerr_type: typing.Union[str, None] = 'sem_over_UIDs',
add_mean: bool = False,
xlim: typing.Union[list, np.ndarray, None] = None,
ylim: typing.Union[list, np.ndarray, None] = None,
plot_aspect: float = 1,
add_identity: bool = True,
save: bool = False,
base_savestr: str = '',
add_savestr: str = '',
PLOTDIR: typing.Union[str, None] = None,
CSVDIR: typing.Union[str, None] = None,
):
"""
Plot scatter per item.
Args
df (pd.DataFrame): Dataframe with rows = items (responses for individual participants) and cols with neural data and condition info.
target_UIDs (list): List of target UIDs to include in the plot
rois_of_interest: str, which ROIs to plot (uses the dictionary d_roi_lists_names)
x_val (str): Which column to use for the x-axis (Predicted response intended:
'encoding_model_pred')
y_val (str): Which column to use for the y-axis (Actual response intended)
yerr_type (bool): which y error to compute, options are:
'sem_over_UIDs': compute sem (ddof=1) across participants for a given item
add_mean (bool): whether to add a mean line to the plot of the conditions
xlim (list): x-axis limits
ylim (list): y-axis limits
plot_aspect (float): aspect ratio of the plot
add_identity (bool): whether to add an identity line to the plot, x=y
base_savestr (str): Base string to use for saving the plot
add_savestr (str): Additional string to use for saving the plot
save (bool): Whether to save the plot)"""
# Define savestr
target_UIDs_str = '-'.join(target_UIDs)
# Filter data
df = df.copy(deep=True)[df['target_UID'].isin([int(x) for x in target_UIDs])]
rois_of_interest, rois_of_interest_name = get_roi_list_name(rois_of_interest=rois_of_interest)
for roi in rois_of_interest:
# If xlim and ylim are not None, join them into a string
if xlim is not None:
xlim_str = f'{xlim[0]}-{xlim[1]}'
else:
xlim_str = 'None'
if ylim is not None:
ylim_str = f'{ylim[0]}-{ylim[1]}'
else:
ylim_str = 'None'
savestr = f'item-scatter_' \
f'X={x_val}_Y={y_val}_' \
f'YERR={yerr_type}_' \
f'xl={xlim_str}_yl={ylim_str}_' \
f'mean={add_mean}_' \
f'a={plot_aspect}_' \
f'i={add_identity}_' \
f'{target_UIDs_str}_{roi}_' \
f'{base_savestr}{add_savestr}'
df_roi = df.copy(deep=True).query(f'roi == "{roi}"')
print(f'\n\nPlotting: {savestr}\n'
f'Total number of data points across {len(df_roi.target_UID.unique())} participants: {len(df_roi)}')
# Create df that is grouped by item id. Keep string columns as is
df_item_id = groupby_coord(df=df_roi, coord_col='item_id', aggfunc='mean', )
# Get yerr
if yerr_type is not None:
if yerr_type == 'sem_over_UIDs':
df_yerr = groupby_coord(df=df_roi, coord_col='item_id', aggfunc='sem', )
# Scatterplot
color_order = [d_colors[x] for x in df_item_id['cond'].values]
df_x = df_item_id.copy(deep=True).loc[:, [x_val]]
assert (df_x.index == df_item_id.index).all(), 'Index of df_x and df_item_id do not match'
if add_mean: # We want to compute the means of the conditions and add them to the plot as horizontal lines
df_mean = df_item_id.groupby('cond').mean().loc[:, [x_val, y_val]]
# Print min/max of x and y (to ensure all data points are within the plot limits)
print(f'Min of {x_val}: {df_x[x_val].min():2f} and max of {x_val}: {df_x[x_val].max():2f}')
print(f'Min of {y_val}: {df_item_id[y_val].min():2f} and max of {y_val}: {df_item_id[y_val].max():2f}')
# Plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_box_aspect(plot_aspect)
ax.scatter(df_x[x_val], # Predicted
df_item_id[y_val], # Actual
c=color_order,
alpha=0.6,
edgecolors='none')
if yerr_type is not None:
ax.errorbar(df_x[x_val], # Predicted
df_item_id[y_val], # Actual
yerr=df_yerr[y_val],
fmt='none',
# use color_order for the error bars as well
ecolor=color_order,
alpha=0.7,
linewidth=0.4)
if add_mean:
for cond in df_mean.index:
ax.axhline(df_mean.loc[cond, y_val], color=d_colors[cond], linestyle='--', alpha=0.6)
# Make ticks and axis labels bigger
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if x_val in d_axes_legend:
plt.xlabel(d_axes_legend[x_val], fontsize=16)
else:
plt.xlabel(x_val, fontsize=16)
if y_val.endswith('noise'):
plt.ylabel(d_axes_legend[y_val], fontsize=16) # f'Actual ({target_UIDs_str})'
else:
plt.ylabel(f'Actual ({target_UIDs_str})', fontsize=16)
plt.title("\n".join(wrap(savestr, 60)), fontsize=14)
if xlim is not None:
plt.xlim(xlim)
if ylim is not None:
plt.ylim(ylim)
if add_identity: # Plot x=y line
plot_identity(ax, color='black', linestyle='-', alpha=0.6)
plt.tight_layout()
# Obtain r value for all values plotted, and for T, D, and B conds separately. Add numbers to plot
r, p = pearsonr(df_x[x_val], df_item_id[y_val])
r_B, p_B = pearsonr(df_x.loc[df_item_id['cond'] == 'B', x_val],
df_item_id.loc[df_item_id['cond'] == 'B', y_val])
r_D, p_D = pearsonr(df_x.loc[df_item_id['cond'] == 'D', x_val],
df_item_id.loc[df_item_id['cond'] == 'D', y_val])
r_S, p_S = pearsonr(df_x.loc[df_item_id['cond'] == 'S', x_val],
df_item_id.loc[df_item_id['cond'] == 'S', y_val])
plt.text(0.01, 0.95, f'r={r:.2f}, p={p:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.90, f'r_T={r_B:.2f}, p_T={p_B:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.85, f'r_D={r_D:.2f}, p_D={p_D:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.80, f'r_B={r_S:.2f}, p_B={p_S:.3}', fontsize=10, transform=plt.gca().transAxes)
if save:
savestr = shorten_savestr(savestr=savestr)
os.chdir(PLOTDIR)
plt.savefig(savestr + '.pdf', dpi=300)
os.chdir(CSVDIR)
# Merge df with df_x and save
df_item_id_store = pd.concat([df_item_id.rename(columns={y_val: f'y_{y_val}'}),
# Ensure that our x and y vals are renamed such that we know what was plotted
df_x.rename(columns={x_val: f'x_{x_val}'})], axis=1)
# Add a col with the r and p values
df_item_id_store['r_all-conds'] = r
df_item_id_store['p_all-conds'] = p
df_item_id_store['r_B'] = r_B
df_item_id_store['p_B'] = p_B
df_item_id_store['r_D'] = r_D
df_item_id_store['p_D'] = p_D
df_item_id_store['r_S'] = r_S
df_item_id_store['p_S'] = p_S
df_item_id_store.to_csv(savestr + '.csv')
plt.show()
def item_scatter_surp_preds(df: pd.DataFrame,
rois_of_interest: str,
target_UIDs: typing.Union[list, np.ndarray],
x_val: str = f'encoding_model_pred',
y_val: str = 'response_target',
yerr_type: typing.Union[str, None] = 'sem_over_UIDs',
add_mean: bool = False,
xlim: typing.Union[list, np.ndarray, None] = None,
ylim: typing.Union[list, np.ndarray, None] = None,
plot_aspect: float = 1,
add_identity: bool = True,
save: bool = False,
base_savestr: str = '',
add_savestr: str = '',
PLOTDIR: typing.Union[str, None] = None,
CSVDIR: typing.Union[str, None] = None,
):
"""
Plot scatter per item. For use with SI 16 and predictions from the surprisal models.
Args
df (pd.DataFrame): Dataframe with rows = items (responses averaged across individuals) and cols with neural data and condition info.
target_UIDs (list): only for savestr. The data has already been averaged over the participants of interest.
rois_of_interest: str, which ROIs to plot (uses the dictionary d_roi_lists_names)
x_val (str): Which column to use for the x-axis (Predicted response intended:
'encoding_model_pred')
y_val (str): Which column to use for the y-axis (Actual response intended)
yerr_type (bool): which y error to compute, options are:
'sem_over_UIDs': compute sem (ddof=1) across participants for a given item
add_mean (bool): whether to add a mean line to the plot of the conditions
xlim (list): x-axis limits
ylim (list): y-axis limits
plot_aspect (float): aspect ratio of the plot
add_identity (bool): whether to add an identity line to the plot, x=y
base_savestr (str): Base string to use for saving the plot
add_savestr (str): Additional string to use for saving the plot
save (bool): Whether to save the plot)"""
# Define savestr
target_UIDs_str = '-'.join(target_UIDs)
# Filter data
rois_of_interest, rois_of_interest_name = get_roi_list_name(rois_of_interest=rois_of_interest)
for roi in rois_of_interest:
# If xlim and ylim are not None, join them into a string
if xlim is not None:
xlim_str = f'{xlim[0]}-{xlim[1]}'
else:
xlim_str = 'None'
if ylim is not None:
ylim_str = f'{ylim[0]}-{ylim[1]}'
else:
ylim_str = 'None'
savestr = f'item-scatter_' \
f'X={x_val}_Y={y_val}_' \
f'YERR={yerr_type}_' \
f'xl={xlim_str}_yl={ylim_str}_' \
f'mean={add_mean}_' \
f'a={plot_aspect}_' \
f'i={add_identity}_' \
f'{target_UIDs_str}_{roi}_' \
f'{base_savestr}{add_savestr}'
df_roi = df.copy(deep=True).query(f'roi == "{roi}"')
# Create df that is grouped by item id. Keep string columns as is
df_item_id = groupby_coord(df=df_roi, coord_col='item_id', aggfunc='mean', )
# Get yerr
if yerr_type is not None:
if yerr_type == 'sem_over_UIDs':
df_yerr = groupby_coord(df=df_roi, coord_col='item_id', aggfunc='sem', )
# Scatterplot
color_order = [d_colors[x] for x in df_item_id['cond'].values]
df_x = df_item_id.copy(deep=True).loc[:, [x_val]]
assert (df_x.index == df_item_id.index).all(), 'Index of df_x and df_item_id do not match'
if add_mean: # We want to compute the means of the conditions and add them to the plot as horizontal lines
df_mean = df_item_id.groupby('cond').mean().loc[:, [x_val, y_val]]
# Print min/max of x and y (to ensure all data points are within the plot limits)
print(f'Min of {x_val}: {df_x[x_val].min():2f} and max of {x_val}: {df_x[x_val].max():2f}')
print(f'Min of {y_val}: {df_item_id[y_val].min():2f} and max of {y_val}: {df_item_id[y_val].max():2f}')
# Plot
fig, ax = plt.subplots(figsize=(8, 6))
ax.set_box_aspect(plot_aspect)
ax.scatter(df_x[x_val], # Predicted
df_item_id[y_val], # Actual
c=color_order,
alpha=0.6,
edgecolors='none')
if yerr_type is not None:
ax.errorbar(df_x[x_val], # Predicted
df_item_id[y_val], # Actual
yerr=df_yerr[y_val],
fmt='none',
# use color_order for the error bars as well
ecolor=color_order,
alpha=0.7,
linewidth=0.4)
if add_mean:
for cond in df_mean.index:
ax.axhline(df_mean.loc[cond, y_val], color=d_colors[cond], linestyle='--', alpha=0.6)
# Make ticks and axis labels bigger
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
if x_val in d_axes_legend:
plt.xlabel(d_axes_legend[x_val], fontsize=16)
else:
plt.xlabel(x_val, fontsize=16)
if y_val.endswith('noise'):
plt.ylabel(d_axes_legend[y_val], fontsize=16) # f'Actual ({target_UIDs_str})'
else:
plt.ylabel(f'Actual ({target_UIDs_str})', fontsize=16)
plt.title("\n".join(wrap(savestr, 60)), fontsize=14)
if xlim is not None:
plt.xlim(xlim)
if ylim is not None:
plt.ylim(ylim)
if add_identity: # Plot x=y line
plot_identity(ax, color='black', linestyle='-', alpha=0.6)
plt.tight_layout()
# Obtain r value for all values plotted, and for T, D, and B conds separately. Add numbers to plot
r, p = pearsonr(df_x[x_val], df_item_id[y_val])
r_B, p_B = pearsonr(df_x.loc[df_item_id['cond'] == 'B', x_val],
df_item_id.loc[df_item_id['cond'] == 'B', y_val])
r_D, p_D = pearsonr(df_x.loc[df_item_id['cond'] == 'D', x_val],
df_item_id.loc[df_item_id['cond'] == 'D', y_val])
r_S, p_S = pearsonr(df_x.loc[df_item_id['cond'] == 'S', x_val],
df_item_id.loc[df_item_id['cond'] == 'S', y_val])
plt.text(0.01, 0.95, f'r={r:.2f}, p={p:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.90, f'r_T={r_B:.2f}, p_T={p_B:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.85, f'r_D={r_D:.2f}, p_D={p_D:.3}', fontsize=10, transform=plt.gca().transAxes)
plt.text(0.01, 0.80, f'r_B={r_S:.2f}, p_B={p_S:.3}', fontsize=10, transform=plt.gca().transAxes)
if save:
savestr = shorten_savestr(savestr=savestr)
os.chdir(PLOTDIR)
plt.savefig(savestr + '.pdf', dpi=300)
os.chdir(CSVDIR)
# Merge df with df_x and save
df_item_id_store = pd.concat([df_item_id.rename(columns={y_val: f'y_{y_val}'}),
# Ensure that our x and y vals are renamed such that we know what was plotted
df_x.rename(columns={x_val: f'x_{x_val}'})], axis=1)
# Add a col with the r and p values
df_item_id_store['r_all-conds'] = r
df_item_id_store['p_all-conds'] = p
df_item_id_store['r_B'] = r_B
df_item_id_store['p_B'] = p_B
df_item_id_store['r_D'] = r_D
df_item_id_store['p_D'] = p_D
df_item_id_store['r_S'] = r_S
df_item_id_store['p_S'] = p_S
df_item_id_store.to_csv(savestr + '.csv')
plt.show()
def NC_across_ROIs(df: pd.DataFrame,
rois: typing.Union[list, np.ndarray],
nc_col: str = 'nc',
nc_err_col: str = 'split_half_se',
save: bool = False,
ylim: typing.Union[list, np.ndarray] = None,
add_space: bool = True,
base_savestr: str = '',
PLOTDIR: str = '',
CSVDIR: str = '', ):
"""
Plot the NC (y-axis) across ROIs (x-axis)
Args
df: pd.DataFrame with index = rois, columns = nc_col, nc_err_col
rois: list of rois to plot
nc_col: column name for NC (y-axis)
nc_err_col: column name for NC error (y-axis)
save: bool, whether to save the figure
add_space: bool, whether to add space between the points when networks change
base_savestr: str, base savestr for the figure
PLOTDIR: str, directory to save the figure
CSVDIR: str, directory to save the csv file
"""
# check which rois_plot are not in df_nc_roi_all
rois_not_in_df = [roi for roi in rois if roi not in df.index]
print(
f'rois_not_in_nc: {rois_not_in_df}') # We do not have NC for md_LH_midFrontalOrb (because 848 had neg t-stat for this ROI)
df_nc_roi = df.loc[[roi for roi in rois if roi not in rois_not_in_df]]
# All ROIs have a color specified in d_netw_colors
colors = [d_netw_colors[x] for x in df_nc_roi.index]
# Make the roi labels nice
roi_labels = make_ROI_labels_nice(roi_list=df_nc_roi.index.values)
nc_y = df_nc_roi[nc_col].values
nc_yerr = df_nc_roi[nc_err_col].values
if add_space:
# # Insert a blank (0) between networks (so when Lang switches to MD and then MD switches to DMN)
replace_flag = False
for i in range(len(roi_labels)):
if replace_flag:
replace_flag = False # To avoid checking a zero str when we just inserted a blank
continue
if i == 0:
continue
if roi_labels[i][0] != roi_labels[i - 1][0]:
replace_flag = True
roi_labels.insert(i, '')
nc_y = np.insert(nc_y, i, 0)
nc_yerr = np.insert(nc_yerr, i, 0)
colors.insert(i, 'white')
# Define savestr
if ylim is not None:
ylimstr = f'{ylim[0]}-{ylim[1]}'
savestr = f'NC-across-ROIs_' \
f'Y={nc_col}_YERR={nc_err_col}_' \
f'yl={ylimstr}_' \
f'space={add_space}_' \
f'n_ROIs={len(df_nc_roi.index)}_' \
f'{base_savestr}'
# Y-axis: nc with error split_half_se across all ROIs (index) on x-axis
fig, ax = plt.subplots(figsize=(10, 7))
ax.errorbar(x=np.arange(len(nc_y)), y=nc_y,
yerr=nc_yerr,
ls='none',
ecolor=colors)
ax.scatter(x=np.arange(len(nc_y)), y=nc_y,
color=colors,
marker='o',
s=50,
linewidths=0)
plt.title("\n".join(wrap(savestr, 80)))
if ylim is not None:
plt.ylim(ylim)
plt.xlabel('ROI')
plt.ylabel('NC + split-half reliability')
# Make y ticks larger
plt.yticks(fontsize=14)
plt.xticks(fontsize=12.5)
ax.set_xticks(np.arange(len(nc_y)))
ax.set_xticklabels(roi_labels, rotation=90)
# Make dotted line for NC = 0
plt.axhline(y=0, color='k', linestyle='--')
plt.tight_layout(pad=2)
if save:
savestr = shorten_savestr(savestr)
os.chdir(PLOTDIR)
plt.savefig(f'{savestr}.pdf', dpi=180)
# Save the df as csv
os.chdir(CSVDIR)
df_nc_roi.to_csv(f'{savestr}.csv')
plt.show()
print(f'NC across ROIs: {df_nc_roi[nc_col].values}')
def add_noise_to_pred(df: pd.DataFrame,
pred_col: str = 'encoding_model_pred',
neural_col: str = 'response_target',
pooled_neural_sd: typing.Union[float, None] = None,
num_participants: typing.Union[int, None] = None) -> pd.DataFrame:
"""
Given a column of predicted neural data, and a column of actual neural data, add noise to the predicted neural data
based on the participant variability in the actual neural data.
The process is:
COMPUTATION OF TRUE SD ACROSS PARTICIPANTS:
For each of 1500 items,
1. compute sd across 3 subjects (using n-1)
2. square sd.^2, mean across 1500, sqrt ==> pooled sd
SIMULATION OF PARTICIPANT NOISE ON PREDICTIONS:
Simulate:
For each of 1500 items,
simulate y_hat + N(0,sd ~ #2), three times
mean across those three measurements
Args:
df: dataframe with rows as items, and columns containing predicted neural data and actual neural data
pred_col: column name of predicted neural data, default is 'encoding_model_pred'
neural_col: column name of actual neural data, default is 'response_target'
pooled_neural_sd: if not None, use this value as the pooled sd across participants (nice for simulations)
num_participants: if not None, use this value as the number of participants (nice for simulations)
Returns:
df_to_return: input dataframe with column: {pred_col}_noise added to it
"""
df_to_return = df.copy(deep=True)
#### First, compute the pooled sd over participants in the real neural data for each item_id (1500) ####
if not pooled_neural_sd: # Compute it based on real data
df_item_id_sd = df_to_return.groupby('item_id')[neural_col].std(ddof=1) # For each item_id, compute sd across participants
pooled_neural_sd = np.sqrt(np.mean(df_item_id_sd ** 2)) # Taking the average of standard deviations
else:
print(f'Using input pooled_neural_sd: {pooled_neural_sd}') # Manual input
#### Second, for each item_id, take the predicted neural data, and add N(0, pooled_sd) to it ####
if not num_participants:
num_participants = df_to_return.target_UID.nunique()
else:
print(f'Using input num_participants: {num_participants}')
for item_id in df_to_return.item_id.unique():
# Get the predicted neural data for this item_id
df_one_item = df_to_return[df_to_return.item_id == item_id]
# Add N(0, pooled_neural_sd) to it
df_one_item_pred = df_one_item[
pred_col] # Get the predicted value for that given item (should be the same for all participants)
if not len(np.unique(df_one_item_pred)) == 1:
print(f'Warning: predicted neural data for item_id {item_id} is not the same across participants')
# assert len(np.unique(df_one_item_pred)) == 1 # Assert that vals are the same
item_pred = df_one_item_pred.iloc[0]
# Sample noise from N(0, pooled_neural_sd) and add to the predicted value as many times as there are participants
lst_item_id_pred_noise = []
for i in range(num_participants):
# Simulate y_hat + N(0,sd ~ #2), three times
item_pred_noise = item_pred + np.random.normal(0,
pooled_neural_sd) # Just samples one value from the Gaussian distribution
lst_item_id_pred_noise.append(item_pred_noise)
# Mean across those three measurements
item_id_pred_noise_mean = np.mean(lst_item_id_pred_noise)
# Create new col with this value
df_to_return.loc[df_to_return.item_id == item_id, f'{pred_col}_noise'] = item_id_pred_noise_mean
return df_to_return
def heatmap(df_corr: pd.DataFrame = None,
title: str = None,
savestr: str = None,
save: bool = False,
vmin: float = None,
vmax: float = None,
center: float = None,
pretty_roi_labels: bool = False,
annot: bool = False,
figsize: tuple = (20, 20),
PLOTDIR: str = None,
CSVDIR: str = None, ):
"""
Plot heatmap of correlation matrix.
Args:
df_corr (pandas.DataFrame): correlation matrix
title (str): title of the plot
savestr (str): string to append to the filename
save (bool): whether to save the plot
vmin (float): minimum value for the colorbar
vmax (float): maximum value for the colorbar
center (float): center value for the colorbar
pretty_roi_labels (bool): whether to make the labels more interpretable for ROI correlations
annot (bool): whether to annotate the heatmap with the correlation values
figsize (tuple): figure size
PLOTDIR (str): directory to save the plot
CSVDIR (str): directory to save the csv file
"""
if pretty_roi_labels:
# Replace _ with space and uppercase first letter
df_corr.index = df_corr.index.str.replace('_', ' ')
df_corr.index = [s[0].upper() + s[1:] for s in df_corr.index]
df_corr.columns = df_corr.index
fig, ax = plt.subplots(figsize=figsize)
sns.heatmap(df_corr,
annot=annot,
fmt='.2f',
ax=ax,
cmap='RdBu_r',
square=True,
vmin=vmin,
vmax=vmax,
center=center,
cbar_kws={'label': 'Pearson R',
'shrink': 0.5,
},
# Make annot bigger
annot_kws={'size': 14},
)
plt.title(title, fontsize=20)
# Make labels bigger
ax.tick_params(axis='both', which='major', labelsize=14)