-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFigures.py
More file actions
2535 lines (2141 loc) · 110 KB
/
Figures.py
File metadata and controls
2535 lines (2141 loc) · 110 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
"""
Figures - Figures within the EMPRISE project (Revision)
Joram Soch, MPI Leipzig <soch@cbs.mpg.de>
2023-05-28, 15:45: inherited from "Figures_V1.py"
2024-05-28, 16:16: WP1_Fig1
2024-06-04, 15:47: WP1_Fig2
2024-06-19, 14:59: WP1_Fig3
2024-06-19, 15:27: WP1_Fig4
2024-06-25, 19:57: WP1_Fig2
2024-06-27, 13:18: WP1_Fig2
2024-07-10, 15:59: WP1_Fig4
2024-07-18, 15:34: WP1_Ana2
2024-07-24, 12:39: WP1_Ana2
2024-07-24, 13:48: WP1_Fig2
2024-07-24, 15:43: WP1_Fig1
2024-07-25, 17:58: WP1_Fig3, WP1_Fig4
2024-07-31, 18:12: WP1_Fig1/2/3/4, WP1_Tab1/2
2024-08-01, 18:28: WP1_Fig4
2024-08-01, 19:21: WP1_Fig5
2024-08-02, 16:53: WP1_Fig4
2024-08-02, 17:02: WP1_Fig1, WP1_Fig5
2024-09-11, 16:09: WP1_Fig6
2024-09-16, 15:58: WP1_Fig4
2024-09-27, 09:15: renamed "Figures_Rev" to "Figures_WP1"
2024-09-27, 09:24: WP1_Fig4, WP1_Fig5
2025-10-02, 13:15: WP1_Fig4
2025-10-08, 11:13: WP1_Fig7
"""
# import packages
#-----------------------------------------------------------------------------#
import os
import math
import numpy as np
import scipy as sp
import pandas as pd
import nibabel as nib
from nilearn import surface
from surfplot import Plot
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
import PySPMs as PySPM
import NumpRF
import EMPRISE
# specify default model
#-----------------------------------------------------------------------------#
model_def = 'True_False_iid_1_V2_new'
# specify results directory
#-----------------------------------------------------------------------------#
if EMPRISE.at_MPI:
res_dir = '/data/hu_soch/ownCloud/MPI/EMPRISE/tools/Python/NumpRF_results/'
else:
res_dir = r'C:\Users\sochj\ownCloud_MPI\MPI\EMPRISE\tools\Python\NumpRF_results/'
# define numerosity maps
#-----------------------------------------------------------------------------#
hemis= ['L', 'R']
maps = {'visual': {'labels': ['NTO', 'NPO', 'NPC1', 'NPC2', 'NPC3', 'NF'], \
# Source: Harvey & Dumoulin (2017), pp. 1-2
'mean' : {'L': np.array([[-42, -77, -3], \
[-23, -80, 32], \
[-22, -59, 61], \
[-38, -43, 48], \
[-48, -29, 34], \
[-22, -11, 50]]), \
'R': np.array([[ 44, -75, -4], \
[ 25, -82, 34], \
[ 22, -61, 60], \
[ 33, -40, 52], \
[ 45, -30, 40], \
[ 24, -11, 52]])}, \
'std' : {'L': np.array([[ 3, 3, 8], \
[ 4, 5, 7], \
[ 4, 11, 8], \
[ 3, 8, 8], \
[ 6, 5, 6], \
[ 3, 6, 8]]), \
'R': np.array([[ 7, 1, 3], \
[ 5, 4, 6], \
[ 5, 7, 5], \
[ 3, 4, 7], \
[ 10, 6, 4], \
[ 3, 5, 6]])}}, \
'audio' : {'labels': ['NaT', 'NaF'], \
# "Numerosity, auditory, temporal/frontal"
'mean' : {'L': np.array([[np.nan, -30, 10], \
[np.nan, -5, 55]]), \
'R': np.array([[np.nan, -30, 10], \
[np.nan, 0, 50]])}, \
'std' : {'L': np.array([[np.nan, np.nan, np.nan], \
[np.nan, np.nan, np.nan]]), \
'R': np.array([[np.nan, np.nan, np.nan], \
[np.nan, np.nan, np.nan]])}}}
# function: p-value string
#-----------------------------------------------------------------------------#
def pvalstr(p, p_thr=0.001, sig_thr=[]):
"""
Convert p-Value to p-Value String
p_str = pvalstr(p, p_thr, sig_thr)
p - float; p-value
p_thr - float; p-value threshold under which not to display
sig_thr - list; significance thresholds defining asterisks
p_str - string; p-value string
"""
# get number of significant digits
num_dig = -math.floor(math.log10(p_thr))
# create p-value string
if p < p_thr:
p_str = ('p < {' + ':.{}f'.format(num_dig) + '}').format(p_thr)
else:
p_str = ('p = {' + ':.{}f'.format(num_dig) + '}').format(p)
# add significance markers
sig_str = '*' * np.sum(p<np.array(sig_thr))
p_str = p_str + sig_str
return p_str
# function: simple linear regression
#-----------------------------------------------------------------------------#
def simplinreg(y, x):
"""
Simple Linear Regression with Correlation
r, p, m, n = simplinreg(y, x)
y - n x 1 array; vector of observations
x - n x 1 array; vector of predictions
r - float; Pearson correlation between x and y
p - float; p-value of the correlation coefficient
m - float; slope of the regression line
n - float; intercept of the regression line
r, p, m, n = simplinreg(y, x) performs a simple linear regression of
observations y on predictors x and returns correlation coefficient r,
p-value p, slope and intercept of the regression line m and n.
"""
# run linear regression
slope, intercept, corr, pval, stderr = sp.stats.linregress(x, y)
# return parameter estimates
r = corr
p = pval
m = slope
n = intercept
return r, p, m, n
# function: calculate surface area
#-----------------------------------------------------------------------------#
def calc_surface_area(verts, trias):
"""
areas = calc_surface_area(verts, trias)
verts - v x 9 array of float; vertex properties (see "EMPRISE.threshold_and_cluster")
trias - t x 3 array of int; triangle vertices (see "EMPRISE.threshold_and_cluster")
areas - v x 7 array of float; supra-threshold triangles with area
o 1st column: triangle index
o 2nd column: cluster index
o 3rd, 4th, 5th column: average mu, fwhm, beta
o 6th column: average R-squared
o 7th column: triangle area
areas = calc_surface_area(verts, trias) takes vertex and triangle
information, as provided by "EMPRISE.threshold_and_cluster" and returns
all triangles that fully consist of supra-threshold vertices, including
their surface area.
Note: coordinates are a v x 3 array and triangles are a t x 3 array.
Source: https://nben.net/MRI-Geometry/#surface-geometry-data
"""
# get vertex indices
verts_ind = verts[:,0].astype(np.int32)
areas = np.zeros((0,7))
# cycle through triangles
for j in range(trias.shape[0]):
# if all three vertices are above threshold,
# then the triangle is above threshold
if trias[j,0] in verts_ind:
if trias[j,1] in verts_ind:
if trias[j,2] in verts_ind:
# get all three vertices
ABC = np.r_[verts[verts_ind==trias[j,0],:], \
verts[verts_ind==trias[j,1],:], \
verts[verts_ind==trias[j,2],:]]
# calculate triangle area
AB = ABC[1,6:9] - ABC[0,6:9]
AC = ABC[2,6:9] - ABC[0,6:9]
ABxAC = np.cross(AB, AC)
A = np.sqrt(np.sum(np.power(ABxAC,2)))/2
# See: https://math.stackexchange.com/a/128999/480910
del AB, AC, ABxAC
# collect triangle information
areas = np.r_[areas, \
np.array([[j, ABC[0,1], \
np.mean(ABC[:,2]), np.mean(ABC[:,3]), np.mean(ABC[:,4]), \
np.mean(ABC[:,5]), A]])]
del ABC
# return triangle information
return areas
# function: filter supra-threshold clusters
#-----------------------------------------------------------------------------#
def filter_clusters(verts, areas, A_min=10, d_max=10, nmap='', hemi=''):
"""
verts, areas = filter_clusters(verts, areas, A_min, d_max, nmap, hemi)
verts - v x 9 array of float; vertex properties (see "EMPRISE.threshold_and_cluster")
areas - v x 7 array of float; triangle properties (see "calc_surface_area")
A_min - float; minimum cluster size [mm²]
d_max - float; maximum distance to map [mm]
nmap - string; numerosity map identifier (see "maps[...]['labels']")
hemi - string; brain hemisphere identifier (e.g. "L")
verts - w x 9 array of float; filtered vertices
areas - w x 7 array of float; filtered triangles
verts, areas = filter_clusters(verts, areas, A_min, d_max, nmap, hemi)
calculates surface areas for all clusters in verts and areas and removes
clusters which are smaller than A_min or further than d_max away from
numerosity map nmap in hemisphere hemi.
Note: "d_max" is only applied, if "nmap" and "hemi" are non-empty.
If "nmap" is a modality (e.g. 'visual' or 'audio'), the clusters close
to all maps from this modality are filtered.
"""
# get number of clusters
if verts.shape[0] > 0:
num_clst = int(np.max(verts[:,1]))
else:
num_clst = 0
cls_inds = np.array(range(1,num_clst+1))
# filter clusters for area
for i in cls_inds:
# calculate area
verts_cls = verts[:,1].astype(np.int32)
areas_cls = areas[:,1].astype(np.int32)
A = np.sum(areas[areas_cls==i,6])
# remove cluster, if cluster area < minimum area
if A < A_min:
verts = verts[verts_cls!=i,:]
areas = areas[areas_cls!=i,:]
# assign to numerosity map
if nmap and hemi:
# get session and index
if nmap in EMPRISE.sess:
ses = nmap
ind = [imap for imap in range(len(maps[ses]['labels']))]
elif nmap in maps['visual']['labels']:
ses = 'visual'
ind = maps[ses]['labels'].index(nmap)
elif nmap in maps['audio']['labels']:
ses = 'audio'
ind = maps[ses]['labels'].index(nmap)
else:
vis_maps = ','.join(maps['visual']['labels'])
aud_maps = ','.join(maps['audio']['labels'])
err_msg = 'Unknown numerosity map: "{}". Map must be one of [{}] or [{}].'
raise ValueError(err_msg.format(nmap, vis_maps, aud_maps))
# if indices are a list
if type(ind) == list:
# check all numerosity maps
verts_all = np.zeros((0,verts.shape[1]))
areas_all = np.zeros((0,areas.shape[1]))
for imap in ind:
# filter clusters for this map
verts_new, areas_new = filter_clusters(verts, areas, A_min, d_max, maps[ses]['labels'][imap], hemi)
# add cluster, if not yet filtered
verts_all_cls = verts_all[:,1].astype(np.int32)
verts_new_cls = verts_new[:,1].astype(np.int32)
areas_new_cls = areas_new[:,1].astype(np.int32)
for i in cls_inds:
if i not in verts_all_cls:
verts_all = np.r_[verts_all, verts_new[verts_new_cls==i,:]]
areas_all = np.r_[areas_all, areas_new[areas_new_cls==i,:]]
# store filtered clusters
verts = verts_all
areas = areas_all
del verts_all, areas_all, verts_new, areas_new
# if index is an integer
elif type(ind) == int:
# filter clusters for distance
for i in cls_inds:
# if cluster still exists
verts_cls = verts[:,1].astype(np.int32)
areas_cls = areas[:,1].astype(np.int32)
if np.sum(verts_cls==i) > 0:
# calculate distance
if ses == 'visual':
c = maps['visual']['mean'][hemi][ind,:]
E = verts[verts_cls==i,6:9] - np.tile(c, (np.sum(verts_cls==i),1))
d = np.sqrt(np.sum(np.power(E, 2), axis=1))
d = np.min(d)
if ses == 'audio':
c = maps['audio']['mean'][hemi][ind,:]
E = verts[verts_cls==i,7:9] - np.tile(c[1:3], (np.sum(verts_cls==i),1))
E = np.concatenate((np.mean(np.matrix(E), axis=1), E), axis=1)
d = np.sqrt(np.sum(np.power(E, 2), axis=1))
d = np.min(d)
# remove cluster, if cluster distance > maximum distance
if d > d_max:
verts = verts[verts_cls!=i,:]
areas = areas[areas_cls!=i,:]
# return clusters
return verts, areas
# function: Work Package 1, Table 1
#-----------------------------------------------------------------------------#
def WP1_Tab1():
# read participant table
filename = EMPRISE.data_dir+'participants.tsv'
part_info = pd.read_table(filename)
subs = EMPRISE.adults
sess = ['visual', 'audio']
# preallocate table columns
gender = []
age = []
hit_rates = np.zeros((len(subs),len(EMPRISE.runs),len(sess)))
visual_hit_rate = []
audio_hit_rate = []
# collect subject information
for i, sub in enumerate(subs):
# get subject info
sub_info = part_info[part_info['participant_id']=='sub-'+sub]
gender.append(sub_info.iloc[0,2])
age.append(np.mean(np.unique(sub_info['age'])))
# for both sessions
for k, ses in enumerate(sess):
# for all runs
for j, run in enumerate(EMPRISE.runs):
# load logfile
filename = EMPRISE.Session(sub, ses).get_events_tsv(run)
events = pd.read_csv(filename, sep='\t')
# analyze all trials
num_catch = 0
num_resp = 0
for t in range(len(events)):
if events['trial_type'][t].find('_attn') > -1:
num_catch = num_catch + 1
curr_time = events['onset'][t]
time_after = events[(events['onset']>(curr_time+0.1)) & (events['onset']<(curr_time+2.1))]
if sum(time_after['trial_type']!='button_press') > 0:
num_resp = num_resp + 1
# calculate hit rates
print('Subject {}, Session {}, Run {}: {} catch trials, {} responses.'. \
format(sub, ses, run, num_catch, num_resp))
hit_rates[i,j,k] = (num_resp/num_catch)*100
# store hit rates
visual_hit_rate.append(np.mean(hit_rates[i,:,0]))
audio_hit_rate.append(np.mean(hit_rates[i,:,1]))
# create data frame
data = zip(subs, gender, age, visual_hit_rate, audio_hit_rate)
cols = ['Subject_ID', 'gender', 'age', \
'visual hit rate', 'auditory hit rate']
df = pd.DataFrame(data, columns=cols)
# save data frame to CSV/XLS
df.to_csv('Figures_WP1/WP1_Table_1_sub-all.csv', index=False)
df.to_excel('Figures_WP1/WP1_Table_1_sub-all.xlsx', index=False)
# function: Work Package 1, Table 2
#-----------------------------------------------------------------------------#
def WP1_Tab2():
# specify analysis
subs = EMPRISE.adults
sess =['visual', 'audio']
space = 'fsnative'
mesh = 'pial'
A_min ={'visual': 50, 'audio': 25}
# preallocate statistics
df_ses = []
df_dep = []
df_ind = []
df_coef = []
df_z = []
df_pval = []
df_ci1 = []
df_ci2 = []
# for all sessions
for ses in sess:
# load results
filepath = res_dir+'sub-adults'+'_ses-'+ses+'_space-'+space+'_mesh-'+mesh+'_AFNI_'
verts = sp.io.loadmat(filepath+'verts.mat')
areas = sp.io.loadmat(filepath+'areas.mat')
# specify mu grid
d_mu = 0.5
mu_min = EMPRISE.mu_thr[0]
mu_max = EMPRISE.mu_thr[1]
mu_b = np.arange(mu_min, mu_max+d_mu, d_mu)
mu_c = np.arange(mu_min+d_mu/2, mu_max+d_mu/2, d_mu)
# preallocate data
df_subs = []
df_hemis = []
df_mus = []
df_fwhms = []
df_areas = []
# for all subjects
for sub in subs:
# for both hemispheres
for j, hemi in enumerate(hemis):
# get supra-threshold vertices/triangles
verts_sub = verts[sub][hemi][0,0]
areas_sub = areas[sub][hemi][0,0]
# verts_sub, areas_sub = \
# filter_clusters(verts_sub, areas_sub, A_min[ses])
mu_vert = verts_sub[:,2]
fwhm_vert = verts_sub[:,3]
mu_area = areas_sub[:,2]
area_area = areas_sub[:,6]
# if supra-threshold vertices exist
if verts_sub.shape[0] > 0:
# go through numerosity bins
for k in range(mu_c.size):
# extract tuning width
ind_k = np.logical_and(mu_vert>mu_b[k],mu_vert<mu_b[k+1])
if np.sum(ind_k) > 0:
fwhm_m = np.mean(fwhm_vert[ind_k])
else:
fwhm_m = np.nan
# extract surface area
ind_k = np.logical_and(mu_area>mu_b[k],mu_area<mu_b[k+1])
if np.sum(ind_k) > 0:
area_s = np.sum(area_area[ind_k])
else:
area_s = 0
# store into data frame
if not np.isnan(fwhm_m): # area_s > 0:
df_subs.append(sub)
df_hemis.append(hemi)
df_mus.append(mu_c[k])
df_fwhms.append(fwhm_m)
df_areas.append(area_s)
# create data frame
data = zip(df_subs, df_hemis, df_mus, df_fwhms, df_areas)
cols = ['sub', 'hemi', 'mu', 'fwhm', 'area']
Y = pd.DataFrame(data, columns=cols)
# run linear mixed model (area vs. mu)
lmm = smf.mixedlm('area ~ mu:hemi + hemi', Y, groups=Y['sub'])
lmm = lmm.fit()
print(lmm.summary())
# store statistical results (area vs. mu)
results = lmm.summary().tables[1]
paras = {'hemisphere': 'hemi[T.R]', 'mu_left': 'mu:hemi[L]', 'mu_right': 'mu:hemi[R]'}
for para in paras.keys():
res = results.loc[paras[para]]
if para == 'hemisphere':
df_ses.append(ses)
df_dep.append('area')
else:
df_ses.append('')
df_dep.append('')
df_ind.append(para)
df_coef.append(float(res.loc['Coef.']))
df_z.append(float(res.loc['z']))
df_pval.append(float(res.loc['P>|z|']))
df_ci1.append(float(res.loc['[0.025']))
df_ci2.append(float(res.loc['0.975]']))
# run linear mixed model (fwhm vs. mu)
lmm = smf.mixedlm('fwhm ~ mu:hemi + hemi', Y, groups=Y['sub'])
lmm = lmm.fit()
print(lmm.summary())
# store statistical results (fwhm vs. mu)
results = lmm.summary().tables[1]
paras = {'hemisphere': 'hemi[T.R]', 'mu_left': 'mu:hemi[L]', 'mu_right': 'mu:hemi[R]'}
for para in paras.keys():
res = results.loc[paras[para]]
if para == 'hemisphere':
df_ses.append(ses)
df_dep.append('fwhm')
else:
df_ses.append('')
df_dep.append('')
df_ind.append(para)
df_coef.append(float(res.loc['Coef.']))
df_pval.append(float(res.loc['P>|z|']))
df_z.append(float(res.loc['z']))
df_ci1.append(float(res.loc['[0.025']))
df_ci2.append(float(res.loc['0.975]']))
# create data frame
data = zip(df_ses, df_dep, df_ind, df_coef, df_z, df_pval, df_ci1, df_ci2)
cols = ['Session','dependent variable','independent variable',\
'coefficient','z-value','p-value','95% CI (lower)','95% CI (upper)']
df = pd.DataFrame(data, columns=cols)
# save data frame to CSV/XLS
df.to_csv('Figures_WP1/WP1_Table_2_sub-all_ses-both.csv', index=False)
df.to_excel('Figures_WP1/WP1_Table_2_sub-all_ses-both.xlsx', index=False)
# function: Work Package 1, Figure 1
#-----------------------------------------------------------------------------#
def WP1_Fig1(Figure):
# sub-function: plot tuning functions & time courses
#-------------------------------------------------------------------------#
def plot_tuning_function_time_course(sub, ses, model, hemi, space, cv=True, verts=[0,0], col='b'):
# load session data
mod = EMPRISE.Model(sub, ses, model, space)
Y, M = mod.load_mask_data(hemi)
labels = EMPRISE.covs
X_c = mod.get_confounds(labels)
X_c = EMPRISE.standardize_confounds(X_c)
ons, dur, stim = mod.get_onsets()
ons, dur, stim = EMPRISE.onsets_trials2blocks(ons, dur, stim, 'closed')
ons0,dur0,stim0= ons[0], dur[0], stim[0]
ons, dur, stim = EMPRISE.correct_onsets(ons0, dur0, stim0)
# load model results
res_file = mod.get_results_file(hemi)
NpRF = sp.io.loadmat(res_file)
mu = np.squeeze(NpRF['mu_est'])
fwhm = np.squeeze(NpRF['fwhm_est'])
beta = np.squeeze(NpRF['beta_est'])
# determine tuning function
try:
ver = NpRF['version'][0]
except KeyError:
ver = 'V2'
linear_model = 'lin' in ver
# load vertex-wise coordinates
hemis = {'L': 'left', 'R': 'right'}
para_map = res_file[:res_file.find('numprf.mat')] + 'mu.surf.gii'
para_mask = nib.load(para_map).darrays[0].data != 0
mesh_file = mod.get_mesh_files(space,'pial')[hemis[hemi]]
mesh_gii = nib.load(mesh_file)
XYZ = mesh_gii.darrays[0].data
XYZ = XYZ[para_mask,:]
del para_map, mesh_file, mesh_gii
# if CV, load cross-validated R^2
if cv:
Rsq_map = res_file[:res_file.find('numprf.mat')] + 'cvRsq.surf.gii'
cvRsq = nib.load(Rsq_map).darrays[0].data
Rsq = cvRsq[para_mask]
del Rsq_map, para_mask, cvRsq
# otherwise, calculate total R^2
else:
MLL1 = np.squeeze(NpRF['MLL_est'])
MLL0 = np.squeeze(NpRF['MLL_const'])
n = np.prod(mod.calc_runs_scans())
Rsq = NumpRF.MLL2Rsq(MLL1, MLL0, n)
# select vertices for plotting
for k, vertex in enumerate(verts):
if vertex == 0:
if k == 0 and len(verts) == 1:
# select maximum R^2 in vertices with numerosity 1 < mu < 5
vertex = np.argmax(Rsq + np.logical_and(mu>1, mu<5))
elif k == 0 and len(verts) == 2:
# select maximum R^2 in vertices with numerosity 1 < mu < 2
vertex = np.argmax(Rsq + np.logical_and(mu>1, mu<2))
elif k == 1:
# select maximum R^2 in vertices with numerosity 4 < mu < 5 or 3 < mu < 5
if ses == 'visual': vertex = np.argmax(Rsq + np.logical_and(mu>4, mu<5) + (fwhm<EMPRISE.fwhm_thr[1]) + (beta>0))
if ses == 'audio': vertex = np.argmax(Rsq + np.logical_and(mu>3, mu<5) + (fwhm<EMPRISE.fwhm_thr[1]) + (beta>0))
verts[k] = vertex
# plot selected vertices
fig = plt.figure(figsize=(24,len(verts)*8))
axs = fig.subplots(len(verts), 2, width_ratios=[4,6])
if len(verts) == 1: axs = np.array([axs])
xr = EMPRISE.mu_thr # numerosity range
xm = xr[1]+1 # maximum numerosity
dx = 0.05 # numerosity delta
# Figure 1A: estimated tuning functions
for k, vertex in enumerate(verts):
# compute vertex tuning function
x = np.arange(dx, xm+dx, dx)
xM = mu[vertex]
if not linear_model:
mu_log, sig_log = NumpRF.lin2log(mu[vertex], fwhm[vertex])
y = NumpRF.f_log(x, mu_log, sig_log)
x1 = np.exp(mu_log - math.sqrt(2*math.log(2))*sig_log)
x2 = np.exp(mu_log + math.sqrt(2*math.log(2))*sig_log)
else:
mu_lin, sig_lin = (mu[vertex], NumpRF.fwhm2sig(fwhm[vertex]))
y = NumpRF.f_lin(x, mu_lin, sig_lin)
x1 = mu[vertex] - fwhm[vertex]/2
x2 = mu[vertex] + fwhm[vertex]/2
x1 = np.max(np.array([0,x1]))
x2 = np.min(np.array([x2,xm]))
# plot vertex tuning function
hdr = 'sub-{}, ses-{}, hemi-{}'.format(sub, ses, hemi)
txt1 = 'vertex {} \n(XYZ = [{:.0f}, {:.0f}, {:.0f}])'. \
format(vertex, XYZ[vertex,0], XYZ[vertex,1], XYZ[vertex,2])
txt2 =('mu = {:.2f}\n fwhm = {' + ':.{}f'.format([1,2][int(fwhm[vertex]<10)]) + '}'). \
format(mu[vertex], fwhm[vertex])
axs[k,0].plot(x[x<=xr[0]], y[x<=xr[0]], '--'+col, linewidth=2)
axs[k,0].plot(x[x>=xr[1]], y[x>=xr[1]], '--'+col, linewidth=2)
axs[k,0].plot(x[np.logical_and(x>=xr[0],x<=xr[1])], y[np.logical_and(x>=xr[0],x<=xr[1])], '-'+col, linewidth=2)
if k == 0:
axs[k,0].plot([xM,xM], [0,1], '-', color='gray', linewidth=2)
axs[k,0].plot([x1,x2], [0.5,0.5], '-', color='gray', linewidth=2)
axs[k,0].text(xM, 0+0.01, ' mu = preferred numerosity', fontsize=18, \
horizontalalignment='left', verticalalignment='bottom')
axs[k,0].text((x1+x2)/2, 0.5-0.01, 'fwhm = tuning width', fontsize=18, \
horizontalalignment='center', verticalalignment='top')
axs[k,0].axis([0, xm, 0, 1+(1/20)])
if k == len(verts)-1:
axs[k,0].set_xlabel('presented numerosity', fontsize=32)
axs[k,0].set_ylabel('neuronal response', fontsize=32)
if k == 0:
axs[k,0].set_title('', fontweight='bold', fontsize=32)
axs[k,0].tick_params(axis='both', labelsize=18)
axs[k,0].text(xm-(1/20)*xm, 0.85, txt1, fontsize=18,
horizontalalignment='right', verticalalignment='top')
axs[k,0].text(xm-(1/20)*xm, 0.05, txt2, fontsize=18,
horizontalalignment='right', verticalalignment='bottom')
del x, y, xM, x1, x2
# Figure 1B: predicted time courses
for k, vertex in enumerate(verts):
# compute "observed" signal
y = EMPRISE.standardize_signals(Y[:,[vertex],:]) - 100
y_reg = np.zeros(y.shape)
for j in range(y.shape[2]):
glm = PySPM.GLM(y[:,:,j], np.c_[X_c[:,:,j], np.ones((EMPRISE.n,1))])
b_reg = glm.OLS()
y_reg[:,:,j] = glm.Y - glm.X @ b_reg
# get vertex tuning parameters
if not linear_model:
mu_k, sig_k = NumpRF.lin2log(mu[vertex], fwhm[vertex])
else:
mu_k, sig_k = (mu[vertex], NumpRF.fwhm2sig(fwhm[vertex]))
# compute predicted signal (run)
y_run, t = EMPRISE.average_signals(y_reg, None, [True, False])
z, t = NumpRF.neuronal_signals(ons0, dur0, stim0, EMPRISE.TR, EMPRISE.mtr, np.array([mu_k]), np.array([sig_k]), lin=linear_model)
s, t = NumpRF.hemodynamic_signals(z, t, EMPRISE.n, EMPRISE.mtr)
glm = PySPM.GLM(y_run, np.c_[s[:,:,0], np.ones((EMPRISE.n, 1))])
b_run= glm.OLS()
s_run= glm.X @ b_run
# compute predicted signal (epoch)
y_avg, t = EMPRISE.average_signals(y_reg, None, [True, True])
# Note: For visualization purposes, we here apply "avg = [True, True]".
z, t = NumpRF.neuronal_signals(ons, dur, stim, EMPRISE.TR, EMPRISE.mtr, np.array([mu_k]), np.array([sig_k]), lin=linear_model)
s, t = NumpRF.hemodynamic_signals(z, t, EMPRISE.scans_per_epoch, EMPRISE.mtr)
glm = PySPM.GLM(y_avg, np.c_[s[:,:,0], np.ones((EMPRISE.scans_per_epoch, 1))])
b_avg= glm.OLS()
s_avg= glm.X @ b_avg
# assess statistical significance
Rsq_run = Rsq[vertex]
Rsq_avg = NumpRF.yp2Rsq(y_avg, s_avg)[0]
p = [4,2][int(cv)]
# Note: Typically, we loose 4 degrees of freedom for estimating 4
# parameters (mu, fwhm, beta, beta_0). But if tuning parameters
# (mu, fwhm) come from independent data, we only loose 2 degrees
# of freedom for estimating 2 parameters (beta, beta_0).
p_run = NumpRF.Rsq2pval(Rsq_run, EMPRISE.n, p)
p_avg = NumpRF.Rsq2pval(Rsq_avg, y_avg.size, p)
# prepare axis limits
y_min = np.min(y_avg)
y_max = np.max(y_avg)
y_rng = y_max-y_min
t_max = np.max(t)
xM = t[np.argmax(s_avg)]
yM = np.max(s_avg)
y0 = b_avg[1,0]
# plot hemodynamic signals
txt = 'beta = {:.2f}\ncvR² = {:.2f}, {}\n '. \
format(beta[vertex], Rsq_run, pvalstr(p_run))
# Note: For visualization purposes, we here apply "avg = [True, True]".
axs[k,1].plot(t, y_avg[:,0], ':ok', markerfacecolor='k', markersize=8, linewidth=1, label='measured signal')
axs[k,1].plot(t, s_avg[:,0], '-'+col, linewidth=2, label='predicted signal')
for i in range(len(ons)):
axs[k,1].plot(np.array([ons[i],ons[i]]), \
np.array([y_max+(1/20)*y_rng, y_max+(3/20)*y_rng]), '-k')
axs[k,1].text(ons[i]+(1/2)*dur[i], y_max+(2/20)*y_rng, str(stim[i]), fontsize=18,
horizontalalignment='center', verticalalignment='center')
axs[k,1].plot(np.array([ons[-1]+dur[-1],ons[-1]+dur[-1]]), \
np.array([y_max+(1/20)*y_rng, y_max+(3/20)*y_rng]), '-k')
axs[k,1].plot(np.array([ons[0],ons[-1]+dur[-1]]), \
np.array([y_max+(1/20)*y_rng, y_max+(1/20)*y_rng]), '-k')
if k == 0:
axs[k,1].plot([xM,xM], [y0,yM], '-', color='gray', linewidth=2)
axs[k,1].text(xM, (y0+yM)/2, 'beta = scaling factor', fontsize=18, \
horizontalalignment='right', verticalalignment='center', rotation=90)
axs[k,1].legend(loc='lower right', fontsize=18)
axs[k,1].axis([0, t_max, y_min-(1/20)*y_rng, y_max+(3/20)*y_rng])
if k == len(verts)-1:
axs[k,1].set_xlabel('within-cycle time [s]', fontsize=32)
axs[k,1].set_ylabel('hemodynamic signal [%]', fontsize=32)
if k == 0:
axs[k,1].set_title('presented numerosity', fontsize=32)
axs[k,1].tick_params(axis='both', labelsize=18)
axs[k,1].text((1/20)*t_max, y_min-(1/20)*y_rng, txt, fontsize=18, \
horizontalalignment='left', verticalalignment='bottom')
del y, y_reg, y_avg, z, s, s_avg, t, b_reg, b_avg, mu_k, sig_k, y_min, y_max, y_rng, txt
# return figure
return fig
# define globals
sub_visual = '003'
sub_audio = '009'
subs_all = EMPRISE.adults
model = model_def
space = 'fsnative'
# Figure 1
if Figure == '1':
# Figure 1, Part 1: visual data
fig = plot_tuning_function_time_course(sub_visual, 'visual', model, 'L', space, verts=[0,0], col='b')
fig.savefig('Figures_WP1/WP1_Figure_1_ses-visual.png', dpi=150, transparent=True)
# Figure 1, Part 2: auditory data
fig = plot_tuning_function_time_course(sub_audio, 'audio', model, 'R', space, verts=[0,0], col='r')
fig.savefig('Figures_WP1/WP1_Figure_1_ses-audio.png', dpi=150, transparent=True)
# Figure 1, Part 1: visual data (fsaverage)
fig = plot_tuning_function_time_course(sub_visual, 'visual', model, 'L', 'fsaverage', verts=[0,0], col='b')
fig.savefig('Figures_WP1/WP1_Figure_1_ses-visual_space-fsaverage.png', dpi=150, transparent=True)
# Figure 1, Part 2: auditory data (fsaverage)
fig = plot_tuning_function_time_course(sub_audio, 'audio', model, 'R', 'fsaverage', verts=[0,0], col='r')
fig.savefig('Figures_WP1/WP1_Figure_1_ses-audio_space-fsaverage.png', dpi=150, transparent=True)
# Figure S1
if Figure == 'S1':
# Figure S1: all subjects, visual
for sub in subs_all:
fig = plot_tuning_function_time_course(sub, 'visual', model, 'L', space, verts=[0], col='b')
filename = 'Figures_WP1/WP1_Figure_S1'+'_ses-'+'visual'+'_sub-'+sub+'.png'
fig.savefig(filename, dpi=150, transparent=True)
# Figure S2
if Figure == 'S2':
# Figure S2: all subjects, audio
for sub in subs_all:
fig = plot_tuning_function_time_course(sub, 'audio', model, 'R', space, verts=[0], col='r')
filename = 'Figures_WP1/WP1_Figure_S2'+'_ses-'+'audio'+'_sub-'+sub+'.png'
fig.savefig(filename, dpi=150, transparent=True)
# Figure S9
if Figure == 'S9':
# Figure S9: audio subject
model = 'True_False_iid_1_V2-lin_new'
fig = plot_tuning_function_time_course(sub_audio, 'audio', model, 'R', space, verts=[0,0], col='r')
fig.savefig('Figures_WP1/WP1_Figure_S9_ses-audio'+'_sub-'+sub_audio+'.png', dpi=150, transparent=True)
# function: Work Package 1, Figure 2
#-----------------------------------------------------------------------------#
def WP1_Fig2(Figure):
# sub-function: plot surface parameter map
#-------------------------------------------------------------------------#
def plot_surface_para(sub, ses, model, space, para='mu', cv=True, Rsq_thr=None, alpha_thr=None, meth_str=''):
# load analysis details
mod = EMPRISE.Model(sub, ses, model, space)
n = np.prod(mod.calc_runs_scans())# effective number of observations in model
p = [4,2][int(cv)] # number of explanatory variables used for R^2
# specify thresholds
if Rsq_thr is None:
if alpha_thr is None:
Rsq_thr = EMPRISE.Rsq_def
# Explanation: If "Rsq_thr" and "alpha_thr" are not specified, then "Rsq_thr" is specified.
elif Rsq_thr is not None:
if alpha_thr is not None:
Rsq_thr = None
# Explanation: If "Rsq_thr" and "alpha_thr" are both specified, then "Rsq_thr" is disspecified.
# configure thresholds # for details, see
mu_thr = EMPRISE.mu_thr # EMPRISE global variables
fwhm_thr = EMPRISE.fwhm_thr
beta_thr = EMPRISE.beta_thr
if Rsq_thr is not None:
crit = 'Rsqmb,'+ str(Rsq_thr)
elif alpha_thr is not None:
if alpha_thr < 0.001:
crit = 'Rsqmb,p='+ '{:1.2e}'.format(alpha_thr) + meth_str
else:
crit = 'Rsqmb,p='+ str(alpha_thr) + meth_str
# analyze hemispheres
hemis = {'L': 'left', 'R': 'right'}
maps = {}
for hemi in hemis.keys():
# load numerosity map
res_file = mod.get_results_file(hemi)
filepath = res_file[:res_file.find('numprf.mat')]
mu_map = filepath + 'mu.surf.gii'
NpRF = sp.io.loadmat(res_file)
image = nib.load(mu_map)
mask = image.darrays[0].data != 0
# load estimation results
mu = np.squeeze(NpRF['mu_est'])
fwhm = np.squeeze(NpRF['fwhm_est'])
beta = np.squeeze(NpRF['beta_est'])
# if CV, load cross-validated R^2
if cv:
Rsq_map = res_file[:res_file.find('numprf.mat')] + 'cvRsq.surf.gii'
cvRsq = nib.load(Rsq_map).darrays[0].data
Rsq = cvRsq[mask]
# otherwise, calculate total R^2
else:
MLL1 = np.squeeze(NpRF['MLL_est'])
MLL0 = np.squeeze(NpRF['MLL_const'])
Rsq = NumpRF.MLL2Rsq(MLL1, MLL0, n)
# prepare quantities for thresholding
ind_m = np.logical_or(mu<mu_thr[0], mu>mu_thr[1])
ind_f = np.logical_or(fwhm<fwhm_thr[0], fwhm>fwhm_thr[1])
ind_b = np.logical_or(beta<beta_thr[0], beta>beta_thr[1])
# apply conditions for exclusion
ind = mu > np.inf
if 'Rsq' in crit:
if not 'p=' in crit:
ind = np.logical_or(ind, Rsq < Rsq_thr)
else:
ind = np.logical_or(ind, ~NumpRF.Rsqsig(Rsq, n, p, alpha_thr, meth_str))
if 'm' in crit:
ind = np.logical_or(ind, ind_m)
if 'f' in crit:
ind = np.logical_or(ind, ind_f)
if 'b' in crit:
ind = np.logical_or(ind, ind_b)
# threshold parameter map
para_est = {'mu': mu, 'fwhm': fwhm, 'beta': beta, 'Rsq': Rsq}
if para == 'cvRsq': para_est['cvRsq'] = para_est.pop('Rsq')
para_map = np.nan * np.ones(mask.size, dtype=np.float32)
para_crit = para_est[para]
para_crit[ind] = np.nan
para_map[mask] = para_crit
filename = filepath + para + '_thr-' + crit + '.surf.gii'
para_img = EMPRISE.save_surf(para_map, image, filename)
maps[hemis[hemi]] = filename
del para_crit, para_map, para_est, image, filename
# specify threshold
if Rsq_thr is None: Rsq_thr = 0.0
# Explanation: If "alpha_thr" is used, set "Rsq_thr" to 0.0.
# specify plotting
if para == 'mu':
caxis = EMPRISE.mu_thr
cmap = 'gist_rainbow'
clabel = 'preferred numerosity'
cbar ={'n_ticks': 5, 'decimals': 0}
elif para == 'fwhm':
caxis = EMPRISE.fwhm_thr
cmap = 'rainbow'
clabel = 'tuning width (FWHM)'
cbar = {'n_ticks': 7, 'decimals': 0}
elif para == 'beta':
caxis = [0,5]
cmap = 'hot'
clabel = 'scaling factor'
cbar = {'n_ticks': 6, 'decimals': 0}
elif para == 'Rsq' or para == 'cvRsq':
caxis = [Rsq_thr,1]
cmap = 'hot'
if para == 'Rsq':
clabel = 'variance explained (R²)'
elif para == 'cvRsq':
clabel = 'variance explained (cvR²)'
if Rsq_thr == 0.0: # 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
cbar = {'n_ticks': 6, 'decimals': 1}
elif Rsq_thr == 0.1: # 0.1, 0.4, 0.7, 1.0
cbar = {'n_ticks': 4, 'decimals': 1}
elif Rsq_thr == 0.15: # 0.15, 0.32, 0.49, 0.66, 0.83, 1.00
cbar = {'n_ticks': 6, 'decimals': 2}
elif Rsq_thr == 0.2: # 0.2, 0.4, 0.6, 0.8, 1.0
cbar = {'n_ticks': 5, 'decimals': 1}
elif Rsq_thr == 0.25: # 0.25, 0.50, 0.75, 1.00
cbar = {'n_ticks': 4, 'decimals': 2}
elif Rsq_thr == 0.3: # 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
cbar = {'n_ticks': 8, 'decimals': 1}
else: # otherwise, five ticks and two decimals
cbar = {'n_ticks': 5, 'decimals': 2}
cbar['fontsize'] = 24
# specify mesh files
mesh_files = mod.get_mesh_files(space)
sulc_files = mod.get_sulc_files(space)
# load surface images
surf_imgs = {}
sulc_data = {}
for hemi in maps.keys():
surf_imgs[hemi] = surface.load_surf_data(maps[hemi])
sulc_data[hemi] = surface.load_surf_data(sulc_files[hemi])
sulc_data[hemi] = np.where(sulc_data[hemi]>0.0, 0.6, 0.2)
# specify surface plot
plot = Plot(mesh_files['left'], mesh_files['right'],
layout='row', views='lateral', size=(1600,600), zoom=1.5)
plot.add_layer(sulc_data, color_range=(0,1),
cmap='Greys', cbar=False)
plot.add_layer(surf_imgs, color_range=(caxis[0],caxis[1]),
cmap=cmap, cbar_label=clabel)
# display surface plot
fig = plot.build(colorbar=True, cbar_kws=cbar)
fig.tight_layout()
return fig
# sub-function: plot participant count map
#-------------------------------------------------------------------------#
def plot_participant_count(subs, ses, model, cv=True, Rsq_thr=None, alpha_thr=None, meth_str=''):
# specify thresholds
if Rsq_thr is None:
if alpha_thr is None:
Rsq_thr = EMPRISE.Rsq_def
# Explanation: If "Rsq_thr" and "alpha_thr" are not specified, then "Rsq_thr" is specified.
elif Rsq_thr is not None:
if alpha_thr is not None:
Rsq_thr = None
# Explanation: If "Rsq_thr" and "alpha_thr" are both specified, then "Rsq_thr" is disspecified.
# configure thresholds # for details, see