onsets2subfolders.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #!/usr/bin/python3
  2. '''
  3. created on Fri Feb 14 2020
  4. author: Christian Olaf Haeusler
  5. '''
  6. from glob import glob
  7. import argparse
  8. import os
  9. import re
  10. import shutil
  11. def parse_arguments():
  12. '''
  13. '''
  14. parser = argparse.ArgumentParser(
  15. description='copy confound files to subject-specific directories')
  16. parser.add_argument('-fmri',
  17. default='inputs/studyforrest-data-aligned/sub-??/in_bold3Tp2/sub-??_task-aomovie_run-1_bold.nii.gz',
  18. help='''pattern of pathes/files that contains 4D fmri files
  19. (e.g. 'inputs/studyforrest-data-aligned/sub-??/in_bold3Tp2/sub-??_task-aomovie_run-1_bold.nii.gz');
  20. needed to get subjects for which used 4D data exist''')
  21. parser.add_argument('-onsets',
  22. default='./events/onsets/aomovie/run-?/*.txt',
  23. help='''pattern for input path/filenames of\n
  24. onsets files (e.g. './events/onsets/aomovie/run-?/*.txt')''')
  25. parser.add_argument('-o',
  26. default='./',
  27. help='the directory in which individual subject directories will be created'
  28. )
  29. args = parser.parse_args()
  30. fmriPattern = args.fmri
  31. onsetPattern = args.onsets
  32. outDir = args.o
  33. return fmriPattern, onsetPattern, outDir
  34. def get_subjects(pattern):
  35. '''
  36. searches a given directory (e.g. a directory with functional data) for
  37. subdirs to get name / number of available subjects
  38. Output:
  39. list of subdirectory (str; format 'sub-xy')
  40. '''
  41. pathes = sorted(glob(pattern))
  42. subs = []
  43. for path in pathes:
  44. x = re.search(r'sub-\d{2}', path)
  45. sub = x.group()[-2:]
  46. subs.append(int(sub))
  47. return subs
  48. def copy_sources_2_destinations(outDir, sub, stim, sources):
  49. '''
  50. '''
  51. # create the list of destinations
  52. dests = [os.path.join(outDir, sub, 'onsets', stim, 'run'+ x.split('run')[1])
  53. for x in sources]
  54. sourcesDests = zip(sources, dests)
  55. for source, dest in sourcesDests:
  56. # create folders if necessary
  57. try:
  58. os.makedirs(os.path.dirname(dest))
  59. except OSError:
  60. if not os.path.isdir(os.path.dirname(dest)):
  61. raise
  62. # copy that shit
  63. shutil.copyfile(source, dest)
  64. return None
  65. if __name__ == "__main__":
  66. fmriPattern, onsetPattern, outDir = parse_arguments()
  67. # get subject numbers from available subject folders
  68. subs = get_subjects(fmriPattern)
  69. regex = re.search(r'[a-z]{2}movie', onsetPattern)
  70. stim = regex.group()
  71. onsetFiles = sorted(glob(onsetPattern))
  72. for sub in subs:
  73. sub = 'sub-' + str(sub).zfill(2)
  74. # copy event files for the audio-only movie
  75. copy_sources_2_destinations(outDir, sub, stim, onsetFiles)