__init__.py 17 KB

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