Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 55 additions & 1 deletion nibabel/freesurfer/io.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
""" Read / write FreeSurfer geometry, morphometry, label, annotation formats
""" Read / write FreeSurfer geometry, morphometry, label, stats, annotation formats
"""
from __future__ import annotations

import warnings
import numpy as np
import getpass
import time
import re
import pandas as pd

from collections import OrderedDict
from ..openers import Opener
Expand Down Expand Up @@ -622,3 +625,54 @@ def _serialize_volume_info(volume_info):
strings.append(
f'{key:6s} = {val[0]:.10g} {val[1]:.10g} {val[2]:.10g}\n'.encode('utf-8'))
return b''.join(strings)


class StatsFileReader:

@staticmethod
def read_stats_file(file_path):
"""Extracts stats from stats files except '*curv.stats' files

Parameters
----------
file_path: str, required

Returns
-------

"""
with open(file_path, 'r') as f:
for line in f:
if re.findall(r'ColHeaders .*', line):
parameters = line.split()
break
f.close()
stats = np.loadtxt(file_path, comments='#', dtype=str)
df_stats = pd.DataFrame(stats, columns=parameters[2:])
df_stats.set_index('StructName', drop=True, inplace=True)
return df_stats

@staticmethod
def read_stats_file_both_hemispheres(file_path: str):
"""Extracts stats data of both hemisphers and merges them

Parameters
----------
file_path: str, required
Path of the stats file belong to left (lh) or right(rh) hemisphere

Returns
-------
df_both_hemispheres: pd.DataFrame
Stats data of both hemisphers

Examples
--------
>>> df_stats_a2009 = StatsFileReader.read_stats_file(r'lh.aparc.a2009s.stats')

"""
df_left = StatsFileReader.read_stats_file(file_path.replace('rh', 'lh'))
df_right = StatsFileReader.read_stats_file(file_path.replace('lh', 'rh'))
df_both_hemispheres = pd.merge(df_left, df_right, suffixes=('_lh', '_rh'), how='outer', left_index=True,
right_index=True)
return df_both_hemispheres