Skip to content

Commit e0ea23d

Browse files
authored
Merge pull request #1 from ehkarimi/ehkarimi-stats_file_reader_added
Update io.py
2 parents d33a05a + dfed1e3 commit e0ea23d

File tree

1 file changed

+55
-1
lines changed

1 file changed

+55
-1
lines changed

nibabel/freesurfer/io.py

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
""" Read / write FreeSurfer geometry, morphometry, label, annotation formats
1+
""" Read / write FreeSurfer geometry, morphometry, label, stats, annotation formats
22
"""
3+
from __future__ import annotations
34

45
import warnings
56
import numpy as np
67
import getpass
78
import time
9+
import re
10+
import pandas as pd
811

912
from collections import OrderedDict
1013
from ..openers import Opener
@@ -622,3 +625,54 @@ def _serialize_volume_info(volume_info):
622625
strings.append(
623626
f'{key:6s} = {val[0]:.10g} {val[1]:.10g} {val[2]:.10g}\n'.encode('utf-8'))
624627
return b''.join(strings)
628+
629+
630+
class StatsFileReader:
631+
632+
@staticmethod
633+
def read_stats_file(file_path):
634+
"""Extracts stats from stats files except '*curv.stats' files
635+
636+
Parameters
637+
----------
638+
file_path: str, required
639+
640+
Returns
641+
-------
642+
643+
"""
644+
with open(file_path, 'r') as f:
645+
for line in f:
646+
if re.findall(r'ColHeaders .*', line):
647+
parameters = line.split()
648+
break
649+
f.close()
650+
stats = np.loadtxt(file_path, comments='#', dtype=str)
651+
df_stats = pd.DataFrame(stats, columns=parameters[2:])
652+
df_stats.set_index('StructName', drop=True, inplace=True)
653+
return df_stats
654+
655+
@staticmethod
656+
def read_stats_file_both_hemispheres(file_path: str):
657+
"""Extracts stats data of both hemisphers and merges them
658+
659+
Parameters
660+
----------
661+
file_path: str, required
662+
Path of the stats file belong to left (lh) or right(rh) hemisphere
663+
664+
Returns
665+
-------
666+
df_both_hemispheres: pd.DataFrame
667+
Stats data of both hemisphers
668+
669+
Examples
670+
--------
671+
>>> df_stats_a2009 = StatsFileReader.read_stats_file(r'lh.aparc.a2009s.stats')
672+
673+
"""
674+
df_left = StatsFileReader.read_stats_file(file_path.replace('rh', 'lh'))
675+
df_right = StatsFileReader.read_stats_file(file_path.replace('lh', 'rh'))
676+
df_both_hemispheres = pd.merge(df_left, df_right, suffixes=('_lh', '_rh'), how='outer', left_index=True,
677+
right_index=True)
678+
return df_both_hemispheres

0 commit comments

Comments
 (0)