__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """
  2. Python Library to Read and Write Surface Files in Freesurfer's TriangularSurface Format
  3. compatible with Freesurfer's MRISwriteTriangularSurface()
  4. https://github.com/freesurfer/freesurfer/blob/release_6_0_0/include/mrisurf.h#L1281
  5. https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/mrisurf.c
  6. https://raw.githubusercontent.com/freesurfer/freesurfer/release_6_0_0/utils/mrisurf.c
  7. Freesurfer
  8. https://surfer.nmr.mgh.harvard.edu/
  9. >>> from freesurfer_surface import Surface, Vertex
  10. >>>
  11. >>> surface = Surface.read_triangular('bert/surf/lh.pial'))
  12. >>>
  13. >>> vertex_index = surface.add_vertex(Vertex(0.0, -3.14, 21.42))
  14. >>> print(surface.vertices[vertex_index])
  15. >>> surface.write_triangular('somewhere/else/lh.pial')
  16. >>>
  17. >>> surface.load_annotation_file('bert/label/lh.aparc.annot')
  18. >>> print([label.name for label in surface.annotation.labels])
  19. >>>
  20. >>> precentral, = filter(lambda l: l.name == 'precentral', annotation.labels.values())
  21. >>> print(precentral.hex_color_code)
  22. >>>
  23. >>> precentral_vertix_indices = [vertex_index for vertex_index, label_index
  24. >>> in surface.annotation.vertex_label_index.items()
  25. >>> if label_index == precentral.index]
  26. >>> print(len(precentral_vertix_indices))
  27. """
  28. import collections
  29. import contextlib
  30. import datetime
  31. import locale
  32. import re
  33. import struct
  34. import typing
  35. try:
  36. from freesurfer_surface.version import __version__
  37. except ImportError: # pragma: no cover
  38. __version__ = None
  39. class UnsupportedLocaleSettingError(locale.Error):
  40. pass
  41. @contextlib.contextmanager
  42. def setlocale(temporary_locale):
  43. primary_locale = locale.setlocale(locale.LC_ALL)
  44. try:
  45. yield locale.setlocale(locale.LC_ALL, temporary_locale)
  46. except locale.Error as exc:
  47. if str(exc) == 'unsupported locale setting':
  48. raise UnsupportedLocaleSettingError(temporary_locale)
  49. raise exc
  50. finally:
  51. locale.setlocale(locale.LC_ALL, primary_locale)
  52. Vertex = collections.namedtuple('Vertex', ['right', 'anterior', 'superior'])
  53. class Triangle:
  54. # pylint: disable=too-few-public-methods
  55. _VERTEX_INDICES_TYPE = typing.Tuple[int]
  56. _vertex_indices: _VERTEX_INDICES_TYPE
  57. def __init__(self, vertex_indices: _VERTEX_INDICES_TYPE):
  58. self.vertex_indices = vertex_indices
  59. @property
  60. def vertex_indices(self):
  61. return self._vertex_indices
  62. @vertex_indices.setter
  63. def vertex_indices(self, indices: _VERTEX_INDICES_TYPE):
  64. assert len(indices) == 3
  65. self._vertex_indices = indices
  66. def __eq__(self, other: 'Triangle') -> bool:
  67. return self.vertex_indices == other.vertex_indices
  68. def __repr__(self) -> str:
  69. return 'Triangle(vertex_indices={})'.format(self.vertex_indices)
  70. class Label:
  71. # pylint: disable=too-few-public-methods
  72. index: int
  73. name: str
  74. red: int
  75. green: int
  76. blue: int
  77. transparency: int
  78. @property
  79. def color_code(self) -> int:
  80. if self.index == 0: # unknown
  81. return 0
  82. return int.from_bytes((self.red, self.green, self.blue, self.transparency),
  83. byteorder='little', signed=False)
  84. @property
  85. def hex_color_code(self) -> str:
  86. return '#{:02x}{:02x}{:02x}'.format(self.red, self.green, self.blue)
  87. def __str__(self) -> str:
  88. return 'Label(name={}, index={}, color={})'.format(
  89. self.name, self.index, self.hex_color_code)
  90. def __repr__(self) -> str:
  91. return str(self)
  92. class Annotation:
  93. # pylint: disable=too-few-public-methods
  94. _TAG_OLD_COLORTABLE = b'\0\0\0\x01'
  95. vertex_label_index: typing.Dict[int, int] = {}
  96. colortable_path: typing.Optional[bytes] = None
  97. labels: typing.Dict[int, Label] = None
  98. @staticmethod
  99. def _read_label(stream: typing.BinaryIO) -> Label:
  100. label = Label()
  101. label.index, name_length = struct.unpack('>II', stream.read(4 * 2))
  102. label.name = stream.read(name_length - 1).decode()
  103. assert stream.read(1) == b'\0'
  104. label.red, label.green, label.blue, label.transparency \
  105. = struct.unpack('>IIII', stream.read(4 * 4))
  106. return label
  107. def _read(self, stream: typing.BinaryIO) -> None:
  108. # https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles
  109. annotations_num, = struct.unpack('>I', stream.read(4))
  110. annotations = [struct.unpack('>II', stream.read(4 * 2))
  111. for _ in range(annotations_num)]
  112. assert stream.read(4) == self._TAG_OLD_COLORTABLE
  113. colortable_version, _, filename_length = struct.unpack('>III', stream.read(4 * 3))
  114. assert colortable_version > 0 # new version
  115. self.colortable_path = stream.read(filename_length - 1)
  116. assert stream.read(1) == b'\0'
  117. labels_num, = struct.unpack('>I', stream.read(4))
  118. self.labels = {label.index: label for label
  119. in (self._read_label(stream) for _ in range(labels_num))}
  120. label_index_by_color_code = {label.color_code: label.index
  121. for label in self.labels.values()}
  122. self.vertex_label_index = {vertex_index: label_index_by_color_code[color_code]
  123. for vertex_index, color_code in annotations}
  124. assert not stream.read(1)
  125. @classmethod
  126. def read(cls, annotation_file_path: str) -> 'Annotation':
  127. annotation = cls()
  128. with open(annotation_file_path, 'rb') as annotation_file:
  129. # pylint: disable=protected-access
  130. annotation._read(annotation_file)
  131. return annotation
  132. class Surface:
  133. # pylint: disable=too-many-instance-attributes
  134. _MAGIC_NUMBER = b'\xff\xff\xfe'
  135. _TAG_CMDLINE = b'\x00\x00\x00\x03'
  136. _TAG_OLD_SURF_GEOM = b'\x00\x00\x00\x14'
  137. _TAG_OLD_USEREALRAS = b'\x00\x00\x00\x02'
  138. _DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
  139. creator: typing.Optional[bytes] = None
  140. creation_datetime: typing.Optional[datetime.datetime] = None
  141. vertices: typing.List[Vertex] = []
  142. triangles: typing.List[Triangle] = []
  143. using_old_real_ras: bool = False
  144. volume_geometry_info: typing.Optional[typing.Tuple[bytes]] = None
  145. command_lines: typing.List[bytes] = []
  146. annotation: typing.Optional[Annotation] = None
  147. @classmethod
  148. def _read_cmdlines(cls, stream: typing.BinaryIO) -> typing.Iterator[str]:
  149. while True:
  150. tag = stream.read(4)
  151. if not tag:
  152. return
  153. assert tag == cls._TAG_CMDLINE # might be TAG_GROUP_AVG_SURFACE_AREA
  154. # TAGwrite
  155. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/tags.c#L94
  156. str_length, = struct.unpack('>Q', stream.read(8))
  157. yield stream.read(str_length - 1)
  158. assert stream.read(1) == b'\x00'
  159. def _read_triangular(self, stream: typing.BinaryIO):
  160. assert stream.read(3) == self._MAGIC_NUMBER
  161. self.creator, creation_dt_str = re.match(rb'^created by (\w+) on (.* \d{4})\n',
  162. stream.readline()).groups()
  163. with setlocale('C'):
  164. self.creation_datetime = datetime.datetime.strptime(creation_dt_str.decode(),
  165. self._DATETIME_FORMAT)
  166. assert stream.read(1) == b'\n'
  167. # fwriteInt
  168. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/fio.c#L290
  169. vertices_num, triangles_num = struct.unpack('>II', stream.read(4 * 2))
  170. self.vertices = [Vertex(*struct.unpack('>fff', stream.read(4 * 3)))
  171. for _ in range(vertices_num)]
  172. self.triangles = [Triangle(struct.unpack('>III', stream.read(4 * 3)))
  173. for _ in range(triangles_num)]
  174. assert all(vertex_idx < vertices_num
  175. for triangle in self.triangles
  176. for vertex_idx in triangle.vertex_indices)
  177. assert stream.read(4) == self._TAG_OLD_USEREALRAS
  178. using_old_real_ras, = struct.unpack('>I', stream.read(4))
  179. assert using_old_real_ras in [0, 1], using_old_real_ras
  180. self.using_old_real_ras = bool(using_old_real_ras)
  181. assert stream.read(4) == self._TAG_OLD_SURF_GEOM
  182. # writeVolGeom
  183. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/transform.c#L368
  184. self.volume_geometry_info = tuple(stream.readline() for _ in range(8))
  185. self.command_lines = list(self._read_cmdlines(stream))
  186. @classmethod
  187. def read_triangular(cls, surface_file_path: str) -> 'Surface':
  188. surface = cls()
  189. with open(surface_file_path, 'rb') as surface_file:
  190. # pylint: disable=protected-access
  191. surface._read_triangular(surface_file)
  192. return surface
  193. def _triangular_creation_datetime_strftime(self) -> bytes:
  194. fmt = self._DATETIME_FORMAT.replace('%d', '{:>2}'.format(self.creation_datetime.day))
  195. with setlocale('C'):
  196. return self.creation_datetime.strftime(fmt).encode()
  197. def write_triangular(self, surface_file_path: str,
  198. creation_datetime: typing.Optional[datetime.datetime] = None):
  199. if creation_datetime is None:
  200. self.creation_datetime = datetime.datetime.now()
  201. else:
  202. self.creation_datetime = creation_datetime
  203. with open(surface_file_path, 'wb') as surface_file:
  204. surface_file.write(
  205. self._MAGIC_NUMBER
  206. + b'created by ' + self.creator
  207. + b' on ' + self._triangular_creation_datetime_strftime()
  208. + b'\n\n'
  209. + struct.pack('>II', len(self.vertices), len(self.triangles))
  210. )
  211. for vertex in self.vertices:
  212. surface_file.write(struct.pack('>fff', *vertex))
  213. for triangle in self.triangles:
  214. surface_file.write(struct.pack('>III', *triangle.vertex_indices))
  215. surface_file.write(self._TAG_OLD_USEREALRAS
  216. + struct.pack('>I', 1 if self.using_old_real_ras else 0))
  217. surface_file.write(self._TAG_OLD_SURF_GEOM
  218. + b''.join(self.volume_geometry_info))
  219. for command_line in self.command_lines:
  220. surface_file.write(self._TAG_CMDLINE + struct.pack('>Q', len(command_line) + 1)
  221. + command_line + b'\0')
  222. def load_annotation_file(self, annotation_file_path: str) -> None:
  223. annotation = Annotation.read(annotation_file_path)
  224. assert len(annotation.vertex_label_index) <= len(self.vertices)
  225. assert max(annotation.vertex_label_index.keys()) < len(self.vertices)
  226. self.annotation = annotation
  227. def add_vertex(self, vertex: Vertex) -> int:
  228. self.vertices.append(vertex)
  229. return len(self.vertices) - 1