-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfastsrm.py
More file actions
1791 lines (1611 loc) · 65.1 KB
/
Copy pathfastsrm.py
File metadata and controls
1791 lines (1611 loc) · 65.1 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
# *- encoding: utf-8 -*-
"""Copied from private fastSRM repo by Hugo Richard"""
"""Fast Shared Response Model (FastSRM)
The implementation is based on the following publications:
.. [Richard2019] "Fast Shared Response Model for fMRI data"
H. Richard, L. Martin, A. Pinho, J. Pillow, B. Thirion, 2019
https://arxiv.org/pdf/1909.12537.pdf
"""
# Author: Hugo Richard
import hashlib
import logging
import os
import numpy as np
import scipy
from joblib import Parallel, delayed
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import NotFittedError
import uuid
__all__ = [
"FastSRM",
]
logger = logging.getLogger(__name__)
def get_safe_shape(path_or_array):
"""
Get shape of an array of saved array
"""
if isinstance(path_or_array, np.ndarray):
return path_or_array.shape
else:
return get_shape(path_or_array)
def get_shape(path):
"""Get shape of saved np array
Parameters
----------
path: str
path to np array
"""
f = open(path, "rb")
version = np.lib.format.read_magic(f)
shape, fortran_order, dtype = np.lib.format._read_array_header(f, version)
f.close()
return shape
def safe_load(data):
"""If data is an array returns data else returns np.load(data)"""
if isinstance(data, np.ndarray):
return data
else:
return np.load(data)
def safe_encode(img):
if isinstance(img, np.ndarray):
name = hashlib.md5(img.tostring()).hexdigest()
else:
name = hashlib.md5(img.encode()).hexdigest()
return name
def assert_non_empty_list(input_list, list_name):
"""
Check that input list is not empty
Parameters
----------
input_list: list
list_name: str
Name of the list
"""
if len(input_list) == 0:
raise ValueError(
"%s is a list of length 0 which is not valid" % list_name
)
def assert_array_2axis(array, name_array):
"""Check that input is an np array with 2 axes
Parameters
----------
array: np array
name_array: str
Name of the array
"""
if not isinstance(array, np.ndarray):
raise ValueError(
"%s should be of type "
"np.ndarray but is of type %s" % (name_array, type(array))
)
if len(array.shape) != 2:
raise ValueError(
"%s must have exactly 2 axes "
"but has %i axes" % (name_array, len(array.shape))
)
def assert_valid_index(indexes, max_value, name_indexes):
"""
Check that indexes are between 0 and max_value and number
of indexes is less than max_value
"""
for i, ind_i in enumerate(indexes):
if ind_i < 0 or ind_i >= max_value:
raise ValueError(
"Index %i of %s has value %i "
"whereas value should be between 0 and %i"
% (i, name_indexes, ind_i, max_value - 1)
)
def _check_imgs_list(imgs):
"""
Checks that imgs is a non empty list of elements of the same type
Parameters
----------
imgs : list
"""
# Check the list is non empty
assert_non_empty_list(imgs, "imgs")
# Check that all input have same type
for i in range(len(imgs)):
if not isinstance(imgs[i], type(imgs[0])):
raise ValueError(
"imgs[%i] has type %s whereas "
"imgs[%i] has type %s. "
"This is inconsistent." % (i, type(imgs[i]), 0, type(imgs[0]))
)
def _check_imgs_list_list(imgs):
"""
Check input images if they are list of list of arrays
Parameters
----------
imgs : list of list of array of shape [n_voxels, n_components]
imgs is a list of list of arrays where element i, j of
the array is a numpy array of shape [n_voxels, n_timeframes] that
contains the data of subject i collected during session j.
n_timeframes and n_voxels are assumed to be the same across
subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
Returns
-------
shapes: array
Shape of input images
"""
n_subjects = len(imgs)
# Check that the number of session is not 0
assert_non_empty_list(imgs[0], "imgs[%i]" % 0)
# Check that the number of sessions is the same for all subjects
n_sessions = None
for i in range(len(imgs)):
if n_sessions is None:
n_sessions = len(imgs[i])
if n_sessions != len(imgs[i]):
raise ValueError(
"imgs[%i] has length %i whereas imgs[%i] "
"has length %i. All subjects should have "
"the same number of sessions."
% (i, len(imgs[i]), 0, len(imgs[0]))
)
shapes = np.zeros((n_subjects, n_sessions, 2))
# Run array-level checks
for i in range(len(imgs)):
for j in range(len(imgs[i])):
assert_array_2axis(imgs[i][j], "imgs[%i][%i]" % (i, j))
shapes[i, j, :] = imgs[i][j].shape
return shapes
def _check_imgs_list_array(imgs):
"""
Check input images if they are list of arrays.
In this case returned images are a list of list of arrays
where element i,j of the array is a numpy array of
shape [n_voxels, n_timeframes] that contains the data of subject i
collected during session j.
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
imgs is a list of arrays where element i of the array is
a numpy array of shape [n_voxels, n_timeframes] that contains the
data of subject i (number of sessions is implicitly 1)
n_timeframes and n_voxels are assumed to be the same across
subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
Returns
-------
shapes: array
Shape of input images
new_imgs: list of list of array of shape [n_voxels, n_components]
"""
n_subjects = len(imgs)
n_sessions = 1
shapes = np.zeros((n_subjects, n_sessions, 2))
new_imgs = []
for i in range(len(imgs)):
assert_array_2axis(imgs[i], "imgs[%i]" % i)
shapes[i, 0, :] = imgs[i].shape
new_imgs.append([imgs[i]])
return new_imgs, shapes
def _check_imgs_array(imgs):
"""Check input image if it is an array
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and expected
shape is [n_voxels, n_timeframes]
n_timeframes and n_voxels are assumed to be the same across
subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
Returns
-------
shapes : array
Shape of input images
"""
assert_array_2axis(imgs, "imgs")
n_subjects, n_sessions = imgs.shape
shapes = np.zeros((n_subjects, n_sessions, 2))
for i in range(n_subjects):
for j in range(n_sessions):
if not (
isinstance(imgs[i, j], str)
or isinstance(imgs[i, j], np.str_)
or isinstance(imgs[i, j], np.str)
):
raise ValueError(
"imgs[%i, %i] is stored using "
"type %s which is not a str" % (i, j, type(imgs[i, j]))
)
shapes[i, j, :] = get_shape(imgs[i, j])
return shapes
def _check_shapes_components(n_components, n_timeframes):
"""Check that n_timeframes is greater than number of components"""
def _check_shapes_atlas_compatibility(
n_voxels, n_timeframes, n_components=None, atlas_shape=None, ignore_ncomponents=False
):
if n_components is not None:
if not ignore_ncomponents and np.sum(n_timeframes) < n_components:
raise ValueError(
"Total number of timeframes is shorter than "
"number of components (%i < %i)"
% (np.sum(n_timeframes), n_components)
)
if atlas_shape is not None:
n_supervoxels, n_atlas_voxels = atlas_shape
if n_atlas_voxels != n_voxels:
raise ValueError(
"Number of voxels in the atlas is not the same "
"as the number of voxels in input data (%i != %i)"
% (n_atlas_voxels, n_voxels)
)
def _check_shapes(
shapes, n_components=None, atlas_shape=None, ignore_nsubjects=False, ignore_ncomponents=False
):
"""Check that number of voxels is the same for each subjects. Number of
timeframes can vary between sessions but must be consistent across
subjects
Parameters
----------
shapes : array of shape (n_subjects, n_sessions, 2)
Array of shapes of input images
"""
n_subjects, n_sessions, _ = shapes.shape
if n_subjects <= 1 and not ignore_nsubjects:
raise ValueError("The number of subjects should be greater than 1")
n_timeframes_list = [None] * n_sessions
n_voxels = None
for n in range(n_subjects):
for m in range(n_sessions):
if n_timeframes_list[m] is None:
n_timeframes_list[m] = shapes[n, m, 1]
if n_voxels is None:
n_voxels = shapes[m, n, 0]
if n_timeframes_list[m] != shapes[n, m, 1]:
raise ValueError(
"Subject %i Session %i does not have the "
"same number of timeframes "
"as Subject %i Session %i" % (n, m, 0, m)
)
if n_voxels != shapes[n, m, 0]:
raise ValueError(
"Subject %i Session %i"
" does not have the same number of voxels as "
"Subject %i Session %i." % (n, m, 0, 0)
)
_check_shapes_atlas_compatibility(
n_voxels, np.sum(
n_timeframes_list), n_components, atlas_shape, ignore_ncomponents
)
def check_atlas(atlas, n_components=None):
""" Check input atlas
Parameters
----------
atlas : array, shape=[n_supervoxels, n_voxels] or array, shape=[n_voxels]
or str or None
Probabilistic or deterministic atlas on which to project the data
Deterministic atlas is an array of shape [n_voxels,] where values
range from 1 to n_supervoxels. Voxels labelled 0 will be ignored.
If atlas is a str the corresponding array is loaded with numpy.load
and expected shape is (n_voxels,) for a deterministic atlas and
(n_supervoxels, n_voxels) for a probabilistic atlas.
n_components : int
Number of timecourses of the shared coordinates
Returns
-------
shape : array or None
atlas shape
"""
if atlas is None:
return None
if not (
isinstance(atlas, np.ndarray)
or isinstance(atlas, str)
or isinstance(atlas, np.str_)
or isinstance(atlas, np.str)
):
raise ValueError(
"Atlas is stored using "
"type %s which is neither np.ndarray or str" % type(atlas)
)
if isinstance(atlas, np.ndarray):
shape = atlas.shape
else:
shape = get_shape(atlas)
if len(shape) == 1:
# We have a deterministic atlas
atlas_array = safe_load(atlas)
n_voxels = atlas_array.shape[0]
n_supervoxels = len(np.unique(atlas_array)) - 1
shape = (n_supervoxels, n_voxels)
elif len(shape) != 2:
raise ValueError(
"Atlas has %i axes. It should have either 1 or 2 axes." % len(
shape)
)
n_supervoxels, n_voxels = shape
if n_supervoxels > n_voxels:
raise ValueError(
"Number of regions in the atlas is bigger than "
"the number of voxels (%i > %i)" % (n_supervoxels, n_voxels)
)
if n_components is not None:
if n_supervoxels < n_components:
raise ValueError(
"Number of regions in the atlas is "
"lower than the number of components "
"(%i < %i)" % (n_supervoxels, n_components)
)
return shape
def check_imgs(
imgs, n_components=None, atlas_shape=None, ignore_nsubjects=False, ignore_ncomponents=False
):
"""
Check input images
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and expected
shape is [n_voxels, n_timeframes]
n_timeframes and n_voxels are assumed to be the same across
subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
imgs can also be a list of list of arrays where element i, j of
the array is a numpy array of shape [n_voxels, n_timeframes] that
contains the data of subject i collected during session j.
imgs can also be a list of arrays where element i of the array is
a numpy array of shape [n_voxels, n_timeframes] that contains the
data of subject i (number of sessions is implicitly 1)
Returns
-------
reshaped_input: bool
True if input had to be reshaped to match the
n_subjects, n_sessions input
new_imgs: list of list of array or np array
input imgs reshaped if it is a list of arrays so that it becomes a
list of list of arrays
shapes: array
Shape of input images
"""
reshaped_input = False
new_imgs = imgs
if isinstance(imgs, list):
_check_imgs_list(imgs)
if isinstance(imgs[0], list):
shapes = _check_imgs_list_list(imgs)
elif isinstance(imgs[0], np.ndarray):
new_imgs, shapes = _check_imgs_list_array(imgs)
reshaped_input = True
else:
raise ValueError(
"Since imgs is a list, it should be a list of list "
"of arrays or a list of arrays but imgs[0] has type %s"
% type(imgs[0])
)
elif isinstance(imgs, np.ndarray):
shapes = _check_imgs_array(imgs)
else:
raise ValueError(
"Input imgs should either be a list or an array but has type %s"
% type(imgs)
)
_check_shapes(shapes, n_components, atlas_shape,
ignore_nsubjects, ignore_ncomponents)
return reshaped_input, new_imgs, shapes
def check_indexes(indexes, name):
if not (
indexes is None
or isinstance(indexes, list)
or isinstance(indexes, np.ndarray)
):
raise ValueError(
"%s should be either a list, an array or None but received type %s"
% (name, type(indexes))
)
def _check_shared_response_list_of_list(
shared_response, n_components, input_shapes
):
# Check that shared_response is indeed a list of list of arrays
n_subjects = len(shared_response)
n_sessions = None
for i in range(len(shared_response)):
if not isinstance(shared_response[i], list):
raise ValueError(
"shared_response[0] is a list but "
"shared_response[%i] is not a list "
"this is incompatible." % i
)
assert_non_empty_list(shared_response[i], "shared_response[%i]" % i)
if n_sessions is None:
n_sessions = len(shared_response[i])
elif n_sessions != len(shared_response[i]):
raise ValueError(
"shared_response[%i] has len %i whereas "
"shared_response[0] has len %i. They should "
"have same length"
% (i, len(shared_response[i]), len(shared_response[0]))
)
for j in range(len(shared_response[i])):
assert_array_2axis(
shared_response[i][j], "shared_response[%i][%i]" % (i, j)
)
return _check_shared_response_list_sessions(
[
np.mean([shared_response[i][j] for i in range(n_subjects)], axis=0)
for j in range(n_sessions)
],
n_components,
input_shapes,
)
def _check_shared_response_list_sessions(
shared_response, n_components, input_shapes
):
for j in range(len(shared_response)):
assert_array_2axis(shared_response[j], "shared_response[%i]" % j)
if input_shapes is not None:
if shared_response[j].shape[1] != input_shapes[0][j][1]:
raise ValueError(
"Number of timeframes in input images during "
"session %i does not match the number of "
"timeframes during session %i "
"of shared_response (%i != %i)"
% (j, j, shared_response[j].shape[1], input_shapes[0, j, 1])
)
if n_components is not None:
if shared_response[j].shape[0] != n_components:
raise ValueError(
"Number of components in "
"shared_response during session %i is "
"different than "
"the number of components of the model (%i != %i)"
% (j, shared_response[j].shape[0], n_components)
)
return shared_response
def _check_shared_response_list_subjects(
shared_response, n_components, input_shapes
):
for i in range(len(shared_response)):
assert_array_2axis(shared_response[i], "shared_response[%i]" % i)
return _check_shared_response_array(
np.mean(shared_response, axis=0), n_components, input_shapes
)
def _check_shared_response_array(shared_response, n_components, input_shapes):
assert_array_2axis(shared_response, "shared_response")
if input_shapes is None:
new_input_shapes = None
else:
n_subjects, n_sessions, _ = input_shapes.shape
new_input_shapes = np.zeros((n_subjects, 1, 2))
new_input_shapes[:, 0, 0] = input_shapes[:, 0, 0]
new_input_shapes[:, 0, 1] = np.sum(input_shapes[:, :, 1], axis=1)
return _check_shared_response_list_sessions(
[shared_response], n_components, new_input_shapes
)
def check_shared_response(
shared_response, aggregate="mean", n_components=None, input_shapes=None
):
"""
Check that shared response has valid input and turn it into
a session-wise shared response
Returns
-------
added_session: bool
True if an artificial sessions was added to match the list of
session input type for shared_response
reshaped_shared_response: list of arrays
shared response (reshaped to match the list of session input)
"""
# Depending on aggregate and shape of input we infer what to do
if isinstance(shared_response, list):
assert_non_empty_list(shared_response, "shared_response")
if isinstance(shared_response[0], list):
if aggregate == "mean":
raise ValueError(
"self.aggregate has value 'mean' but "
"shared response is a list of list. This is "
"incompatible"
)
return (
False,
_check_shared_response_list_of_list(
shared_response, n_components, input_shapes
),
)
elif isinstance(shared_response[0], np.ndarray):
if aggregate == "mean":
return (
False,
_check_shared_response_list_sessions(
shared_response, n_components, input_shapes
),
)
else:
return (
True,
_check_shared_response_list_subjects(
shared_response, n_components, input_shapes
),
)
else:
raise ValueError(
"shared_response is a list but "
"shared_response[0] is neither a list "
"or an array. This is invalid."
)
elif isinstance(shared_response, np.ndarray):
return (
True,
_check_shared_response_array(
shared_response, n_components, input_shapes
),
)
else:
raise ValueError(
"shared_response should be either "
"a list or an array but is of type %s" % type(shared_response)
)
def create_temp_dir(temp_dir):
"""
This check whether temp_dir exists and creates dir otherwise
"""
if temp_dir is None:
return None
if not os.path.exists(temp_dir):
os.makedirs(temp_dir)
else:
raise ValueError(
"Path %s already exists. "
"When a model is used, filesystem should be cleaned "
"by using the .clean() method" % temp_dir
)
def reduce_data_single(
subject_index,
session_index,
img,
atlas=None,
inv_atlas=None,
low_ram=False,
temp_dir=None,
):
"""Reduce data using given atlas
Parameters
----------
subject_index : int
session_index : int
img : str or array
path to data.
Data are loaded with numpy.load and expected shape is
(n_voxels, n_timeframes)
n_timeframes and n_voxels are assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
img can also be an array of shape (n_voxels, n_timeframes)
atlas : array, shape=[n_supervoxels, n_voxels] or [n_voxels] or None
Probabilistic or deterministic atlas on which to project the data
Deterministic atlas is an array of shape [n_voxels,] where values
range from 1 to n_supervoxels. Voxels labelled 0 will be ignored.
inv_atlas : array, shape=[n_voxels, n_supervoxels] or None
Pseudo inverse of the atlas (only for probabilistic atlases)
temp_dir : str or None
path to dir where temporary results are stored
if None temporary results will be stored in memory. This
can results in memory errors when the number of subjects
and / or sessions is large
low_ram : bool
if True and temp_dir is not None, reduced_data will be saved on disk
this increases the number of IO but reduces memory complexity when the
number
of subject and number of sessions are large
Returns
-------
reduced_data : array, shape=[n_timeframes, n_supervoxels]
reduced data
"""
# Here we return to the conventions of the paper
data = safe_load(img).T
n_timeframes, n_voxels = data.shape
# Here we check that input is normalized
if (
np.max(np.abs(np.mean(data, axis=0))) > 1e-6
or np.max(np.abs(np.var(data, axis=0) - 1))
) > 1e-6:
ValueError(
"Data in imgs[%i, %i] does not have 0 mean and unit \
variance. If you are using NiftiMasker to mask your data \
(nilearn) please use standardize=True."
% (subject_index, session_index)
)
if inv_atlas is None and atlas is not None:
atlas_values = np.unique(atlas)
if 0 in atlas_values:
atlas_values = atlas_values[1:]
reduced_data = np.array(
[np.mean(data[:, atlas == c], axis=1) for c in atlas_values]
).T
elif inv_atlas is not None and atlas is None:
# this means that it is a probabilistic atlas
reduced_data = data.dot(inv_atlas)
else:
reduced_data = data
if low_ram:
name = safe_encode(img)
path = os.path.join(temp_dir, "reduced_data_" + name)
np.save(path, reduced_data)
return path + ".npy"
else:
return reduced_data
def reduce_data(imgs, atlas, n_jobs=1, low_ram=False, temp_dir=None):
"""Reduce data using given atlas.
Work done in parallel across subjects.
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and expected shape is
[n_timeframes, n_voxels]
n_timeframes and n_voxels are assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
imgs can also be a list of list of arrays where element i, j of
the array is a numpy array of shape [n_voxels, n_timeframes] that
contains the data of subject i collected during session j.
imgs can also be a list of arrays where element i of the array is
a numpy array of shape [n_voxels, n_timeframes] that contains the
data of subject i (number of sessions is implicitly 1)
atlas : array, shape=[n_supervoxels, n_voxels] or array, shape=[n_voxels]
or None
Probabilistic or deterministic atlas on which to project the data
Deterministic atlas is an array of shape [n_voxels,] where values
range from 1 to n_supervoxels. Voxels labelled 0 will be ignored.
n_jobs : integer, optional, default=1
The number of CPUs to use to do the computation.
-1 means all CPUs, -2 all CPUs but one, and so on.
temp_dir : str or None
path to dir where temporary results are stored
if None temporary results will be stored in memory. This
can results in memory errors when the number of subjects
and / or sessions is large
low_ram : bool
if True and temp_dir is not None, reduced_data will be saved on disk
this increases the number of IO but reduces memory complexity when
the number of subject and/or sessions is large
Returns
-------
reduced_data_list : array of str, shape=[n_subjects, n_sessions]
or array, shape=[n_subjects, n_sessions, n_timeframes, n_supervoxels]
Element i, j of the array is a path to the data of subject i collected
during session j.
Data are loaded with numpy.load and expected shape is
[n_timeframes, n_supervoxels]
or Element i, j of the array is the data in array of
shape=[n_timeframes, n_supervoxels]
n_timeframes and n_supervoxels
are assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
"""
if atlas is None:
A = None
A_inv = None
else:
loaded_atlas = safe_load(atlas)
if len(loaded_atlas.shape) == 2:
A = None
A_inv = loaded_atlas.T.dot(
np.linalg.inv(loaded_atlas.dot(loaded_atlas.T))
)
else:
A = loaded_atlas
A_inv = None
n_subjects = len(imgs)
n_sessions = len(imgs[0])
reduced_data_list = Parallel(n_jobs=n_jobs)(
delayed(reduce_data_single)(
i,
j,
imgs[i][j],
atlas=A,
inv_atlas=A_inv,
low_ram=low_ram,
temp_dir=temp_dir,
)
for i in range(n_subjects)
for j in range(n_sessions)
)
if low_ram:
reduced_data_list = np.reshape(
reduced_data_list, (n_subjects, n_sessions)
)
else:
if len(np.array(reduced_data_list).shape) == 1:
reduced_data_list = np.reshape(
reduced_data_list, (n_subjects, n_sessions)
)
else:
n_timeframes, n_supervoxels = np.array(reduced_data_list).shape[1:]
reduced_data_list = np.reshape(
reduced_data_list,
(n_subjects, n_sessions, n_timeframes, n_supervoxels),
)
return reduced_data_list
def _reduced_space_compute_shared_response(
reduced_data_list, reduced_basis_list, n_components=50, transpose=False, seed=0
):
"""Compute shared response with basis fixed in reduced space
Parameters
----------
reduced_data_list : array of str, shape=[n_subjects, n_sessions]
or array, shape=[n_subjects, n_sessions, n_timeframes, n_supervoxels]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and expected shape is
[n_timeframes, n_supervoxels]
or Element i, j of the array is the data in array of
shape=[n_timeframes, n_supervoxels]
n_timeframes and n_supervoxels are
assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
reduced_basis_list : None or list of array, element i has
shape=[n_components, n_supervoxels]
each subject's reduced basis
if None the basis will be generated on the fly
n_components : int or None
number of components
Returns
-------
shared_response_list : list of array, element i has
shape=[n_timeframes, n_components]
shared response, element i is the shared response during session i
"""
n_subjects = len(reduced_data_list)
n_sessions = len(reduced_data_list[0])
if transpose:
n_supervoxels, n_timeframes = get_safe_shape(reduced_data_list[0][0])
else:
n_timeframes, n_supervoxels = get_safe_shape(reduced_data_list[0][0])
s = [None] * n_sessions
# This is just to check that all subjects have same number of
# timeframes in a given session
random_state = np.random.RandomState(seed)
for n in range(n_subjects):
if reduced_basis_list is None:
basis_n = np.linalg.qr(random_state.random_sample(
(n_supervoxels, n_components)))[0].T
else:
basis_n = safe_load(reduced_basis_list[n])
for m in range(n_sessions):
if transpose:
data_nm = safe_load(reduced_data_list[n][m]).T
else:
data_nm = safe_load(reduced_data_list[n][m])
if s[m] is None:
s[m] = data_nm.dot(basis_n.T)
else:
s[m] = s[m] + data_nm.dot(basis_n.T)
for m in range(n_sessions):
s[m] = s[m] / float(n_subjects)
return s
def _compute_and_save_corr_mat(img, shared_response, temp_dir):
"""computes correlation matrix and stores it
Parameters
----------
img : str
path to data.
Data are loaded with numpy.load and expected shape is
[n_timeframes, n_voxels]
n_timeframes and n_voxels are assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
shared_response : array, shape=[n_timeframes, n_components]
shared response
"""
data = safe_load(img).T
name = safe_encode(img)
path = os.path.join(temp_dir, "corr_mat_" + name)
np.save(path, shared_response.T.dot(data))
def _compute_and_save_subject_basis(subject_number, sessions, temp_dir):
"""computes correlation matrix for all sessions
Parameters
----------
subject_number: int
Number that identifies the subject. Basis will be stored in
[temp_dir]/basis_[subject_number].npy
sessions : array of str
Element i of the array is a path to the data collected during
session i.
Data are loaded with numpy.load and expected shape is
[n_timeframes, n_voxels]
n_timeframes and n_voxels are assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance
temp_dir : str or None
path to dir where temporary results are stored
if None temporary results will be stored in memory. This
can results in memory errors when the number of subjects
and / or sessions is large
Returns
-------
basis: array, shape=[n_component, n_voxels] or str
basis of subject [subject_number] or path to this basis
"""
corr_mat = None
for session in sessions:
name = safe_encode(session)
path = os.path.join(temp_dir, "corr_mat_" + name + ".npy")
if corr_mat is None:
corr_mat = np.load(path)
else:
corr_mat += np.load(path)
os.remove(path)
basis_i = _compute_subject_basis(corr_mat)
path = os.path.join(temp_dir, "basis_%i" % subject_number)
np.save(path, basis_i)
return path + ".npy"
def _compute_subject_basis(corr_mat):
"""From correlation matrix between shared response and subject data,
Finds subject's basis
Parameters
----------
corr_mat: array, shape=[n_component, n_voxels]
or shape=[n_components, n_supervoxels]
correlation matrix between shared response and subject data or
subject reduced data
element k, v is given by S.T.dot(X_i) where S is the shared response
and X_i the data of subject i.
Returns
-------
basis: array, shape=[n_components, n_voxels]
or shape=[n_components, n_supervoxels]
basis of subject or reduced_basis of subject
"""
U, _, V = scipy.linalg.svd(corr_mat, full_matrices=False)
return U.dot(V)
def fast_srm(
reduced_data_list, n_iter=10, n_components=None, low_ram=False,
):
"""Computes shared response and basis in reduced space
Parameters
----------
reduced_data_list : array, shape=[n_subjects, n_sessions]
or array, shape=[n_subjects, n_sessions, n_timeframes, n_supervoxels]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded with numpy.load and expected
shape is [n_timeframes, n_supervoxels]
or Element i, j of the array is the data in array of
shape=[n_timeframes, n_supervoxels]
n_timeframes and n_supervoxels are
assumed to be the same across subjects
n_timeframes can vary across sessions
Each voxel's timecourse is assumed to have mean 0 and variance 1
n_iter : int
Number of iterations performed
n_components : int or None
number of components
Returns
-------
shared_response_list : list of array, element i has
shape=[n_timeframes, n_components]