__init__.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. def parse_version_string(version_string: str) -> typing.Tuple[typing.Union[int, str]]:
  21. return tuple(int(p) if p.isdigit() else p for p in version_string.split('.'))
  22. def remove_group_names_from_regex(regex_pattern: str) -> str:
  23. return re.sub(r'\?P<.+?>', '', regex_pattern)
  24. class VolumeFile(metaclass=abc.ABCMeta):
  25. FILENAME_REGEX = NotImplemented
  26. @property
  27. @abc.abstractmethod
  28. def absolute_path(self):
  29. raise NotImplementedError()
  30. @abc.abstractmethod
  31. def read_volumes_mm3(self) -> typing.Dict[str, float]:
  32. raise NotImplementedError()
  33. @abc.abstractmethod
  34. def read_volumes_dataframe(self) -> pandas.DataFrame:
  35. raise NotImplementedError()
  36. @classmethod
  37. def find(cls, root_dir_path: str,
  38. filename_regex: typing.Optional[typing.Pattern] = None,
  39. ) -> typing.Iterator['VolumeFile']:
  40. if not filename_regex:
  41. filename_regex = cls.FILENAME_REGEX
  42. for dirpath, _, filenames in os.walk(root_dir_path):
  43. for filename in filter(filename_regex.search, filenames):
  44. yield cls(path=os.path.join(dirpath, filename))