__init__.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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 datetime
  20. import re
  21. import struct
  22. import typing
  23. try:
  24. from freesurfer_surface.version import __version__
  25. except ImportError: # pragma: no cover
  26. __version__ = None
  27. Vertex = collections.namedtuple('Vertex', ['right', 'anterior', 'superior'])
  28. class Surface:
  29. _MAGIC_NUMBER = b'\xff\xff\xfe'
  30. _TAG_CMDLINE = b'\x00\x00\x00\x03'
  31. _TAG_OLD_SURF_GEOM = b'\x00\x00\x00\x14'
  32. _TAG_OLD_USEREALRAS = b'\x00\x00\x00\x02'
  33. # TODO set locale
  34. _DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
  35. def __init__(self):
  36. self.creator = None
  37. self.creation_datetime = None
  38. self.vertices = []
  39. self.triangles_vertex_indices = []
  40. # self._triangles = []
  41. self.using_old_real_ras = False
  42. self.volume_geometry_info = None
  43. self.command_lines = []
  44. @classmethod
  45. def _read_cmdlines(cls, stream: typing.BinaryIO) -> typing.Iterator[str]:
  46. while True:
  47. tag = stream.read(4)
  48. if not tag:
  49. return
  50. assert tag == cls._TAG_CMDLINE # might be TAG_GROUP_AVG_SURFACE_AREA
  51. # TAGwrite
  52. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/tags.c#L94
  53. str_length, = struct.unpack('>Q', stream.read(8))
  54. yield stream.read(str_length - 1)
  55. assert stream.read(1) == b'\x00'
  56. def _read_triangular(self, stream: typing.BinaryIO):
  57. assert stream.read(3) == self._MAGIC_NUMBER
  58. self.creator, creation_dt_str = re.match(rb'^created by (\w+) on (.* \d{4})\n',
  59. stream.readline()).groups()
  60. self.creation_datetime = datetime.datetime.strptime(creation_dt_str.decode(),
  61. self._DATETIME_FORMAT)
  62. assert stream.read(1) == b'\n'
  63. # fwriteInt
  64. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/fio.c#L290
  65. vertices_num, triangles_num = struct.unpack('>II', stream.read(4 * 2))
  66. self.vertices = [Vertex(*struct.unpack('>fff', stream.read(4 * 3)))
  67. for _ in range(vertices_num)]
  68. self.triangles_vertex_indices = [struct.unpack('>III', stream.read(4 * 3))
  69. for _ in range(triangles_num)]
  70. assert all(vertex_idx < vertices_num
  71. for triangle_vertex_index in self.triangles_vertex_indices
  72. for vertex_idx in triangle_vertex_index)
  73. assert stream.read(4) == self._TAG_OLD_USEREALRAS
  74. using_old_real_ras, = struct.unpack('>I', stream.read(4))
  75. assert using_old_real_ras in [0, 1], using_old_real_ras
  76. self.using_old_real_ras = bool(using_old_real_ras)
  77. assert stream.read(4) == self._TAG_OLD_SURF_GEOM
  78. # writeVolGeom
  79. # https://github.com/freesurfer/freesurfer/blob/release_6_0_0/utils/transform.c#L368
  80. self.volume_geometry_info = tuple(stream.readline() for _ in range(8))
  81. self.command_lines = list(self._read_cmdlines(stream))
  82. @classmethod
  83. def read_triangular(cls, surface_file_path: str) -> 'Surface':
  84. surface = cls()
  85. with open(surface_file_path, 'rb') as surface_file:
  86. # pylint: disable=protected-access
  87. surface._read_triangular(surface_file)
  88. return surface
  89. def _triangular_creation_datetime_strftime(self) -> bytes:
  90. fmt = self._DATETIME_FORMAT.replace('%d', '{:>2}'.format(self.creation_datetime.day))
  91. return self.creation_datetime.strftime(fmt).encode()
  92. def write_triangular(self, surface_file_path: str,
  93. creation_datetime: typing.Optional[datetime.datetime] = None):
  94. if creation_datetime is None:
  95. creation_datetime = datetime.datetime.now()
  96. with open(surface_file_path, 'wb') as surface_file:
  97. surface_file.write(
  98. self._MAGIC_NUMBER
  99. + b'created by ' + self.creator
  100. + b' on ' + self._triangular_creation_datetime_strftime()
  101. + b'\n\n'
  102. + struct.pack('>II', len(self.vertices), len(self.triangles_vertex_indices))
  103. )
  104. for vertex in self.vertices:
  105. surface_file.write(struct.pack('>fff', *vertex))
  106. for triangle_vertex_indices in self.triangles_vertex_indices:
  107. surface_file.write(struct.pack('>III', *triangle_vertex_indices))
  108. surface_file.write(self._TAG_OLD_USEREALRAS
  109. + struct.pack('>I', 1 if self.using_old_real_ras else 0))
  110. surface_file.write(self._TAG_OLD_SURF_GEOM
  111. + b''.join(self.volume_geometry_info))
  112. for command_line in self.command_lines:
  113. surface_file.write(self._TAG_CMDLINE + struct.pack('>Q', len(command_line) + 1)
  114. + command_line + b'\0')
  115. def add_vertex(self, vertex: Vertex) -> int:
  116. self.vertices.append(vertex)
  117. return len(self.vertices) - 1