ashs.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. Read hippocampal subfield volumes computed by ASHS
  3. https://sites.google.com/site/hipposubfields/home
  4. >>> from freesurfer_volume_reader.ashs import HippocampalSubfieldsVolumeFile
  5. >>>
  6. >>> for volume_file in HippocampalSubfieldsVolumeFile('/my/ashs/subjects'):
  7. >>> print(volume_file.subject, volume_file.hemisphere, volume_file.correction)
  8. >>> print(volume_file.read_volumes_mm3())
  9. >>> print(volume_file.read_volumes_dataframe())
  10. """
  11. import os
  12. import re
  13. import typing
  14. import pandas
  15. import freesurfer_volume_reader
  16. class HippocampalSubfieldsVolumeFile(freesurfer_volume_reader.VolumeFile):
  17. # https://sites.google.com/site/hipposubfields/tutorial#TOC-Viewing-ASHS-Segmentation-Results
  18. FILENAME_PATTERN = r'^(?P<s>\w+)_(?P<h>left|right)' \
  19. r'_(heur|corr_(?P<c>nogray|usegray))_volumes.txt$'
  20. FILENAME_REGEX = re.compile(FILENAME_PATTERN)
  21. def __init__(self, path: str):
  22. self._absolute_path = os.path.abspath(path)
  23. filename_match = self.FILENAME_REGEX.match(os.path.basename(path))
  24. assert filename_match, self._absolute_path
  25. filename_groups = filename_match.groupdict()
  26. self.subject = filename_groups['s']
  27. self.hemisphere = filename_groups['h']
  28. self.correction = filename_groups['c']
  29. @property
  30. def absolute_path(self):
  31. return self._absolute_path
  32. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  33. subfield_volumes = {}
  34. with open(self.absolute_path, 'r') as volume_file:
  35. for line in volume_file.read().rstrip().split('\n'):
  36. # > echo $ASHS_SUBJID $side $SUB $NBODY $VSUB >> $FNBODYVOL
  37. # https://github.com/pyushkevich/ashs/blob/515ff7c2f50928adabc4e64bded9a7e76fc750b1/bin/ashs_extractstats_qsub.sh#L94
  38. subject, hemisphere, subfield_name, slices_number_str, volume_mm3_str \
  39. = line.split(' ')
  40. assert self.subject == subject
  41. assert self.hemisphere == hemisphere
  42. assert int(slices_number_str) >= 0
  43. subfield_volumes[subfield_name] = float(volume_mm3_str)
  44. return subfield_volumes
  45. def read_volumes_dataframe(self) -> pandas.DataFrame:
  46. volumes_frame = pandas.DataFrame([
  47. {'subfield': s, 'volume_mm^3': v}
  48. for s, v in self.read_volumes_mm3().items()
  49. ])
  50. volumes_frame['subject'] = self.subject
  51. volumes_frame['hemisphere'] = self.hemisphere
  52. volumes_frame['correction'] = self.correction
  53. return volumes_frame