__init__.py 20 KB

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