def test_get_fieldmap2(): data_dir = join(dirname(__file__), 'data', '7t_trt') layout = BIDSLayout(data_dir) target = 'sub-03/ses-2/func/sub-03_ses-2_task-' \ 'rest_acq-fullbrain_run-2_bold.nii.gz' result = layout.get_fieldmap(join(data_dir, target)) assert result["type"] == "phasediff" assert result["phasediff"].endswith('sub-03_ses-2_run-2_phasediff.nii.gz')
def main(sourcedata, derivatives, tmp_dir, subject=None, session=None, run=None): if run is []: run = '[0-9]+' print('Processing subject {subject}, session {session}, run {run}'.format( **locals())) layout = BIDSLayout(sourcedata) derivatives_layout = BIDSLayout(derivatives) dtissue = derivatives_layout.get(subject=subject, type='dtissue', return_type='file') dura = derivatives_layout.get(subject=subject, type='dura', return_type='file') if len(dtissue) > 1: warnings.warn('Found more than one white-matter segmentation! {} '\ 'Using {}'.format(dtissue, dtissue[0])) dtissue = dtissue[0] print(dtissue) dura = dura[0] get_wm_wf = get_wm_seg_from_fmriprep_wf(dtissue) bold = layout.get(subject=subject, session=session, run=run, type='bold', return_type='file') epi = [] for b in bold: fmaps = layout.get_fieldmap(b, return_list=True) for fmap in fmaps: if fmap['type'] == 'epi': break epi.append(fmap['epi']) print('Using {} as epi_op for {}'.format(fmap['epi'], b)) t1w = layout.get(subject=subject, type='T1w', return_type='file')[0] init_matrix = derivatives_layout.get(subject=subject, type='initmat', extensions='mat', return_type='file') if len(init_matrix) == 1: init_matrix = init_matrix[0] else: init_matrix = None print(init_matrix) wf = init_hires_unwarping_wf( name="unwarp_hires_{}_onefield".format(subject), method='topup', bids_layout=layout, single_warpfield=True, register_to='last', init_transform=init_matrix, linear_registration_parameters='linear_hires.json', nonlinear_registration_parameters='nonlinear_precise.json', bold=bold, epi_op=epi, t1w_epi=None, t1w=t1w, dura_mask=dura, wm_seg=True, inv2_epi=None, dof=6, crop_bolds=True, topup_package='afni', epi_to_t1_package='fsl', within_epi_reg=False, polish=True, derivatives_dir=os.path.join(derivatives, 'onefield'), num_threads_ants=4) wf.connect(get_wm_wf, 'outputspec.wm_seg', wf.get_node('inputspec'), 'wm_seg') wf.base_dir = tmp_dir wf.run(plugin='MultiProc', plugin_args={'n_procs': 12})
extensions=["nii.gz", "nii"])] t2ws = [f.filename for f in layout.get(subject=subject_label, type='T2w', extensions=["nii.gz", "nii"])] assert (len(t1ws) > 0), "No T1w files found for subject %s!"%subject_label assert (len(t2ws) > 0), "No T2w files found for subject %s!"%subject_label available_resolutions = ["0.7", "0.8", "1"] t1_zooms = nibabel.load(t1ws[0]).get_header().get_zooms() t1_res = float(min(t1_zooms[:3])) t1_template_res = min(available_resolutions, key=lambda x:abs(float(x)-t1_res)) t2_zooms = nibabel.load(t2ws[0]).get_header().get_zooms() t2_res = float(min(t2_zooms[:3])) t2_template_res = min(available_resolutions, key=lambda x:abs(float(x)-t2_res)) fieldmap_set = layout.get_fieldmap(t1ws[0],return_list=True) fmap_args = {"fmapmag": "NONE", "fmapphase": "NONE", "echodiff": "NONE", "t1samplespacing": "NONE", "t2samplespacing": "NONE", "unwarpdir": "NONE", "avgrdcmethod": "NONE", "SEPhaseNeg": "NONE", "SEPhasePos": "NONE", "echospacing": "NONE", "seunwarpdir": "NONE"} if fieldmap_set: if len(fieldmap_set)>1: fieldmap_trans=dict(zip(fieldmap_set[0],zip(*[d.values() for d in fieldmap_set])))
def get_metadata(epi_file, bids_dir): """ This function requires the "IntendedFor" field in the json sidecar of the field map to be defined. (See section 8.3.5 of the BIDS spec) """ import re import os import subprocess from bids.grabbids import BIDSLayout # save to node folder (go up 2 directories bc of iterfield) cwd = os.path.dirname(os.path.dirname(os.getcwd())) # get bids layout layout = BIDSLayout(bids_dir) # get fieldmaps for epi fieldmap = layout.get_fieldmap(epi_file) # check if None; this means the IntendedFor tag is not defined; Try to guess the field map from the data # TODO THIS POTENTIALLY UNSTABLE CODE. SOMEONE SHOULD COME UP WITH A BETTER WAY TO DO THIS! # I assume there is only 1 fieldmap per session if not fieldmap: print( '\n****************************************************************************' ) print('File: {}'.format(epi_file)) print( 'IntendedFor field undefined! I\'ll try to guess the fieldmap file...\n' ) sub = os.path.split(epi_file)[1].split("_")[0].split("sub-")[ 1] # set subject type_ = '(phase1|phasediff|epi|fieldmap)' # get all fieldmap types files = layout.get(subject=sub, type=type_, extensions=['nii.gz', 'nii']) # get the potential fmaps # check files length, if 1 then there is probable only 1 session and only one fieldmap if len(files) == 1: fieldmap = { 'phasediff': files[0].filename, 'type': files[0].type, 'magnitude1': files[0].filename.replace('phasediff', 'magnitude1'), 'magnitude2': files[0].filename.replace('phasediff', 'magnitude2') } else: # assume more than one session ses = os.path.split(epi_file)[1].split("_")[1].split("ses-")[1] for file in files: if file.session == ses: # match the session number fieldmap = { 'phasediff': file.filename, 'type': file.type, 'magnitude1': file.filename.replace('phasediff', 'magnitude1'), 'magnitude2': file.filename.replace('phasediff', 'magnitude2') } # check if we were able to get the fieldmap assert bool( fieldmap ), 'We couldn\'t find a fieldmap. Specify the IntendedFor Field or disable field map correction.' print('I think {} is the fieldmap. You should verify this is correct.'. format(fieldmap['phasediff'])) print( '****************************************************************************\n' ) # we only know how to use phasediff map, anything else is not supported... assert fieldmap[ 'type'] == 'phasediff', 'Non-phasediff map unsupported for field map correction.' # get the phase diff image phasediff = fieldmap['phasediff'] # get the list of magnitude images magnitude = [ fieldmap[key] for key in fieldmap if re.match('magnitude', key) ] # choose 1st magnitude image TODO: add setting that lets user choose magnitude image magnitude = magnitude[0] # get effective echo time of phasediff echotime1 = layout.get_metadata(phasediff)['EchoTime1'] echotime2 = layout.get_metadata(phasediff)['EchoTime2'] TE = abs(echotime2 - echotime1) * 1000 # get the echospacing for the epi image echospacing = layout.get_metadata(epi_file)['EffectiveEchoSpacing'] # get the phase encoding direction ped = layout.get_metadata(epi_file)['PhaseEncodingDirection'] # determine image orientation output = subprocess.run(['3dinfo', '-orient', phasediff], stdout=subprocess.PIPE) orientation = output.stdout.decode('utf-8').rstrip() if ped[0] == 'i': # choose orientation based on ped if orientation[0] == 'R': orient_code = 'RL' elif orientation[0] == 'L': orient_code = 'LR' else: raise ValueError('Invalid Orientation!') elif ped[0] == 'j': if orientation[1] == 'A': orient_code = 'AP' elif orientation[1] == 'P': orient_code = 'PA' else: raise ValueError('Invalid Orientation!') elif ped[0] == 'k': if orientation[2] == 'I': orient_code = 'IS' elif orientation[2] == 'S': orient_code = 'SI' else: raise ValueError('Invalid Orientation!') else: raise ValueError('Invalid Phhase Encoding Direction Parsed!') # reverse the orientation if ped was negative if ped[1] == '-': orient_code = orient_code[::-1] # Using the orient code to find the equivalent FSL ped ped = { 'RL': 'x', 'LR': 'x-', 'AP': 'y', 'PA': 'y-', 'SI': 'z', 'IS': 'z-' }[orient_code] # return the magnitude and phase image paths return (magnitude, phasediff, TE, echospacing, ped)
assert (len(t1ws) > 0), "No T1w files found for subject %s!" % subject_label assert (len(t2ws) > 0), "No T2w files found for subject %s!" % subject_label available_resolutions = [0.7, 0.8, 1.0] t1_zooms = nibabel.load(t1ws[0]).get_header().get_zooms() t1_res = float(min(t1_zooms[:3])) t1_template_res = min(available_resolutions, key=lambda x: abs(x - t1_res)) t2_zooms = nibabel.load(t2ws[0]).get_header().get_zooms() t2_res = float(min(t2_zooms[:3])) t2_template_res = min(available_resolutions, key=lambda x: abs(x - t2_res)) fieldmap_set = layout.get_fieldmap(t1ws[0]) fmap_args = { "fmapmag": "NONE", "fmapphase": "NONE", "echodiff": "NONE", "t1samplespacing": "NONE", "t2samplespacing": "NONE", "unwarpdir": "NONE", "avgrdcmethod": "NONE", "SEPhaseNeg": "NONE", "SEPhasePos": "NONE", "echospacing": "NONE", "seunwarpdir": "NONE" } if fieldmap_set: