highspeed-bids-fieldmaps.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # ======================================================================
  4. # SCRIPT INFORMATION:
  5. # ======================================================================
  6. # SCRIPT: UPDATE THE FIELDMAP JSON FILES
  7. # PROJECT: HIGHSPEED
  8. # WRITTEN BY LENNART WITTKUHN, 2018 - 2020
  9. # CONTACT: WITTKUHN AT MPIB HYPHEN BERLIN DOT MPG DOT DE
  10. # MAX PLANCK RESEARCH GROUP NEUROCODE
  11. # MAX PLANCK INSTITUTE FOR HUMAN DEVELOPMENT
  12. # MAX PLANCK UCL CENTRE FOR COMPUTATIONAL PSYCHIATRY AND AGEING RESEARCH
  13. # LENTZEALLEE 94, 14195 BERLIN, GERMANY
  14. # ======================================================================
  15. # IMPORT RELEVANT PACKAGES
  16. # ======================================================================
  17. import os
  18. import glob
  19. import json
  20. import sys
  21. import stat
  22. # ======================================================================
  23. # DEFINE PATHS
  24. # ======================================================================
  25. # to run type python3 bids_fieldmaps_info.py $PATH_BIDS
  26. # where $PATH_BIDS is the path to your BIDS directory
  27. path_bids = str(sys.argv[1])
  28. path_fmap = os.path.join(path_bids, '*', '*', 'fmap', '*.json')
  29. path_func = os.path.join(path_bids, '*', '*', 'func', '*.nii.gz')
  30. # ======================================================================
  31. # UPDATE FIELDMAP JSON FILES
  32. # ======================================================================
  33. # get all fieldmap files in the data-set:
  34. files_fmap = glob.glob(path_fmap)
  35. # loop over all field-map files:
  36. for file_path in files_fmap:
  37. # open the .json file of the fieldmap acquisition:
  38. with open(file_path, 'r') as in_file:
  39. json_info = json.load(in_file)
  40. in_file.close()
  41. # get the path to the session folder of a specific participant:
  42. file_base = os.path.dirname(os.path.dirname(file_path))
  43. # get the path to all functional acquisitions in that session:
  44. files_func = glob.glob(os.path.join(file_base, 'func', '*nii.gz'))
  45. session = os.path.basename(file_base)
  46. up_dirs = os.path.join(session, 'func')
  47. intended_for = [os.path.join(up_dirs, os.path.basename(file)) for file in files_func]
  48. json_info["IntendedFor"] = sorted(intended_for)
  49. # change file permissions to read:
  50. permissions = os.stat(file_path).st_mode
  51. os.chmod(path=file_path, mode=permissions | stat.S_IWUSR)
  52. # save updated fieldmap json-file:
  53. with open(file_path, 'w') as out_file:
  54. json.dump(json_info, out_file, indent=2, sort_keys=True)
  55. out_file.close()
  56. # change file permissions back to read-only:
  57. os.chmod(path=file_path, mode=permissions)