-
Notifications
You must be signed in to change notification settings - Fork 12
/
nsda.py
381 lines (322 loc) · 15.9 KB
/
nsda.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import os
import os.path as op
import glob
import nibabel as nb
import numpy as np
import pandas as pd
import h5py
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import urllib.request
import zipfile
from pycocotools.coco import COCO
from IPython import embed
class NSDAccess(object):
"""
Little class that provides easy access to the NSD data, see [http://naturalscenesdataset.org](their website)
"""
def __init__(self, nsd_folder, *args, **kwargs):
super().__init__(*args, **kwargs)
self.nsd_folder = nsd_folder
self.nsddata_folder = op.join(self.nsd_folder, 'nsddata')
self.ppdata_folder = op.join(self.nsd_folder, 'nsddata', 'ppdata')
self.nsddata_betas_folder = op.join(
self.nsd_folder, 'nsddata_betas', 'ppdata')
self.behavior_file = op.join(
self.ppdata_folder, '{subject}', 'behav', 'responses.tsv')
self.stimuli_file = op.join(
self.nsd_folder, 'nsddata_stimuli', 'stimuli', 'nsd', 'nsd_stimuli.hdf5')
self.stimuli_description_file = op.join(
self.nsd_folder, 'nsddata', 'experiments', 'nsd', 'nsd_stim_info_merged.csv')
self.coco_annotation_file = op.join(
self.nsd_folder, 'nsddata_stimuli', 'stimuli', 'nsd', 'annotations', '{}_{}.json')
def download_coco_annotation_file(self, url='http://images.cocodataset.org/annotations/annotations_trainval2017.zip'):
"""download_coco_annotation_file downloads and extracts the relevant annotations files
Parameters
----------
url : str, optional
url for zip file containing annotations, by default 'http://images.cocodataset.org/annotations/annotations_trainval2017.zip'
"""
print('downloading annotations from {}'.format(url))
filehandle, _ = urllib.request.urlretrieve(url)
zip_file_object = zipfile.ZipFile(filehandle, 'r')
zip_file_object.extractall(path=op.split(
op.split(self.coco_annotation_file)[0])[0])
def affine_header(self, subject, data_format='func1pt8mm'):
"""affine_header affine and header, for construction of Nifti image
Parameters
----------
subject : str
subject identifier, such as 'subj01'
data_format : str, optional
what type of data format, from ['func1pt8mm', 'func1mm'], by default 'func1pt8mm'
Returns
-------
tuple
affine and header, for construction of Nifti image
"""
full_path = op.join(self.ppdata_folder, '{subject}', '{data_format}', 'brainmask.nii.gz')
full_path = full_path.format(subject=subject,
data_format=data_format)
nii = nb.load(full_path)
return nii.affine, nii.header
def read_vol_ppdata(self, subject, filename='brainmask', data_format='func1pt8mm'):
"""load_brainmask, returns boolean brainmask for volumetric data formats
Parameters
----------
subject : str
subject identifier, such as 'subj01'
data_format : str, optional
what type of data format, from ['func1pt8mm', 'func1mm'], by default 'func1pt8mm'
Returns
-------
numpy.ndarray, 4D (bool)
brain mask array
"""
full_path = op.join(self.ppdata_folder, '{subject}', '{data_format}', '{filename}.nii.gz')
full_path = full_path.format(subject=subject,
data_format=data_format,
filename=filename)
return nb.load(full_path).get_data()
def read_betas(self, subject, session_index, trial_index=[], data_type='betas_fithrf_GLMdenoise_RR', data_format='fsaverage', mask=None):
"""read_betas read betas from MRI files
Parameters
----------
subject : str
subject identifier, such as 'subj01'
session_index : int
which session, counting from 0
trial_index : list, optional
which trials from this session's file to return, by default [], which returns all trials
data_type : str, optional
which type of beta values to return from ['betas_assumehrf', 'betas_fithrf', 'betas_fithrf_GLMdenoise_RR', 'restingbetas_fithrf'], by default 'betas_fithrf_GLMdenoise_RR'
data_format : str, optional
what type of data format, from ['fsaverage', 'func1pt8mm', 'func1mm'], by default 'fsaverage'
mask : numpy.ndarray, if defined, selects 'mat' data_format, needs volumetric data_format
binary/boolean mask into mat file beta data format.
Returns
-------
numpy.ndarray, 2D (fsaverage) or 4D (other data formats)
the requested per-trial beta values
"""
data_folder = op.join(self.nsddata_betas_folder,
subject, data_format, data_type)
si_str = str(session_index).zfill(2)
if type(mask) == np.ndarray: # will use the mat file iff exists, otherwise boom!
ipf = op.join(data_folder, f'betas_session{si_str}.mat')
assert op.isfile(ipf), \
'Error: ' + ipf + ' not available for masking. You may need to download these separately.'
# will do indexing of both space and time in one go for this option,
# so will return results immediately from this
h5 = h5py.File(ipf, 'r')
betas = h5.get('betas')
# embed()
if len(trial_index) == 0:
trial_index = slice(0, betas.shape[0])
# this isn't finished yet - binary masks cannot be used for indexing like this
return betas[trial_index, np.nonzero(mask)]
if data_format == 'fsaverage':
session_betas = []
for hemi in ['lh', 'rh']:
hdata = nb.load(op.join(
data_folder, f'{hemi}.betas_session{si_str}.mgz')).get_data()
session_betas.append(hdata)
out_data = np.squeeze(np.vstack(session_betas))
else:
# if no mask was specified, we'll use the nifti image
out_data = nb.load(op.join(data_folder, f'betas_session{si_str}.nii.gz')).get_data()
if len(trial_index) == 0:
trial_index = slice(0, out_data.shape[-1])
return out_data[..., trial_index]
def read_mapper_results(self, subject, mapper='prf', data_type='angle', data_format='fsaverage'):
"""read_mapper_results [summary]
Parameters
----------
subject : str
subject identifier, such as 'subj01'
mapper : str, optional
first part of the mapper filename, by default 'prf'
data_type : str, optional
second part of the mapper filename, by default 'angle'
data_format : str, optional
what type of data format, from ['fsaverage', 'func1pt8mm', 'func1mm'], by default 'fsaverage'
Returns
-------
numpy.ndarray, 2D (fsaverage) or 4D (other data formats)
the requested mapper values
"""
if data_format == 'fsaverage':
# unclear for now where the fsaverage mapper results would be
# as they are still in fsnative format now.
raise NotImplementedError('no mapper results in fsaverage present for now')
else: # is 'func1pt8mm' or 'func1mm'
return self.read_vol_ppdata(subject=subject, filename=f'{mapper}_{data_type}', data_format=data_format)
def read_atlas_results(self, subject, atlas='HCP_MMP1', data_format='fsaverage'):
"""read_atlas_results [summary]
Parameters
----------
subject : str
subject identifier, such as 'subj01'
for surface-based data formats, subject should be the same as data_format.
for example, for fsaverage, both subject and data_format should be 'fsaverage'
this requires a little more typing but makes data format explicit
atlas : str, optional
which atlas to read,
for volume formats, any of ['HCP_MMP1', 'Kastner2015', 'nsdgeneral', 'visualsulc'] for volume,
for fsaverage
can be prefixed by 'lh.' or 'rh.' for hemisphere-specific atlases in volume
for surface: takes both hemispheres by default, instead when prefixed by '.rh' or '.lh'.
By default 'HCP_MMP1'.
data_format : str, optional
what type of data format, from ['fsaverage', 'func1pt8mm', 'func1mm', 'MNI'], by default 'fsaverage'
Returns
-------
numpy.ndarray, 1D/2D (surface) or 3D/4D (volume data formats)
the requested atlas values
dict,
dictionary containing the mapping between ROI names and atlas values
"""
# first, get the mapping.
atlas_name = atlas
if atlas[:3] in ('rh.', 'lh.'):
atlas_name = atlas[3:]
mapp_df = pd.read_csv(os.path.join(self.nsddata_folder, 'freesurfer', 'fsaverage', 'label', f'{atlas_name}.mgz.ctab'), delimiter=' ', header=None, index_col=0)
atlas_mapping = mapp_df.to_dict()[1]
atlas_mapping = {y:x for x,y in atlas_mapping.items()} # dict((y,x) for x,y in atlas_mapping.iteritems())
if data_format not in ('func1pt8mm', 'func1mm', 'MNI'):
# if surface based results by exclusion
if atlas[:3] in ('rh.', 'lh.'): # check if hemisphere-specific atlas requested
ipf = op.join(self.nsddata_folder, 'freesurfer', subject, 'label', f'{atlas}.mgz')
return np.squeeze(nb.load(ipf).get_data()), atlas_mapping
else: # more than one hemisphere requested
session_betas = []
for hemi in ['lh', 'rh']:
hdata = nb.load(op.join(
self.nsddata_folder, 'freesurfer', subject, 'label', f'{hemi}.{atlas}.mgz')).get_data()
session_betas.append(hdata)
out_data = np.squeeze(np.vstack(session_betas))
return out_data, atlas_mapping
else: # is 'func1pt8mm', 'MNI', or 'func1mm'
ipf = op.join(self.ppdata_folder, subject, data_format, 'roi', f'{atlas}.nii.gz')
return nb.load(ipf).get_data(), atlas_mapping
def list_atlases(self, subject, data_format='fsaverage', abs_paths=False):
"""list_atlases [summary]
Parameters
----------
subject : str
subject identifier, such as 'subj01'
for surface-based data formats, subject should be the same as data_format.
for example, for fsaverage, both subject and data_format should be 'fsaverage'
this requires a little more typing but makes data format explicit
data_format : str, optional
what type of data format, from ['fsaverage', 'func1pt8mm', 'func1mm', 'MNI'], by default 'fsaverage'
Returns
-------
list
collection of absolute path names to
"""
if data_format in ('func1pt8mm', 'func1mm', 'MNI'):
atlas_files = glob.glob(op.join(self.ppdata_folder, subject, data_format, 'roi', '*.nii.gz'))
else:
atlas_files = glob.glob(op.join(self.nsddata_folder, 'freesurfer', subject, 'label', '*.mgz'))
# print this
import pprint
pp = pprint.PrettyPrinter(indent=4)
print('Atlases found in {}:'.format(op.split(atlas_files[0])[0]))
pp.pprint([op.split(f)[1] for f in atlas_files])
if abs_paths:
return atlas_files
else: # this is the format which you can input into other functions, so this is the default
return np.unique([op.split(f)[1].replace('lh.','').replace('rh.','').replace('.mgz','').replace('.nii.gz','') for f in atlas_files])
def read_behavior(self, subject, session_index, trial_index=[]):
"""read_behavior [summary]
Parameters
----------
subject : str
subject identifier, such as 'subj01'
session_index : int
which session, counting from 0
trial_index : list, optional
which trials from this session's behavior to return, by default [], which returns all trials
Returns
-------
pandas DataFrame
DataFrame containing the behavioral information for the requested trials
"""
behavior = pd.read_csv(self.behavior_file.format(
subject=subject), delimiter='\t')
# the behavior is encoded per run.
# I'm now setting this function up so that it aligns with the timepoints in the fmri files,
# i.e. using indexing per session, and not using the 'run' information.
session_behavior = behavior[behavior['SESSION'] == session_index]
if len(trial_index) == 0:
trial_index = slice(0, len(session_behavior))
return session_behavior.iloc[trial_index]
def read_images(self, image_index, show=False):
"""read_images reads a list of images, and returns their data
Parameters
----------
image_index : list of integers
which images indexed in the 73k format to return
show : bool, optional
whether to also show the images, by default False
Returns
-------
numpy.ndarray, 3D
RGB image data
"""
if not hasattr(self, 'stim_descriptions'):
self.stim_descriptions = pd.read_csv(
self.stimuli_description_file, index_col=0)
sf = h5py.File(self.stimuli_file, 'r')
sdataset = sf.get('imgBrick')
if show:
f, ss = plt.subplots(1, len(image_index),
figsize=(6*len(image_index), 6))
if len(image_index) == 1:
ss = [ss]
for s, d in zip(ss, sdataset[image_index]):
s.axis('off')
s.imshow(d)
return sdataset[image_index]
def read_image_coco_info(self, image_index, info_type='captions', show_annot=False, show_img=False):
"""image_coco_info returns the coco annotations of a given single image
Parameters
----------
image_index : integer
index to image in 73k format
info_type : str, optional
what type of annotation to return, from ['captions', 'person_keypoints', 'instances'], by default 'captions'
show_annot : bool, optional
whether to show the annotation, by default False
show_img : bool, optional
whether to show the image (from the nsd formatted data), by default False
Returns
-------
coco Annotation
coco annotation, to be used in subsequent analysis steps
"""
if not hasattr(self, 'stim_descriptions'):
self.stim_descriptions = pd.read_csv(
self.stimuli_description_file, index_col=0)
subj_info = self.stim_descriptions.iloc[image_index]
# checking whether annotation file for this trial exists.
# This may not be the right place to call the download, and
# re-opening the annotations for all images separately may be slowing things down
# however images used in the experiment seem to have come from different sets.
annot_file = self.coco_annotation_file.format(
info_type, subj_info['cocoSplit'])
print('getting annotations from ' + annot_file)
if not os.path.isfile(annot_file):
print('annotations file not found')
self.download_coco_annotation_file()
coco = COCO(annot_file)
coco_annot_IDs = coco.getAnnIds([subj_info['cocoId']])
coco_annot = coco.loadAnns(coco_annot_IDs)
if show_img:
self.read_images([image_index], show=True)
if show_annot:
# still need to convert the annotations (especially person_keypoints and instances) to the right reference frame,
# because the images were cropped. See image information per image to do this.
coco.showAnns(coco_annot)
return coco_annot