__init__.py 8.2 KB

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