Created
April 18, 2017 21:39
-
-
Save tsalo/82e442a1d087d849b3602ffb25e4feb5 to your computer and use it in GitHub Desktop.
Add "IntendedFor" field to BIDS field map jsons for the associated fMRI and DWI scans based on acquisition time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import bisect | |
from glob import glob | |
from os.path import join, splitext | |
from bids.grabbids import BIDSLayout | |
from dateutil.parser import parse | |
# subj_dir *must* have trailing / | |
subj_dir = '/scratch/tsalo006/dset/sub-01/' | |
sess = '01' | |
data_suffix = '.nii.gz' | |
layout = BIDSLayout(subj_dir) | |
def files_to_dict(file_list): | |
"""Convert list of BIDS Files to dictionary where key is | |
acquisition time (datetime.datetime object) and value is | |
the File object. | |
""" | |
out_dict = {} | |
for f in file_list: | |
fn = f.filename | |
with open(fn, 'r') as fi: | |
data = json.load(fi) | |
dt = parse(data['AcquisitionDateTime']) | |
out_dict[dt] = f | |
return out_dict | |
# Get json files for field maps | |
fmap_jsons = layout.get(session=sess, modality='fmap', extensions='json') | |
for dir_ in ['AP', 'PA']: | |
# Run field map directions independently | |
dir_jsons = [fm for fm in fmap_jsons if '_dir-{0}_'.format(dir_) in fm.filename] | |
fmap_dict = files_to_dict(dir_jsons) | |
dts = sorted(fmap_dict.keys()) | |
intendedfor_dict = {fmap.filename: [] for fmap in dir_jsons} | |
# Get all scans with associated field maps (bold + dwi) | |
func_jsons = layout.get(session=sess, type='bold', extensions='json') +\ | |
layout.get(session=sess, type='dwi', extensions='json') | |
func_dict = files_to_dict(func_jsons) | |
for func in func_dict.keys(): | |
fn, _ = splitext(func_dict[func].filename) | |
fn += data_suffix | |
fn = fn.split(subj_dir)[-1] | |
# Find most immediate field map before scan | |
idx = bisect.bisect_right(dts, func) - 1 | |
fmap_file = fmap_dict[dts[idx]].filename | |
intendedfor_dict[fmap_file].append(fn) | |
for fmap_file in intendedfor_dict.keys(): | |
with open(fmap_file, 'r') as fi: | |
data = json.load(fi) | |
# No overwriting, for now | |
if 'IntendedFor' not in data.keys(): | |
data['IntendedFor'] = intendedfor_dict[fmap_file] | |
with open(fmap, 'w') as fo: | |
json.dump(data, fo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated a few things in my fork since it seems
pybids
has changed a bit.