__init__.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Read hippocampal subfield volumes computed by Freesurfer
  3. https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfields
  4. """
  5. import argparse
  6. import os
  7. import re
  8. import typing
  9. import pandas
  10. from freesurfer_volume_reader.freesurfer import HippocampalSubfieldsVolumeFile
  11. def remove_group_names_from_regex(regex_pattern: str) -> str:
  12. return re.sub(r'\?P<.+?>', '', regex_pattern)
  13. def read_hippocampal_volume_file_dataframe(volume_file: HippocampalSubfieldsVolumeFile,
  14. ) -> pandas.DataFrame:
  15. volumes_frame = pandas.DataFrame([
  16. {'subfield': s, 'volume_mm^3': v}
  17. for s, v in volume_file.read_volumes_mm3().items()
  18. ])
  19. volumes_frame['subject'] = volume_file.subject
  20. volumes_frame['hemisphere'] = volume_file.hemisphere
  21. # volumes_frame['hemisphere'] = volumes_frame['hemisphere'].astype('category')
  22. volumes_frame['T1_input'] = volume_file.t1_input
  23. volumes_frame['analysis_id'] = volume_file.analysis_id
  24. return volumes_frame
  25. def main():
  26. argparser = argparse.ArgumentParser(description=__doc__)
  27. argparser.add_argument('--filename-regex', type=re.compile,
  28. default=remove_group_names_from_regex(
  29. HippocampalSubfieldsVolumeFile.FILENAME_PATTERN),
  30. help='default: %(default)s')
  31. argparser.add_argument('--output-format', choices=['csv'], default='csv',
  32. help='default: %(default)s')
  33. subjects_dir_path = os.environ.get('SUBJECTS_DIR', None)
  34. argparser.add_argument('root_dir_paths',
  35. metavar='ROOT_DIR',
  36. nargs='*' if subjects_dir_path else '+',
  37. default=[subjects_dir_path],
  38. help='default: $SUBJECTS_DIR ({})'.format(subjects_dir_path))
  39. args = argparser.parse_args()
  40. volume_files = [f for d in args.root_dir_paths
  41. for f in HippocampalSubfieldsVolumeFile.find(
  42. root_dir_path=d, filename_regex=args.filename_regex)]
  43. volume_frames = []
  44. for volume_file in volume_files:
  45. volume_frame = read_hippocampal_volume_file_dataframe(volume_file)
  46. volume_frame['source_path'] = volume_file.absolute_path
  47. volume_frames.append(volume_frame)
  48. united_volume_frame = pandas.concat(volume_frames, ignore_index=True)
  49. print(united_volume_frame.to_csv(index=False))
  50. if __name__ == '__main__':
  51. main()