freesurfer.py 2.7 KB

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