__init__.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. @abc.abstractmethod
  35. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  36. raise NotImplementedError()
  37. @abc.abstractmethod
  38. def read_volumes_dataframe(self) -> pandas.DataFrame:
  39. raise NotImplementedError()
  40. @classmethod
  41. def find(cls, root_dir_path: str,
  42. filename_regex: typing.Optional[typing.Pattern] = None,
  43. ) -> typing.Iterator['VolumeFile']:
  44. if not filename_regex:
  45. filename_regex = cls.FILENAME_REGEX
  46. for dirpath, _, filenames in os.walk(root_dir_path):
  47. for filename in filter(filename_regex.search, filenames):
  48. yield cls(path=os.path.join(dirpath, filename))