-
Notifications
You must be signed in to change notification settings - Fork 1
/
explore_dataset.py
194 lines (147 loc) · 5.59 KB
/
explore_dataset.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
import h5py
from pathlib import Path
import sys
import lxml
import lxml.etree
from copy import copy
# Point to directory where your fastmri train and validation data is
traindir = Path('./fastmri/brain/multicoil_train')
valdir = Path('./fastmri/brain/multicoil_val')
# Describe scan type we want to filter
match = {'scantype': 'T1POST',
'shape_phase': 320,
'shape_read': 640,
'B0': 2.8936,
'TR': '250',
'TE': '2.64',
'TI': '300',
'flipAngle_deg': '70',
'sequence_type': 'Flash'}
# Set match to empty dictionary to match every scan and see full range of parameters to filter on
# match = {}
# Coil elements to use
coils = ['HeadNeck_20:1:H11',
'HeadNeck_20:1:H12',
'HeadNeck_20:1:H13',
'HeadNeck_20:1:H14',
'HeadNeck_20:1:H21',
'HeadNeck_20:1:H22',
'HeadNeck_20:1:H23',
'HeadNeck_20:1:H24',
'HeadNeck_20:1:H31',
'HeadNeck_20:1:H32',
'HeadNeck_20:1:H33',
'HeadNeck_20:1:H34',
'HeadNeck_20:1:H41',
'HeadNeck_20:1:H42',
'HeadNeck_20:1:H43',
'HeadNeck_20:1:H44']
# Set coils to None to not select for coil and see all elements present in the matched scans
# coils = None
#%%
def dictify(r,root=True):
if root:
return {r.tag : dictify(r, False)}
d=copy(r.attrib)
if r.text and r.text.strip() != '':
d["_text"] = r.text
for x in r.findall("./*"):
if x.tag not in d:
d[x.tag] = []
d[x.tag].append(dictify(x,False))
for x in d:
if isinstance(d[x], list) and len(d[x]) == 1:
d[x] = d[x][0]
if len(list(d.keys())) == 1 and list(d.keys())[0] == '_text':
return d['_text']
return d
#%% Iterate through all fastMRI file and get relevant scan parameters
parameters = []
files = sorted(list(traindir.glob('*.h5')) + list(valdir.glob('*.h5')))
from tqdm.auto import tqdm
for file in tqdm(files, file=sys.stdout):
pars = {}
pars['filename'] = file
if str(file).find('AXFLAIR') != -1:
pars['scantype'] = 'FLAIR'
elif str(file).find('AXT1POST') != -1:
pars['scantype'] = 'T1POST'
# # Uncomment to put T1PRE scans into a separate set (otherwise it's combined with AXT1)
# elif str(file).find('AXT1PRE') != -1:
# pars['scantype'] = 'T1PRE'
elif str(file).find('AXT1') != -1:
pars['scantype'] = 'T1'
elif str(file).find('AXT2') != -1:
pars['scantype'] = 'T2'
else:
raise RuntimeError('Unknown scan type')
with h5py.File(file, 'r') as f:
root = lxml.etree.fromstring(f['ismrmrd_header'][()])
for elem in root.getiterator():
elem.tag = lxml.etree.QName(elem).localname
pars['shape'] = f['kspace'].shape # slice, coils,read, phase
pars['shape_slice'] = f['kspace'].shape[0]
pars['shape_phase'] = f['kspace'].shape[3]
pars['shape_read'] = f['kspace'].shape[2]
d = dictify(root)
pars['B0'] = float(d['ismrmrdHeader']['acquisitionSystemInformation']['systemFieldStrength_T'])
if any(x in pars for x in d['ismrmrdHeader']['sequenceParameters']):
raise RuntimeError('Double parameter')
for x in d['ismrmrdHeader']['sequenceParameters']:
pars[x] = d['ismrmrdHeader']['sequenceParameters'][x]
# Skip data with less than 8 receive channels
if int(d['ismrmrdHeader']['acquisitionSystemInformation']['receiverChannels']) < 8:
continue
parameters.append(pars)
#%% Select files that match the requested scan parameters
files_filtered = []
parameter_range = {}
for x in parameters:
if all(k in x and x[k] == match[k] for k in match):
files_filtered.append(x['filename'])
for k in x:
if k == 'filename':
continue
if k not in parameter_range:
parameter_range[k] = set([x[k]])
parameter_range[k] |= set([x[k]])
print('Parameter ranges:')
for k,v in parameter_range.items():
print(f' {k}:', sorted(list(v)))
#%% Select files that include the requested coils (if specified)
files_filtered2 = []
for file in files_filtered:
with h5py.File(file, 'r') as f:
root = lxml.etree.fromstring(f['ismrmrd_header'][()])
for elem in root.getiterator():
elem.tag = lxml.etree.QName(elem).localname
d = dictify(root)
if 'coilLabel' in d['ismrmrdHeader']['acquisitionSystemInformation']:
coilLabel = d['ismrmrdHeader']['acquisitionSystemInformation']['coilLabel']
c = [x['coilName'] for x in coilLabel]
else:
c = []
# Only include files that include the requested coil elements
if coils is None or all([x in c for x in coils]):
files_filtered2.append(file)
#%% Count frequency of coil elements
coil_frequencies = {}
for i,file in enumerate(files_filtered2):
# print(file)
# Read data
with h5py.File(file, 'r') as f:
root = lxml.etree.fromstring(f['ismrmrd_header'][()])
for elem in root.getiterator():
elem.tag = lxml.etree.QName(elem).localname
d = dictify(root)
if 'coilLabel' in d['ismrmrdHeader']['acquisitionSystemInformation']:
coilLabel = d['ismrmrdHeader']['acquisitionSystemInformation']['coilLabel']
for x in coilLabel:
name = x['coilName']
if name not in coil_frequencies:
coil_frequencies[name] = 0
coil_frequencies[name] += 1
print(f'Total files matched: {len(files_filtered2)}')
print('Coil element counts:')
for k,v in sorted(coil_frequencies.items()):
print(' ', k, v)