__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 PolygonalChain:
  54. def __init__(self, vertex_indices: typing.Iterable[int]):
  55. self.vertex_indices: typing.Deque[int] = collections.deque(vertex_indices)
  56. def __eq__(self, other: 'PolygonalChain') -> bool:
  57. return self.vertex_indices == other.vertex_indices
  58. def __repr__(self) -> str:
  59. return 'PolygonalChain(vertex_indices={})'.format(tuple(self.vertex_indices))
  60. def connect(self, other: 'PolygonalChain') -> None:
  61. if self.vertex_indices[-1] == other.vertex_indices[0]:
  62. self.vertex_indices.pop()
  63. self.vertex_indices.extend(other.vertex_indices)
  64. elif self.vertex_indices[-1] == other.vertex_indices[-1]:
  65. self.vertex_indices.pop()
  66. self.vertex_indices.extend(reversed(other.vertex_indices))
  67. elif self.vertex_indices[0] == other.vertex_indices[0]:
  68. self.vertex_indices.popleft()
  69. self.vertex_indices.extendleft(other.vertex_indices)
  70. elif self.vertex_indices[0] == other.vertex_indices[-1]:
  71. self.vertex_indices.popleft()
  72. self.vertex_indices.extendleft(reversed(other.vertex_indices))
  73. else:
  74. raise ValueError('polygonal chains do not overlap')
  75. class _PolygonalCircuit:
  76. _VERTEX_INDICES_TYPE = typing.Tuple[int]
  77. def __init__(self, vertex_indices: _VERTEX_INDICES_TYPE):
  78. self.vertex_indices: self._VERTEX_INDICES_TYPE = vertex_indices
  79. @property
  80. def vertex_indices(self):
  81. return self._vertex_indices
  82. @vertex_indices.setter
  83. def vertex_indices(self, indices: _VERTEX_INDICES_TYPE):
  84. # pylint: disable=attribute-defined-outside-init
  85. self._vertex_indices = indices
  86. def __eq__(self, other: '_PolygonalCircuit') -> bool:
  87. return self.vertex_indices == other.vertex_indices
  88. def __hash__(self) -> int:
  89. return hash(self._vertex_indices)
  90. class _LineSegment(_PolygonalCircuit):
  91. # pylint: disable=no-member
  92. @_PolygonalCircuit.vertex_indices.setter
  93. def vertex_indices(self, indices: _PolygonalCircuit._VERTEX_INDICES_TYPE):
  94. assert len(indices) == 2
  95. # pylint: disable=attribute-defined-outside-init
  96. self._vertex_indices = indices
  97. def __repr__(self) -> str:
  98. return '_LineSegment(vertex_indices={})'.format(self.vertex_indices)
  99. class Triangle(_PolygonalCircuit):
  100. # pylint: disable=no-member
  101. @_PolygonalCircuit.vertex_indices.setter
  102. def vertex_indices(self, indices: _PolygonalCircuit._VERTEX_INDICES_TYPE):
  103. assert len(indices) == 3
  104. # pylint: disable=attribute-defined-outside-init
  105. self._vertex_indices = indices
  106. def __repr__(self) -> str:
  107. return 'Triangle(vertex_indices={})'.format(self.vertex_indices)
  108. class Label:
  109. # pylint: disable=too-many-arguments
  110. def __init__(self, index: int, name: str, red: int,
  111. green: int, blue: int, transparency: int):
  112. self.index: int = index
  113. self.name: str = name
  114. self.red: int = red
  115. self.green: int = green
  116. self.blue: int = blue
  117. self.transparency: int = transparency
  118. @property
  119. def color_code(self) -> int:
  120. if self.index == 0: # unknown
  121. return 0
  122. return int.from_bytes((self.red, self.green, self.blue, self.transparency),
  123. byteorder='little', signed=False)
  124. @property
  125. def hex_color_code(self) -> str:
  126. return '#{:02x}{:02x}{:02x}'.format(self.red, self.green, self.blue)
  127. def __str__(self) -> str:
  128. return 'Label(name={}, index={}, color={})'.format(
  129. self.name, self.index, self.hex_color_code)
  130. def __repr__(self) -> str:
  131. return str(self)
  132. class Annotation:
  133. # pylint: disable=too-few-public-methods
  134. _TAG_OLD_COLORTABLE = b'\0\0\0\x01'
  135. def __init__(self):
  136. self.vertex_label_index: typing.Dict[int, int] = {}
  137. self.colortable_path: typing.Optional[bytes] = None
  138. self.labels: typing.Dict[int, Label] = {}
  139. @staticmethod
  140. def _read_label(stream: typing.BinaryIO) -> Label:
  141. index, name_length = struct.unpack('>II', stream.read(4 * 2))
  142. name = stream.read(name_length - 1).decode()
  143. assert stream.read(1) == b'\0'
  144. red, green, blue, transparency = struct.unpack('>IIII', stream.read(4 * 4))
  145. return Label(index=index, name=name, red=red, green=green,
  146. blue=blue, transparency=transparency)
  147. def _read(self, stream: typing.BinaryIO) -> None:
  148. # https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles
  149. annotations_num, = struct.unpack('>I', stream.read(4))
  150. annotations = [struct.unpack('>II', stream.read(4 * 2))
  151. for _ in range(annotations_num)]
  152. assert stream.read(4) == self._TAG_OLD_COLORTABLE
  153. colortable_version, _, filename_length = struct.unpack('>III', stream.read(4 * 3))
  154. assert colortable_version > 0 # new version
  155. self.colortable_path = stream.read(filename_length - 1)
  156. assert stream.read(1) == b'\0'
  157. labels_num, = struct.unpack('>I', stream.read(4))
  158. self.labels = {label.index: label for label
  159. in (self._read_label(stream) for _ in range(labels_num))}
  160. label_index_by_color_code = {label.color_code: label.index
  161. for label in self.labels.values()}
  162. self.vertex_label_index = {vertex_index: label_index_by_color_code[color_code]
  163. for vertex_index, color_code in annotations}
  164. assert not stream.read(1)
  165. @classmethod
  166. def read(cls, annotation_file_path: str) -> 'Annotation':
  167. annotation = cls()
  168. with open(annotation_file_path, 'rb') as annotation_file:
  169. # pylint: disable=protected-access
  170. annotation._read(annotation_file)
  171. return annotation
  172. class Surface:
  173. # pylint: disable=too-many-instance-attributes
  174. _MAGIC_NUMBER = b'\xff\xff\xfe'
  175. _TAG_CMDLINE = b'\x00\x00\x00\x03'
  176. _TAG_OLD_SURF_GEOM = b'\x00\x00\x00\x14'
  177. _TAG_OLD_USEREALRAS = b'\x00\x00\x00\x02'
  178. _DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
  179. def __init__(self):
  180. self.creator: typing.Optional[bytes] = None
  181. self.creation_datetime: typing.Optional[datetime.datetime] = None
  182. self.vertices: typing.List[Vertex] = []
  183. self.triangles: typing.List[Triangle] = []
  184. self.using_old_real_ras: bool = False
  185. self.volume_geometry_info: typing.Optional[typing.Tuple[bytes]] = None
  186. self.command_lines: typing.List[bytes] = []
  187. self.annotation: typing.Optional[Annotation] = None
  188. @classmethod
  189. def _read_cmdlines(cls, stream: typing.BinaryIO) -> typing.Iterator[str]:
  190. while True:
  191. tag = stream.read(4)
  192. if not tag:
  193. return
  194. assert tag == cls._TAG_CMDLINE # might be TAG_GROUP_AVG_SURFACE_AREA
  195. # TAGwrite
  196. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/tags.c#L94
  197. str_length, = struct.unpack('>Q', stream.read(8))
  198. yield stream.read(str_length - 1)
  199. assert stream.read(1) == b'\x00'
  200. def _read_triangular(self, stream: typing.BinaryIO):
  201. assert stream.read(3) == self._MAGIC_NUMBER
  202. self.creator, creation_dt_str = re.match(rb'^created by (\w+) on (.* \d{4})\n',
  203. stream.readline()).groups()
  204. with setlocale('C'):
  205. self.creation_datetime = datetime.datetime.strptime(creation_dt_str.decode(),
  206. self._DATETIME_FORMAT)
  207. assert stream.read(1) == b'\n'
  208. # fwriteInt
  209. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/fio.c#L290
  210. vertices_num, triangles_num = struct.unpack('>II', stream.read(4 * 2))
  211. self.vertices = [Vertex(*struct.unpack('>fff', stream.read(4 * 3)))
  212. for _ in range(vertices_num)]
  213. self.triangles = [Triangle(struct.unpack('>III', stream.read(4 * 3)))
  214. for _ in range(triangles_num)]
  215. assert all(vertex_idx < vertices_num
  216. for triangle in self.triangles
  217. for vertex_idx in triangle.vertex_indices)
  218. assert stream.read(4) == self._TAG_OLD_USEREALRAS
  219. using_old_real_ras, = struct.unpack('>I', stream.read(4))
  220. assert using_old_real_ras in [0, 1], using_old_real_ras
  221. self.using_old_real_ras = bool(using_old_real_ras)
  222. assert stream.read(4) == self._TAG_OLD_SURF_GEOM
  223. # writeVolGeom
  224. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/transform.c#L368
  225. self.volume_geometry_info = tuple(stream.readline() for _ in range(8))
  226. self.command_lines = list(self._read_cmdlines(stream))
  227. @classmethod
  228. def read_triangular(cls, surface_file_path: str) -> 'Surface':
  229. surface = cls()
  230. with open(surface_file_path, 'rb') as surface_file:
  231. # pylint: disable=protected-access
  232. surface._read_triangular(surface_file)
  233. return surface
  234. def _triangular_creation_datetime_strftime(self) -> bytes:
  235. fmt = self._DATETIME_FORMAT.replace('%d', '{:>2}'.format(self.creation_datetime.day))
  236. with setlocale('C'):
  237. return self.creation_datetime.strftime(fmt).encode()
  238. def write_triangular(self, surface_file_path: str,
  239. creation_datetime: typing.Optional[datetime.datetime] = None):
  240. if creation_datetime is None:
  241. self.creation_datetime = datetime.datetime.now()
  242. else:
  243. self.creation_datetime = creation_datetime
  244. with open(surface_file_path, 'wb') as surface_file:
  245. surface_file.write(
  246. self._MAGIC_NUMBER
  247. + b'created by ' + self.creator
  248. + b' on ' + self._triangular_creation_datetime_strftime()
  249. + b'\n\n'
  250. + struct.pack('>II', len(self.vertices), len(self.triangles))
  251. )
  252. for vertex in self.vertices:
  253. surface_file.write(struct.pack('>fff', *vertex))
  254. for triangle in self.triangles:
  255. surface_file.write(struct.pack('>III', *triangle.vertex_indices))
  256. surface_file.write(self._TAG_OLD_USEREALRAS
  257. + struct.pack('>I', 1 if self.using_old_real_ras else 0))
  258. surface_file.write(self._TAG_OLD_SURF_GEOM
  259. + b''.join(self.volume_geometry_info))
  260. for command_line in self.command_lines:
  261. surface_file.write(self._TAG_CMDLINE + struct.pack('>Q', len(command_line) + 1)
  262. + command_line + b'\0')
  263. def load_annotation_file(self, annotation_file_path: str) -> None:
  264. annotation = Annotation.read(annotation_file_path)
  265. assert len(annotation.vertex_label_index) <= len(self.vertices)
  266. assert max(annotation.vertex_label_index.keys()) < len(self.vertices)
  267. self.annotation = annotation
  268. def add_vertex(self, vertex: Vertex) -> int:
  269. self.vertices.append(vertex)
  270. return len(self.vertices) - 1
  271. def _find_label_border_segments(self, label: Label) -> typing.Iterator[_LineSegment]:
  272. for triangle in self.triangles:
  273. border_vertex_indices = tuple(filter(
  274. lambda i: self.annotation.vertex_label_index[i] == label.index,
  275. triangle.vertex_indices,
  276. ))
  277. if len(border_vertex_indices) == 2:
  278. yield _LineSegment(border_vertex_indices)