Browse Source

added ashs.HippocampalSubfieldsVolumeFile.read_volumes_dataframe()

Fabian Peter Hammerle 5 years ago
parent
commit
5f546743fc
5 changed files with 48 additions and 2 deletions
  1. 1 0
      README.md
  2. 6 0
      freesurfer_volume_reader/__init__.py
  3. 13 0
      freesurfer_volume_reader/ashs.py
  4. 26 1
      tests/ashs_test.py
  5. 2 1
      tests/conftest.py

+ 1 - 0
README.md

@@ -47,6 +47,7 @@ from freesurfer_volume_reader import ashs
 for volume_file in ashs.HippocampalSubfieldsVolumeFile.find('/my/ashs/subjects'):
     print(volume_file.subject, volume_file.hemisphere, volume_file.correction)
     print(volume_file.read_volumes_mm3())
+    print(volume_file.read_volumes_dataframe())
 ```
 
 ## Tests

+ 6 - 0
freesurfer_volume_reader/__init__.py

@@ -14,6 +14,8 @@ import abc
 import os
 import typing
 
+import pandas
+
 
 class VolumeFile(metaclass=abc.ABCMeta):
 
@@ -28,6 +30,10 @@ class VolumeFile(metaclass=abc.ABCMeta):
     def read_volumes_mm3(self) -> typing.Dict[str, float]:
         raise NotImplementedError()
 
+    @abc.abstractmethod
+    def read_volumes_dataframe(self) -> pandas.DataFrame:
+        raise NotImplementedError()
+
     @classmethod
     def find(cls, root_dir_path: str,
              filename_regex: typing.Optional[typing.Pattern] = None) -> typing.Iterator[str]:

+ 13 - 0
freesurfer_volume_reader/ashs.py

@@ -8,12 +8,15 @@ https://sites.google.com/site/hipposubfields/home
 >>> for volume_file in HippocampalSubfieldsVolumeFile('/my/ashs/subjects'):
 >>>     print(volume_file.subject, volume_file.hemisphere, volume_file.correction)
 >>>     print(volume_file.read_volumes_mm3())
+>>>     print(volume_file.read_volumes_dataframe())
 """
 
 import os
 import re
 import typing
 
+import pandas
+
 import freesurfer_volume_reader
 
 
@@ -50,3 +53,13 @@ class HippocampalSubfieldsVolumeFile(freesurfer_volume_reader.VolumeFile):
                 assert int(slices_number_str) >= 0
                 subfield_volumes[subfield_name] = float(volume_mm3_str)
         return subfield_volumes
+
+    def read_volumes_dataframe(self) -> pandas.DataFrame:
+        volumes_frame = pandas.DataFrame([
+            {'subfield': s, 'volume_mm^3': v}
+            for s, v in self.read_volumes_mm3().items()
+        ])
+        volumes_frame['subject'] = self.subject
+        volumes_frame['hemisphere'] = self.hemisphere
+        volumes_frame['correction'] = self.correction
+        return volumes_frame

+ 26 - 1
tests/ashs_test.py

@@ -1,11 +1,12 @@
 import os
 import re
 
+import pandas
 import pytest
 
 from freesurfer_volume_reader.ashs import HippocampalSubfieldsVolumeFile
 
-from conftest import SUBJECTS_DIR
+from conftest import SUBJECTS_DIR, assert_volume_frames_equal
 
 
 @pytest.mark.parametrize(('volume_file_path', 'expected_attrs'), [
@@ -70,6 +71,30 @@ def test_hippocampal_subfields_volume_file_read_volumes_mm3_not_found():
         volume_file.read_volumes_mm3()
 
 
+@pytest.mark.parametrize(('volume_file_path', 'expected_dataframe'), [
+    (os.path.join(SUBJECTS_DIR, 'alice', 'final', 'alice_left_heur_volumes.txt'),
+     pandas.DataFrame({
+         'subfield': ['CA1', 'CA2+3', 'DG', 'ERC', 'PHC', 'PRC', 'SUB'],
+         'volume_mm^3': [679.904, 124.459, 902.237, 679.904, 2346.879, 2346.671, 458.782],
+         'subject': 'alice',
+         'hemisphere': 'left',
+         'correction': None,
+     })),
+])
+def test_hippocampal_subfields_volume_file_read_volumes_dataframe(
+        volume_file_path: str, expected_dataframe: pandas.DataFrame):
+    volume_file = HippocampalSubfieldsVolumeFile(path=volume_file_path)
+    assert_volume_frames_equal(left=expected_dataframe,
+                               right=volume_file.read_volumes_dataframe())
+
+
+def test_hippocampal_subfields_volume_file_read_volumes_dataframe_not_found():
+    volume_file = HippocampalSubfieldsVolumeFile(
+        path=os.path.join(SUBJECTS_DIR, 'nobert', 'final', 'bert_left_corr_nogray_volumes.txt'))
+    with pytest.raises(FileNotFoundError):
+        volume_file.read_volumes_dataframe()
+
+
 @pytest.mark.parametrize(('root_dir_path', 'expected_file_paths'), [
     (os.path.join(SUBJECTS_DIR, 'alice'),
      {os.path.join(SUBJECTS_DIR, 'alice', 'final', 'alice_left_heur_volumes.txt'),

+ 2 - 1
tests/conftest.py

@@ -6,7 +6,8 @@ SUBJECTS_DIR = os.path.join(os.path.dirname(__file__), 'subjects')
 
 
 def assert_volume_frames_equal(left: pandas.DataFrame, right: pandas.DataFrame):
-    sort_by = ['volume_mm^3', 'analysis_id']
+    sort_by = list(filter(lambda n: n in left,
+                          ['volume_mm^3', 'analysis_id', 'correction']))
     left.sort_values(sort_by, inplace=True)
     right.sort_values(sort_by, inplace=True)
     left.reset_index(inplace=True, drop=True)