|
1 |
| -""" Read / write FreeSurfer geometry, morphometry, label, annotation formats |
| 1 | +""" Read / write FreeSurfer geometry, morphometry, label, stats, annotation formats |
2 | 2 | """
|
| 3 | +from __future__ import annotations |
3 | 4 |
|
4 | 5 | import warnings
|
5 | 6 | import numpy as np
|
6 | 7 | import getpass
|
7 | 8 | import time
|
| 9 | +import re |
| 10 | +import pandas as pd |
8 | 11 |
|
9 | 12 | from collections import OrderedDict
|
10 | 13 | from ..openers import Opener
|
@@ -622,3 +625,54 @@ def _serialize_volume_info(volume_info):
|
622 | 625 | strings.append(
|
623 | 626 | f'{key:6s} = {val[0]:.10g} {val[1]:.10g} {val[2]:.10g}\n'.encode('utf-8'))
|
624 | 627 | 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