__init__.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """
  2. Python Library to Read FreeSurfer's cortical parcellation anatomical statistics
  3. ([lh]h.aparc(.*)?.stats)
  4. Freesurfer
  5. https://surfer.nmr.mgh.harvard.edu/
  6. >>> from freesurfer_stats import CorticalParcellationStats
  7. >>> stats = CorticalParcellationStats.read('tests/subjects/fabian/stats/lh.aparc.DKTatlas.stats')
  8. >>> stats.headers['CreationTime'].isoformat()
  9. '2019-05-09T21:05:54+00:00'
  10. >>> stats.headers['cvs_version']
  11. 'Id: mris_anatomical_stats.c,v 1.79 2016/03/14 15:15:34 greve Exp'
  12. >>> stats.headers['cmdline'][:64]
  13. 'mris_anatomical_stats -th3 -mgz -cortex ../label/lh.cortex.label'
  14. >>> stats.hemisphere
  15. >>> stats.whole_brain_measurements['estimated_total_intracranial_volume_mm^3']
  16. 0 1.670487e+06
  17. Name: estimated_total_intracranial_volume_mm^3, dtype: float64
  18. >>> stats.whole_brain_measurements['white_surface_total_area_mm^2']
  19. 0 98553
  20. Name: white_surface_total_area_mm^2, dtype: int64
  21. >>> stats.structural_measurements[['structure_name', 'surface_area_mm^2',
  22. ... 'gray_matter_volume_mm^3']].head()
  23. structure_name surface_area_mm^2 gray_matter_volume_mm^3
  24. 0 caudalanteriorcingulate 1472 4258
  25. 1 caudalmiddlefrontal 3039 8239
  26. 2 cuneus 2597 6722
  27. 3 entorhinal 499 2379
  28. 4 fusiform 3079 9064
  29. """
  30. import datetime
  31. import re
  32. import typing
  33. import pandas
  34. from freesurfer_stats.version import __version__
  35. class CorticalParcellationStats:
  36. _HEMISPHERE_PREFIX_TO_SIDE = {'lh': 'left', 'rh': 'right'}
  37. _GENERAL_MEASUREMENTS_REGEX = re.compile(
  38. r'^Measure \S+, ([^,\s]+),? ([^,]+), ([\d\.]+), (\S+)$')
  39. _COLUMN_NAMES_NON_SAFE_REGEX = re.compile(r'\s+')
  40. def __init__(self):
  41. self.headers \
  42. = {} # type: typing.Dict[str, typing.Union[str, datetime.datetime]]
  43. self.whole_brain_measurements \
  44. = {} # type: typing.Dict[str, typing.Tuple[float, int]]
  45. self.structural_measurements \
  46. = {} # type: typing.Union[pandas.DataFrame, None]
  47. @property
  48. def hemisphere(self) -> str:
  49. return self._HEMISPHERE_PREFIX_TO_SIDE[self.headers['hemi']]
  50. @staticmethod
  51. def _read_header_line(stream: typing.TextIO) -> str:
  52. line = stream.readline()
  53. assert line.startswith('# ')
  54. return line[2:].rstrip()
  55. @classmethod
  56. def _read_column_header_line(cls, stream: typing.TextIO) -> typing.Tuple[int, str, str]:
  57. line = cls._read_header_line(stream)
  58. assert line.startswith('TableCol'), line
  59. line = line[len('TableCol '):].lstrip()
  60. index, key, value = line.split(maxsplit=2)
  61. return int(index), key, value
  62. def _read_headers(self, stream: typing.TextIO) -> None:
  63. self.headers = {}
  64. while True:
  65. line = self._read_header_line(stream)
  66. if line.startswith('Measure'):
  67. break
  68. elif line:
  69. attr_name, attr_value = line.split(' ', maxsplit=1)
  70. attr_value = attr_value.lstrip()
  71. if attr_name in ['cvs_version', 'mrisurf.c-cvs_version']:
  72. attr_value = attr_value.strip('$').rstrip()
  73. if attr_name == 'CreationTime':
  74. attr_dt = datetime.datetime.strptime(
  75. attr_value, '%Y/%m/%d-%H:%M:%S-%Z')
  76. if attr_dt.tzinfo is None:
  77. assert attr_value.endswith('-GMT')
  78. attr_dt = attr_dt.replace(tzinfo=datetime.timezone.utc)
  79. attr_value = attr_dt
  80. if attr_name == 'AnnotationFileTimeStamp':
  81. attr_value = datetime.datetime.strptime(
  82. attr_value, '%Y/%m/%d %H:%M:%S')
  83. self.headers[attr_name] = attr_value
  84. @classmethod
  85. def _format_column_name(cls, name: str, unit: typing.Optional[str]) -> str:
  86. column_name = name.lower()
  87. if unit not in ['unitless', 'NA']:
  88. column_name += '_' + unit
  89. return cls._COLUMN_NAMES_NON_SAFE_REGEX.sub('_', column_name)
  90. @classmethod
  91. def _read_column_attributes(cls, num: int, stream: typing.TextIO) \
  92. -> typing.List[typing.Dict[str, str]]:
  93. columns = []
  94. for column_index in range(1, int(num) + 1):
  95. column_attrs = {}
  96. for _ in range(3):
  97. column_index_line, key, value \
  98. = cls._read_column_header_line(stream)
  99. assert column_index_line == column_index
  100. assert key not in column_attrs
  101. column_attrs[key] = value
  102. columns.append(column_attrs)
  103. return columns
  104. def _read(self, stream: typing.TextIO) -> None:
  105. assert stream.readline().rstrip() \
  106. == '# Table of FreeSurfer cortical parcellation anatomical statistics'
  107. assert stream.readline().rstrip() == '#'
  108. self._read_headers(stream)
  109. self.whole_brain_measurements = pandas.DataFrame()
  110. line = self._read_header_line(stream)
  111. while not line.startswith('NTableCols'):
  112. key, name, value, unit \
  113. = self._GENERAL_MEASUREMENTS_REGEX.match(line).groups()
  114. if key == 'SupraTentorialVolNotVent' and name.lower() == 'supratentorial volume':
  115. name += ' Without Ventricles'
  116. column_name = self._format_column_name(name, unit)
  117. assert column_name not in self.whole_brain_measurements, \
  118. (key, name, column_name, self.whole_brain_measurements)
  119. self.whole_brain_measurements[column_name] \
  120. = pandas.to_numeric([value], errors='raise')
  121. line = self._read_header_line(stream)
  122. columns = self._read_column_attributes(
  123. int(line[len('NTableCols '):]), stream)
  124. assert self._read_header_line(stream) \
  125. == 'ColHeaders ' + ' '.join(c['ColHeader'] for c in columns)
  126. self.structural_measurements = pandas.DataFrame(
  127. (line.rstrip().split() for line in stream),
  128. columns=[self._format_column_name(c['FieldName'], c['Units']) for c in columns]) \
  129. .apply(pandas.to_numeric, errors='ignore')
  130. @classmethod
  131. def read(cls, path: str) -> 'CorticalParcellationStats':
  132. stats = cls()
  133. with open(path, 'r') as stream:
  134. # pylint: disable=protected-access
  135. stats._read(stream)
  136. return stats