Skip to content

Instantly share code, notes, and snippets.

@mgxd
Created November 19, 2018 16:35
Show Gist options
  • Save mgxd/0c3a6ee99b30aa99fc2e8fc36b9f6847 to your computer and use it in GitHub Desktop.
Save mgxd/0c3a6ee99b30aa99fc2e8fc36b9f6847 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import pandas as pd
import numpy as np
from argparse import ArgumentParser
import sys
import os
def parse_outliers(outliers, volumes):
if not outliers:
return []
# initialize array of volumes
arr = np.zeros(volumes)
arr[outliers[0]] = 1
return [arr] + parse_outliers(outliers[1:], volumes)
def save_outliers(outliers):
# save as dataframe
df = pd.DataFrame()
for i, outlier in enumerate(outliers):
df[str(i)] = pd.Series(outlier).astype(int)
return df
def get_parser():
docstr = """Generate outlier files compatible with SPM from fmriprep outputs"""
parser = ArgumentParser(description="Generate outlier files compatible with SPM")
parser.add_argument('bids_dir', action='store', help='the root folder of a BIDS dataset')
parser.add_argument('-f', '--fmriprep', action='store', help='fmriprep directory')
parser.add_argument('-o', '--outdir', action='store', help='outdir')
parser.add_argument('-c', '--cutoff', action='store', default=0.2, help='FD cutoff')
parser.add_argument('--overwrite', action='store_true', help='regenerate files')
return parser
def main(argv=None):
parser = get_parser()
args = parser.parse_args(argv)
if args.fmriprep:
from glob import glob
path = os.path.join(args.fmriprep, 'sub-*', '**', '*_confounds.tsv')
confounds = [x for x in glob(path)]
else:
from bids.grabbids import BIDSLayout
layout = BIDSLayout(args.bids_dir)
confounds = layout.get(type='confounds', return_type='file')
if not confounds:
print("No confounds found")
sys.exit(1)
if not args.cutoff:
print("FD cutoff missing")
sys.exit(1)
outdir = args.outdir if args.outdir else os.path.join(args.bids_dir,
'derivatives',
'outliers')
for confound in confounds:
outname = os.path.join(outdir, os.path.basename(confound.split('_bold')[0] + '_fd.txt'))
if os.path.exists(outname) and not args.overwrite:
print(outname, 'already exists, to regenerate run with --overwrite option')
continue
df = pd.read_csv(confound, sep='\t')
volumes = len(df)
outliers = df[df['FramewiseDisplacement'].gt(args.cutoff)].index.tolist()
outlier_arr = parse_outliers(outliers, volumes)
if not outlier_arr:
continue
outdf = save_outliers(outlier_arr)
outname = os.path.join(outdir, os.path.basename(confound.split('_bold')[0] + '_fd.txt'))
if not os.path.exists(outdir):
os.makedirs(outdir)
outdf.to_csv(outname, index=False, header=False, sep="\t")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment