ashs.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. >>> volume_file = HippocampalSubfieldsVolumeFile('ashs/final/bert_right_corr_nogray_volumes.txt')
  7. >>> print(volume_file.subject, volume_file.hemisphere, volume_file.correction)
  8. >>> print(volume_file.read_volumes_mm3())
  9. """
  10. import os
  11. import re
  12. import typing
  13. import freesurfer_volume_reader
  14. class HippocampalSubfieldsVolumeFile(freesurfer_volume_reader.VolumeFile):
  15. # https://sites.google.com/site/hipposubfields/tutorial#TOC-Viewing-ASHS-Segmentation-Results
  16. FILENAME_PATTERN = r'^(?P<s>\w+)_(?P<h>left|right)' \
  17. r'_(heur|corr_(?P<c>nogray|usegray))_volumes.txt$'
  18. FILENAME_REGEX = re.compile(FILENAME_PATTERN)
  19. def __init__(self, path: str):
  20. self._absolute_path = os.path.abspath(path)
  21. filename_match = self.FILENAME_REGEX.match(os.path.basename(path))
  22. assert filename_match, self._absolute_path
  23. filename_groups = filename_match.groupdict()
  24. self.subject = filename_groups['s']
  25. self.hemisphere = filename_groups['h']
  26. self.correction = filename_groups['c']
  27. @property
  28. def absolute_path(self):
  29. return self._absolute_path
  30. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  31. subfield_volumes = {}
  32. with open(self.absolute_path, 'r') as volume_file:
  33. for line in volume_file.read().rstrip().split('\n'):
  34. # > echo $ASHS_SUBJID $side $SUB $NBODY $VSUB >> $FNBODYVOL
  35. # https://github.com/pyushkevich/ashs/blob/515ff7c2f50928adabc4e64bded9a7e76fc750b1/bin/ashs_extractstats_qsub.sh#L94
  36. subject, hemisphere, subfield_name, slices_number_str, volume_mm3_str \
  37. = line.split(' ')
  38. assert self.subject == subject
  39. assert self.hemisphere == hemisphere
  40. assert int(slices_number_str) >= 0
  41. subfield_volumes[subfield_name] = float(volume_mm3_str)
  42. return subfield_volumes