dingliyu commited on
Commit
3641763
1 Parent(s): 0f41f55

Upload fMRI-openneuro.py

Browse files
Files changed (1) hide show
  1. fMRI-openneuro.py +157 -0
fMRI-openneuro.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import nibabel as nib
2
+ import os
3
+ import numpy as np
4
+
5
+ import datasets
6
+
7
+ import boto3
8
+
9
+
10
+ _DESCRIPTION = """\
11
+ fMIR dataset from openneuro.org
12
+ """
13
+
14
+ class fMRIConfig(datasets.BuilderConfig):
15
+ """Builder Config for fMRI"""
16
+
17
+ def __init__(self, data_url, num_datasets=[10, 1, 1], num_frames=8, sampling_rate=1, **kwargs):
18
+ """BuilderConfig for fMRI.
19
+ Args:
20
+ data_url: `string`, url to download the zip file from.
21
+ **kwargs: keyword arguments forwarded to super.
22
+ """
23
+ super(fMRIConfig, self).__init__(**kwargs)
24
+ self.data_url = data_url
25
+ self.num_datasets = num_datasets
26
+ self.num_frames = num_frames
27
+ self.sampling_rate = sampling_rate
28
+
29
+ class fMRITest(datasets.GeneratorBasedBuilder):
30
+ """TODO: Short description of my dataset."""
31
+
32
+ VERSION = datasets.Version("1.0.0")
33
+
34
+ # This is an example of a dataset with multiple configurations.
35
+ # If you don't want/need to define several sub-sets in your dataset,
36
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
37
+
38
+ # If you need to make complex sub-parts in the datasets with configurable options
39
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
40
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
41
+
42
+ # You will be able to load one or the other configurations in the following list with
43
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
44
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
45
+ BUILDER_CONFIGS = [
46
+ fMRIConfig(name="test1", data_url="openneuro.org", version=VERSION, description="fMRI test dataset 1", ),
47
+ ]
48
+
49
+ DEFAULT_CONFIG_NAME = "test1" # It's not mandatory to have a default configuration. Just use one if it make sense.
50
+
51
+
52
+ def _info(self):
53
+ # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
54
+ if self.config.name == "test1": # This is the name of the configuration selected in BUILDER_CONFIGS above
55
+ # features = datasets.Features(
56
+ # {
57
+ # # "func": np.ndarray(shape=(65,77,65,self.config.duration)),
58
+ # "func": datasets.Array4D(shape=(None,None,None,self.config.duration), dtype='float32'),
59
+ # }
60
+ # )
61
+ features = None
62
+ return datasets.DatasetInfo(
63
+ # This is the description that will appear on the datasets page.
64
+ description=_DESCRIPTION,
65
+ # This defines the different columns of the dataset and their types
66
+ features=features, # Here we define them above because they are different between the two configurations
67
+ # If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
68
+ # specify them. They'll be used if as_supervised=True in builder.as_dataset.
69
+ # supervised_keys=("sentence", "label"),
70
+ )
71
+
72
+ def _split_generators(self, dl_manager):
73
+
74
+ # Connect to S3
75
+ s3 = boto3.client('s3')
76
+
77
+ bucket_name = self.config.data_url
78
+
79
+ response = s3.list_objects_v2(Bucket=bucket_name, Prefix='', Delimiter='/')
80
+
81
+ folder_names = [x['Prefix'].split('/')[-2] for x in response.get('CommonPrefixes', [])]
82
+ print(len(folder_names))
83
+
84
+ ndatasets = self.config.num_datasets
85
+ if isinstance(ndatasets, int):
86
+ ndatasets = [ndatasets, 10, 10]
87
+
88
+ return [
89
+ datasets.SplitGenerator(
90
+ name=datasets.Split.TRAIN,
91
+ # These kwargs will be passed to _generate_examples
92
+ gen_kwargs={
93
+ "bucket_name": bucket_name,
94
+ "folder_names": folder_names[:ndatasets[0]],
95
+ },
96
+ ),
97
+ datasets.SplitGenerator(
98
+ name=datasets.Split.VALIDATION,
99
+ # These kwargs will be passed to _generate_examples
100
+ gen_kwargs={
101
+ "bucket_name": bucket_name,
102
+ "folder_names": folder_names[ndatasets[0]:ndatasets[0] + ndatasets[1]],
103
+ },
104
+ ),
105
+ datasets.SplitGenerator(
106
+ name=datasets.Split.TEST,
107
+ # These kwargs will be passed to _generate_examples
108
+ gen_kwargs={
109
+ "bucket_name": bucket_name,
110
+ "folder_names": folder_names[ndatasets[0] + ndatasets[1]:ndatasets[0] + ndatasets[1] + ndatasets[2]],
111
+ },
112
+ ),
113
+ ]
114
+
115
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
116
+ def _generate_examples(self, bucket_name, folder_names):
117
+ # TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
118
+ # The `key` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
119
+ s3 = boto3.client('s3')
120
+ tmp_dir = os.path.join('tmp', folder_names[0]) if len(folder_names) > 0 else 'tmp'
121
+ if not os.path.exists(tmp_dir):
122
+ os.makedirs(tmp_dir)
123
+ anat_file = os.path.join(tmp_dir, 'T1w.nii.gz')
124
+ func_file = os.path.join(tmp_dir, 'bold.nii.gz')
125
+
126
+ duration = self.config.num_frames * self.config.sampling_rate
127
+
128
+ for folder_name in folder_names:
129
+ response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_name)
130
+ for obj in response.get('Contents', []):
131
+ obj_key = obj['Key']
132
+ if '_T1w.nii.gz' in obj_key: # Anatomical
133
+ # Store subject number to verify anat/func match
134
+ anat_subj = obj_key.split('/')[1]
135
+
136
+ # Download the object to tmp location
137
+ s3.download_file(bucket_name, obj_key, anat_file)
138
+
139
+ # store the head of anat_subj
140
+ anat_header = nib.load(anat_file).header
141
+ elif '_bold.nii.gz' in obj_key: # Functional
142
+ func_subj = obj_key.split('/')[1]
143
+ if func_subj == anat_subj:
144
+ s3.download_file(bucket_name, obj_key, func_file)
145
+ func = nib.load(func_file).get_fdata().astype('float16')
146
+ func = np.transpose(func, (3, 0, 1, 2)) # T, X, Y, Z
147
+ shape = func.shape
148
+ # print(f"{obj_key}", shape)
149
+ for i in range(0, shape[0] - duration + self.config.sampling_rate, duration):
150
+ func_slice = func[i:i+duration:self.config.sampling_rate, :, :, :]
151
+ # print(f"{obj_key}-{i}", func_slice.shape)
152
+ yield f"{obj_key}-{i}", {
153
+ "func": func_slice,
154
+ }
155
+
156
+
157
+