__init__.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. Read hippocampal subfield volumes computed by Freesurfer and/or ASHS
  3. https://sites.google.com/site/hipposubfields/home
  4. https://surfer.nmr.mgh.harvard.edu/fswiki/HippocampalSubfields
  5. >>> from freesurfer_volume_reader import ashs, freesurfer
  6. >>>
  7. >>> for volume_file in itertools.chain(
  8. >>> ashs.HippocampalSubfieldsVolumeFile.find('/my/ashs/subjects'),
  9. >>> freesurfer.HippocampalSubfieldsVolumeFile.find('/my/freesurfer/subjects')):
  10. >>> print(volume_file.absolute_path)
  11. >>> print(volume_file.subject, volume_file.hemisphere)
  12. >>> print(volume_file.read_volumes_mm3())
  13. >>> print(volume_file.read_volumes_dataframe())
  14. """
  15. import abc
  16. import os
  17. import re
  18. import typing
  19. import pandas
  20. try:
  21. from freesurfer_volume_reader.version import __version__
  22. except ImportError: # pragma: no cover
  23. __version__ = None
  24. def parse_version_string(version_string: str) -> typing.Tuple[typing.Union[int, str]]:
  25. return tuple(int(p) if p.isdigit() else p for p in version_string.split('.'))
  26. def remove_group_names_from_regex(regex_pattern: str) -> str:
  27. return re.sub(r'\?P<.+?>', '', regex_pattern)
  28. class VolumeFile(metaclass=abc.ABCMeta):
  29. FILENAME_REGEX = NotImplemented
  30. @property
  31. @abc.abstractmethod
  32. def absolute_path(self):
  33. raise NotImplementedError()
  34. @classmethod
  35. def find(cls, root_dir_path: str,
  36. filename_regex: typing.Optional[typing.Pattern] = None,
  37. ) -> typing.Iterator['SubfieldVolumeFile']:
  38. if not filename_regex:
  39. filename_regex = cls.FILENAME_REGEX
  40. for dirpath, _, filenames in os.walk(root_dir_path):
  41. for filename in filter(filename_regex.search, filenames):
  42. yield cls(path=os.path.join(dirpath, filename))
  43. class SubfieldVolumeFile(VolumeFile):
  44. @abc.abstractmethod
  45. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  46. raise NotImplementedError()
  47. @abc.abstractmethod
  48. def read_volumes_dataframe(self) -> pandas.DataFrame:
  49. raise NotImplementedError()
  50. def _read_volume_series(self) -> pandas.Series:
  51. subfield_volumes = self.read_volumes_mm3()
  52. return pandas.Series(
  53. data=list(subfield_volumes.values()),
  54. name='volume_mm^3',
  55. index=pandas.Index(
  56. data=subfield_volumes.keys(),
  57. name='subfield',
  58. ),
  59. )