__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. Edit Surface File
  10. >>> from freesurfer_surface import Surface, Vertex, Triangle
  11. >>>
  12. >>> surface = Surface.read_triangular('bert/surf/lh.pial'))
  13. >>>
  14. >>> vertex_a = surface.add_vertex(Vertex(0.0, 0.0, 0.0))
  15. >>> vertex_b = surface.add_vertex(Vertex(1.0, 1.0, 1.0))
  16. >>> vertex_c = surface.add_vertex(Vertex(2.0, 2.0, 2.0))
  17. >>> surface.triangles.append(Triangle((vertex_a, vertex_b, vertex_c)))
  18. >>>
  19. >>> surface.write_triangular('somewhere/else/lh.pial')
  20. List Labels in Annotation File
  21. >>> from freesurfer_surface import Annotation
  22. >>>
  23. >>> annotation = Annotation.read('bert/label/lh.aparc.annot')
  24. >>> for label in annotation.labels.values():
  25. >>> print(label.index, label.hex_color_code, label.name)
  26. Find Border of Labelled Region
  27. >>> surface = Surface.read_triangular('bert/surf/lh.pial'))
  28. >>> surface.load_annotation_file('bert/label/lh.aparc.annot')
  29. >>> region, = filter(lambda l: l.name == 'precentral',
  30. >>> annotation.labels.values())
  31. >>> print(surface.find_label_border_polygonal_chains(region))
  32. """
  33. import collections
  34. import contextlib
  35. import datetime
  36. import itertools
  37. import locale
  38. import re
  39. import struct
  40. import typing
  41. import numpy
  42. try:
  43. from freesurfer_surface.version import __version__
  44. except ImportError: # pragma: no cover
  45. __version__ = None
  46. class UnsupportedLocaleSettingError(locale.Error):
  47. pass
  48. @contextlib.contextmanager
  49. def setlocale(temporary_locale):
  50. primary_locale = locale.setlocale(locale.LC_ALL)
  51. try:
  52. yield locale.setlocale(locale.LC_ALL, temporary_locale)
  53. except locale.Error as exc:
  54. if str(exc) == 'unsupported locale setting':
  55. raise UnsupportedLocaleSettingError(temporary_locale)
  56. raise exc
  57. finally:
  58. locale.setlocale(locale.LC_ALL, primary_locale)
  59. Vertex = collections.namedtuple('Vertex', ['right', 'anterior', 'superior'])
  60. class _PolygonalCircuit:
  61. _VERTEX_INDICES_TYPE = typing.Tuple[int]
  62. def __init__(self, vertex_indices: _VERTEX_INDICES_TYPE):
  63. self.vertex_indices: self._VERTEX_INDICES_TYPE = vertex_indices
  64. @property
  65. def vertex_indices(self):
  66. return self._vertex_indices
  67. @vertex_indices.setter
  68. def vertex_indices(self, indices: _VERTEX_INDICES_TYPE):
  69. # pylint: disable=attribute-defined-outside-init
  70. self._vertex_indices = tuple(indices)
  71. def _normalize(self) -> '_PolygonalCircuit':
  72. min_vertex_index_index = self.vertex_indices.index(min(self.vertex_indices))
  73. return type(self)(self.vertex_indices[min_vertex_index_index:]
  74. + self.vertex_indices[:min_vertex_index_index])
  75. def __eq__(self, other: '_PolygonalCircuit') -> bool:
  76. # pylint: disable=protected-access
  77. return self._normalize().vertex_indices == other._normalize().vertex_indices
  78. def __hash__(self) -> int:
  79. # pylint: disable=protected-access
  80. return hash(self._normalize()._vertex_indices)
  81. class _LineSegment(_PolygonalCircuit):
  82. # pylint: disable=no-member
  83. @_PolygonalCircuit.vertex_indices.setter
  84. def vertex_indices(self, indices: _PolygonalCircuit._VERTEX_INDICES_TYPE):
  85. assert len(indices) == 2
  86. # pylint: disable=attribute-defined-outside-init
  87. self._vertex_indices = tuple(indices)
  88. def __repr__(self) -> str:
  89. return '_LineSegment(vertex_indices={})'.format(self.vertex_indices)
  90. class Triangle(_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) == 3
  95. # pylint: disable=attribute-defined-outside-init
  96. self._vertex_indices = tuple(indices)
  97. def __repr__(self) -> str:
  98. return 'Triangle(vertex_indices={})'.format(self.vertex_indices)
  99. class PolygonalChainsNotOverlapingError(ValueError):
  100. pass
  101. class PolygonalChain:
  102. def __init__(self, vertex_indices: typing.Iterable[int]):
  103. self.vertex_indices: typing.Deque[int] \
  104. = collections.deque(vertex_indices)
  105. def __eq__(self, other: 'PolygonalChain') -> bool:
  106. return self.vertex_indices == other.vertex_indices
  107. def __repr__(self) -> str:
  108. return 'PolygonalChain(vertex_indices={})'.format(tuple(self.vertex_indices))
  109. def connect(self, other: 'PolygonalChain') -> None:
  110. if self.vertex_indices[-1] == other.vertex_indices[0]:
  111. self.vertex_indices.pop()
  112. self.vertex_indices.extend(other.vertex_indices)
  113. elif self.vertex_indices[-1] == other.vertex_indices[-1]:
  114. self.vertex_indices.pop()
  115. self.vertex_indices.extend(reversed(other.vertex_indices))
  116. elif self.vertex_indices[0] == other.vertex_indices[0]:
  117. self.vertex_indices.popleft()
  118. self.vertex_indices.extendleft(other.vertex_indices)
  119. elif self.vertex_indices[0] == other.vertex_indices[-1]:
  120. self.vertex_indices.popleft()
  121. self.vertex_indices.extendleft(reversed(other.vertex_indices))
  122. else:
  123. raise PolygonalChainsNotOverlapingError()
  124. def segments(self) -> typing.Iterable[_LineSegment]:
  125. indices = self.vertex_indices
  126. return map(_LineSegment, zip(indices, itertools.islice(indices, 1, len(indices))))
  127. class Label:
  128. # pylint: disable=too-many-arguments
  129. def __init__(self, index: int, name: str, red: int,
  130. green: int, blue: int, transparency: int):
  131. self.index: int = index
  132. self.name: str = name
  133. self.red: int = red
  134. self.green: int = green
  135. self.blue: int = blue
  136. self.transparency: int = transparency
  137. @property
  138. def color_code(self) -> int:
  139. if self.index == 0: # unknown
  140. return 0
  141. return int.from_bytes((self.red, self.green, self.blue, self.transparency),
  142. byteorder='little', signed=False)
  143. @property
  144. def hex_color_code(self) -> str:
  145. return '#{:02x}{:02x}{:02x}'.format(self.red, self.green, self.blue)
  146. def __str__(self) -> str:
  147. return 'Label(name={}, index={}, color={})'.format(
  148. self.name, self.index, self.hex_color_code)
  149. def __repr__(self) -> str:
  150. return str(self)
  151. class Annotation:
  152. # pylint: disable=too-few-public-methods
  153. _TAG_OLD_COLORTABLE = b'\0\0\0\x01'
  154. def __init__(self):
  155. self.vertex_label_index: typing.Dict[int, int] = {}
  156. self.colortable_path: typing.Optional[bytes] = None
  157. self.labels: typing.Dict[int, Label] = {}
  158. @staticmethod
  159. def _read_label(stream: typing.BinaryIO) -> Label:
  160. index, name_length = struct.unpack('>II', stream.read(4 * 2))
  161. name = stream.read(name_length - 1).decode()
  162. assert stream.read(1) == b'\0'
  163. red, green, blue, transparency \
  164. = struct.unpack('>IIII', stream.read(4 * 4))
  165. return Label(index=index, name=name, red=red, green=green,
  166. blue=blue, transparency=transparency)
  167. def _read(self, stream: typing.BinaryIO) -> None:
  168. # https://surfer.nmr.mgh.harvard.edu/fswiki/LabelsClutsAnnotationFiles
  169. annotations_num, = struct.unpack('>I', stream.read(4))
  170. annotations = [struct.unpack('>II', stream.read(4 * 2))
  171. for _ in range(annotations_num)]
  172. assert stream.read(4) == self._TAG_OLD_COLORTABLE
  173. colortable_version, _, filename_length \
  174. = struct.unpack('>III', stream.read(4 * 3))
  175. assert colortable_version > 0 # new version
  176. self.colortable_path = stream.read(filename_length - 1)
  177. assert stream.read(1) == b'\0'
  178. labels_num, = struct.unpack('>I', stream.read(4))
  179. self.labels = {label.index: label for label
  180. in (self._read_label(stream) for _ in range(labels_num))}
  181. label_index_by_color_code = {label.color_code: label.index
  182. for label in self.labels.values()}
  183. self.vertex_label_index = {vertex_index: label_index_by_color_code[color_code]
  184. for vertex_index, color_code in annotations}
  185. assert not stream.read(1)
  186. @classmethod
  187. def read(cls, annotation_file_path: str) -> 'Annotation':
  188. annotation = cls()
  189. with open(annotation_file_path, 'rb') as annotation_file:
  190. # pylint: disable=protected-access
  191. annotation._read(annotation_file)
  192. return annotation
  193. class Surface:
  194. # pylint: disable=too-many-instance-attributes
  195. _MAGIC_NUMBER = b'\xff\xff\xfe'
  196. _TAG_CMDLINE = b'\x00\x00\x00\x03'
  197. _TAG_OLD_SURF_GEOM = b'\x00\x00\x00\x14'
  198. _TAG_OLD_USEREALRAS = b'\x00\x00\x00\x02'
  199. _DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
  200. def __init__(self):
  201. self.creator: typing.Optional[bytes] = None
  202. self.creation_datetime: typing.Optional[datetime.datetime] = None
  203. self.vertices: typing.List[Vertex] = []
  204. self.triangles: typing.List[Triangle] = []
  205. self.using_old_real_ras: bool = False
  206. self.volume_geometry_info: typing.Optional[typing.Tuple[bytes]] = None
  207. self.command_lines: typing.List[bytes] = []
  208. self.annotation: typing.Optional[Annotation] = None
  209. @classmethod
  210. def _read_cmdlines(cls, stream: typing.BinaryIO) -> typing.Iterator[str]:
  211. while True:
  212. tag = stream.read(4)
  213. if not tag:
  214. return
  215. assert tag == cls._TAG_CMDLINE # might be TAG_GROUP_AVG_SURFACE_AREA
  216. # TAGwrite
  217. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/tags.c#L94
  218. str_length, = struct.unpack('>Q', stream.read(8))
  219. yield stream.read(str_length - 1)
  220. assert stream.read(1) == b'\x00'
  221. def _read_triangular(self, stream: typing.BinaryIO):
  222. assert stream.read(3) == self._MAGIC_NUMBER
  223. self.creator, creation_dt_str = re.match(rb'^created by (\w+) on (.* \d{4})\n',
  224. stream.readline()).groups()
  225. with setlocale('C'):
  226. self.creation_datetime = datetime.datetime.strptime(creation_dt_str.decode(),
  227. self._DATETIME_FORMAT)
  228. assert stream.read(1) == b'\n'
  229. # fwriteInt
  230. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/fio.c#L290
  231. vertices_num, triangles_num = struct.unpack('>II', stream.read(4 * 2))
  232. self.vertices = [Vertex(*struct.unpack('>fff', stream.read(4 * 3)))
  233. for _ in range(vertices_num)]
  234. self.triangles = [Triangle(struct.unpack('>III', stream.read(4 * 3)))
  235. for _ in range(triangles_num)]
  236. assert all(vertex_idx < vertices_num
  237. for triangle in self.triangles
  238. for vertex_idx in triangle.vertex_indices)
  239. assert stream.read(4) == self._TAG_OLD_USEREALRAS
  240. using_old_real_ras, = struct.unpack('>I', stream.read(4))
  241. assert using_old_real_ras in [0, 1], using_old_real_ras
  242. self.using_old_real_ras = bool(using_old_real_ras)
  243. assert stream.read(4) == self._TAG_OLD_SURF_GEOM
  244. # writeVolGeom
  245. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/transform.c#L368
  246. self.volume_geometry_info = tuple(stream.readline() for _ in range(8))
  247. self.command_lines = list(self._read_cmdlines(stream))
  248. @classmethod
  249. def read_triangular(cls, surface_file_path: str) -> 'Surface':
  250. surface = cls()
  251. with open(surface_file_path, 'rb') as surface_file:
  252. # pylint: disable=protected-access
  253. surface._read_triangular(surface_file)
  254. return surface
  255. def _triangular_creation_datetime_strftime(self) -> bytes:
  256. padded_day = '{:>2}'.format(self.creation_datetime.day)
  257. fmt = self._DATETIME_FORMAT.replace('%d', padded_day)
  258. with setlocale('C'):
  259. return self.creation_datetime.strftime(fmt).encode()
  260. def write_triangular(self, surface_file_path: str,
  261. creation_datetime: typing.Optional[datetime.datetime] = None):
  262. if creation_datetime is None:
  263. self.creation_datetime = datetime.datetime.now()
  264. else:
  265. self.creation_datetime = creation_datetime
  266. with open(surface_file_path, 'wb') as surface_file:
  267. surface_file.write(
  268. self._MAGIC_NUMBER
  269. + b'created by ' + self.creator
  270. + b' on ' + self._triangular_creation_datetime_strftime()
  271. + b'\n\n'
  272. + struct.pack('>II', len(self.vertices), len(self.triangles))
  273. )
  274. for vertex in self.vertices:
  275. surface_file.write(struct.pack('>fff', *vertex))
  276. for triangle in self.triangles:
  277. assert all(vertex_index < len(self.vertices)
  278. for vertex_index in triangle.vertex_indices)
  279. surface_file.write(struct.pack('>III',
  280. *triangle.vertex_indices))
  281. surface_file.write(self._TAG_OLD_USEREALRAS
  282. + struct.pack('>I', 1 if self.using_old_real_ras else 0))
  283. surface_file.write(self._TAG_OLD_SURF_GEOM
  284. + b''.join(self.volume_geometry_info))
  285. for command_line in self.command_lines:
  286. surface_file.write(self._TAG_CMDLINE + struct.pack('>Q', len(command_line) + 1)
  287. + command_line + b'\0')
  288. def load_annotation_file(self, annotation_file_path: str) -> None:
  289. annotation = Annotation.read(annotation_file_path)
  290. assert len(annotation.vertex_label_index) <= len(self.vertices)
  291. assert max(annotation.vertex_label_index.keys()) < len(self.vertices)
  292. self.annotation = annotation
  293. def add_vertex(self, vertex: Vertex) -> int:
  294. self.vertices.append(vertex)
  295. return len(self.vertices) - 1
  296. def add_rectangle(self, vertex_indices: typing.Iterable[int]) -> typing.Iterable[int]:
  297. vertex_indices = list(vertex_indices)
  298. assert len(vertex_indices) == 3
  299. vertex_coords = [numpy.array(self.vertices[vertex_index])
  300. for vertex_index in vertex_indices]
  301. vertex_coords.append(vertex_coords[0]
  302. + vertex_coords[2] - vertex_coords[1])
  303. vertex_indices.append(self.add_vertex(Vertex(*vertex_coords[3])))
  304. self.triangles.append(Triangle(vertex_indices[:3]))
  305. self.triangles.append(Triangle(vertex_indices[2:]
  306. + vertex_indices[:1]))
  307. def _find_label_border_segments(self, label: Label) -> typing.Iterator[_LineSegment]:
  308. for triangle in self.triangles:
  309. border_vertex_indices = tuple(filter(
  310. lambda i: self.annotation.vertex_label_index[i] == label.index,
  311. triangle.vertex_indices,
  312. ))
  313. if len(border_vertex_indices) == 2:
  314. yield _LineSegment(border_vertex_indices)
  315. def find_label_border_polygonal_chains(self, label: Label) -> typing.Iterator[PolygonalChain]:
  316. segments = set(self._find_label_border_segments(label))
  317. available_chains = collections.deque(PolygonalChain(segment.vertex_indices)
  318. for segment in segments)
  319. # irrespective of its poor performance,
  320. # we keep this approach since it's easy to read and fast enough
  321. while available_chains:
  322. chain = available_chains.pop()
  323. last_chains_len = None
  324. while last_chains_len != len(available_chains):
  325. last_chains_len = len(available_chains)
  326. checked_chains = collections.deque()
  327. while available_chains:
  328. potential_neighbour = available_chains.pop()
  329. try:
  330. chain.connect(potential_neighbour)
  331. except PolygonalChainsNotOverlapingError:
  332. checked_chains.append(potential_neighbour)
  333. available_chains = checked_chains
  334. assert all((segment in segments) for segment in chain.segments())
  335. yield chain