__init__.py 9.6 KB

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