freesurfer.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """
  2. Read hippocampal subfield volumes computed by Freesurfer
  3. https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfields
  4. >>> from freesurfer_volume_reader.freesurfer import HippocampalSubfieldsVolumeFile
  5. >>>
  6. >>> for volume_file in HippocampalSubfieldsVolumeFile.find('/my/freesurfer/subjects'):
  7. >>> print(volume_file.read_volumes_mm3())
  8. >>> print(volume_file.read_volumes_dataframe())
  9. """
  10. import os
  11. import re
  12. import typing
  13. import pandas
  14. import freesurfer_volume_reader
  15. class HippocampalSubfieldsVolumeFile(freesurfer_volume_reader.VolumeFile):
  16. # https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfields
  17. FILENAME_PATTERN = r'^(?P<h>[lr])h\.hippoSfVolumes' \
  18. r'(?P<T1>-T1)?(-(?P<analysis_id>.+?))?\.v10.txt$'
  19. FILENAME_REGEX = re.compile(FILENAME_PATTERN)
  20. FILENAME_HEMISPHERE_PREFIX_MAP = {'l': 'left', 'r': 'right'}
  21. def __init__(self, path: str):
  22. self._absolute_path = os.path.abspath(path)
  23. subject_dir_path = os.path.dirname(os.path.dirname(self._absolute_path))
  24. self.subject = os.path.basename(subject_dir_path)
  25. filename_match = self.FILENAME_REGEX.match(os.path.basename(path))
  26. assert filename_match, self._absolute_path
  27. filename_groups = filename_match.groupdict()
  28. assert filename_groups['T1'] or filename_groups['analysis_id'], self._absolute_path
  29. self.hemisphere = self.FILENAME_HEMISPHERE_PREFIX_MAP[filename_groups['h']]
  30. self.t1_input = filename_groups['T1'] is not None
  31. self.analysis_id = filename_groups['analysis_id']
  32. @property
  33. def absolute_path(self):
  34. return self._absolute_path
  35. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  36. subfield_volumes = {}
  37. with open(self.absolute_path, 'r') as volume_file:
  38. for line in volume_file.read().rstrip().split('\n'):
  39. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/HippoSF/src/segmentSubjectT1T2_autoEstimateAlveusML.m#L8
  40. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/HippoSF/src/segmentSubjectT1T2_autoEstimateAlveusML.m#L1946
  41. subfield_name, subfield_volume_mm3_str = line.split(' ')
  42. subfield_volumes[subfield_name] = float(subfield_volume_mm3_str)
  43. return subfield_volumes
  44. def read_volumes_dataframe(self) -> pandas.DataFrame:
  45. volumes_frame = pandas.DataFrame([
  46. {'subfield': s, 'volume_mm^3': v}
  47. for s, v in self.read_volumes_mm3().items()
  48. ])
  49. volumes_frame['subject'] = self.subject
  50. volumes_frame['hemisphere'] = self.hemisphere
  51. # volumes_frame['hemisphere'] = volumes_frame['hemisphere'].astype('category')
  52. volumes_frame['T1_input'] = self.t1_input
  53. volumes_frame['analysis_id'] = self.analysis_id
  54. return volumes_frame