You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

519 lines
14 KiB

8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. import re
  2. from nd2reader.common import read_chunk, read_array, read_metadata, parse_date
  3. import xmltodict
  4. import six
  5. import numpy as np
  6. def ignore_missing(func):
  7. """
  8. Args:
  9. func:
  10. Returns:
  11. """
  12. def wrapper(*args, **kwargs):
  13. """
  14. Args:
  15. *args:
  16. **kwargs:
  17. Returns:
  18. """
  19. try:
  20. return func(*args, **kwargs)
  21. except:
  22. return None
  23. return wrapper
  24. class RawMetadata(object):
  25. """
  26. RawMetadata class parses and stores the raw metadata that is read from the binary file in dict format
  27. """
  28. def __init__(self, fh, label_map):
  29. self._fh = fh
  30. self._label_map = label_map
  31. self._metadata_parsed = None
  32. @property
  33. def __dict__(self):
  34. """Returns the parsed metadata in dictionary form
  35. """
  36. return self.get_parsed_metadata()
  37. def get_parsed_metadata(self):
  38. """ Returns the parsed metadata in dictionary form
  39. """
  40. if self._metadata_parsed is not None:
  41. return self._metadata_parsed
  42. self._metadata_parsed = {
  43. "height": self.image_attributes[six.b('SLxImageAttributes')][six.b('uiHeight')],
  44. "width": self.image_attributes[six.b('SLxImageAttributes')][six.b('uiWidth')],
  45. "date": parse_date(self.image_text_info[six.b('SLxImageTextInfo')]),
  46. "fields_of_view": self._parse_fields_of_view(),
  47. "frames": self._parse_frames(),
  48. "z_levels": self._parse_z_levels(),
  49. "total_images_per_channel": self._parse_total_images_per_channel(),
  50. "channels": self._parse_channels(),
  51. "pixel_microns": self.image_calibration.get(six.b('SLxCalibration'), {}).get(six.b('dCalibration')),
  52. }
  53. self._metadata_parsed['num_frames'] = len(self._metadata_parsed['frames'])
  54. self._parse_roi_metadata()
  55. self._parse_experiment_metadata()
  56. return self._metadata_parsed
  57. def _parse_channels(self):
  58. """
  59. These are labels created by the NIS Elements user. Typically they may a short description of the filter cube
  60. used (e.g. "bright field", "GFP", etc.)
  61. """
  62. channels = []
  63. metadata = self.image_metadata_sequence[six.b('SLxPictureMetadata')][six.b('sPicturePlanes')]
  64. try:
  65. validity = self.image_metadata[six.b('SLxExperiment')][six.b('ppNextLevelEx')][six.b('')][0][
  66. six.b('ppNextLevelEx')][six.b('')][0][six.b('pItemValid')]
  67. except (KeyError, TypeError):
  68. # If none of the channels have been deleted, there is no validity list, so we just make one
  69. validity = [True for _ in metadata]
  70. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  71. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  72. # we get the correct order.
  73. for (label, chan), valid in zip(sorted(metadata[six.b('sPlaneNew')].items()), validity):
  74. if not valid:
  75. continue
  76. channels.append(chan[six.b('sDescription')].decode("utf8"))
  77. return channels
  78. def _parse_fields_of_view(self):
  79. """
  80. The metadata contains information about fields of view, but it contains it even if some fields
  81. of view were cropped. We can't find anything that states which fields of view are actually
  82. in the image data, so we have to calculate it. There probably is something somewhere, since
  83. NIS Elements can figure it out, but we haven't found it yet.
  84. """
  85. return self._parse_dimension(r""".*?XY\((\d+)\).*?""")
  86. def _parse_frames(self):
  87. """The number of cycles.
  88. """
  89. return self._parse_dimension(r""".*?T'?\((\d+)\).*?""")
  90. def _parse_z_levels(self):
  91. """The different levels in the Z-plane.
  92. Just a sequence from 0 to n.
  93. """
  94. return self._parse_dimension(r""".*?Z\((\d+)\).*?""")
  95. def _parse_dimension_text(self):
  96. """
  97. While there are metadata values that represent a lot of what we want to capture, they seem to be unreliable.
  98. Sometimes certain elements don't exist, or change their data type randomly. However, the human-readable text
  99. is always there and in the same exact format, so we just parse that instead.
  100. """
  101. dimension_text = six.b("")
  102. textinfo = self.image_text_info[six.b('SLxImageTextInfo')].values()
  103. for line in textinfo:
  104. if six.b("Dimensions:") in line:
  105. entries = line.split(six.b("\r\n"))
  106. for entry in entries:
  107. if entry.startswith(six.b("Dimensions:")):
  108. return entry
  109. return dimension_text
  110. def _parse_dimension(self, pattern):
  111. dimension_text = self._parse_dimension_text()
  112. if six.PY3:
  113. dimension_text = dimension_text.decode("utf8")
  114. match = re.match(pattern, dimension_text)
  115. if not match:
  116. return [0]
  117. count = int(match.group(1))
  118. return list(range(count))
  119. def _parse_total_images_per_channel(self):
  120. """The total number of images per channel.
  121. Warning: this may be inaccurate as it includes "gap" images.
  122. """
  123. return self.image_attributes[six.b('SLxImageAttributes')][six.b('uiSequenceCount')]
  124. def _parse_roi_metadata(self):
  125. """Parse the raw ROI metadata.
  126. """
  127. if self.roi_metadata is None or not six.b('RoiMetadata_v1') in self.roi_metadata:
  128. return
  129. raw_roi_data = self.roi_metadata[six.b('RoiMetadata_v1')]
  130. number_of_rois = raw_roi_data[six.b('m_vectGlobal_Size')]
  131. roi_objects = []
  132. for i in range(number_of_rois):
  133. current_roi = raw_roi_data[six.b('m_vectGlobal_%d' % i)]
  134. roi_objects.append(self._parse_roi(current_roi))
  135. self._metadata_parsed['rois'] = roi_objects
  136. def _parse_roi(self, raw_roi_dict):
  137. """Extract the vector animation parameters from the ROI.
  138. This includes the position and size at the given timepoints.
  139. Args:
  140. raw_roi_dict:
  141. Returns:
  142. """
  143. number_of_timepoints = raw_roi_dict[six.b('m_vectAnimParams_Size')]
  144. roi_dict = {
  145. "timepoints": [],
  146. "positions": [],
  147. "sizes": [],
  148. "shape": self._parse_roi_shape(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiShapeType')]),
  149. "type": self._parse_roi_type(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiInterpType')])
  150. }
  151. for i in range(number_of_timepoints):
  152. roi_dict = self._parse_vect_anim(roi_dict, raw_roi_dict[six.b('m_vectAnimParams_%d' % i)])
  153. # convert to NumPy arrays
  154. roi_dict["timepoints"] = np.array(roi_dict["timepoints"], dtype=np.float)
  155. roi_dict["positions"] = np.array(roi_dict["positions"], dtype=np.float)
  156. roi_dict["sizes"] = np.array(roi_dict["sizes"], dtype=np.float)
  157. return roi_dict
  158. @staticmethod
  159. def _parse_roi_shape(shape):
  160. if shape == 3:
  161. return 'rectangle'
  162. elif shape == 9:
  163. return 'circle'
  164. return None
  165. @staticmethod
  166. def _parse_roi_type(type_no):
  167. if type_no == 4:
  168. return 'stimulation'
  169. elif type_no == 3:
  170. return 'reference'
  171. elif type_no == 2:
  172. return 'background'
  173. return None
  174. def _parse_vect_anim(self, roi_dict, animation_dict):
  175. """
  176. Parses a ROI vector animation object and adds it to the global list of timepoints and positions.
  177. Args:
  178. roi_dict:
  179. animation_dict:
  180. Returns:
  181. """
  182. roi_dict["timepoints"].append(animation_dict[six.b('m_dTimeMs')])
  183. image_width = self._metadata_parsed["width"] * self._metadata_parsed["pixel_microns"]
  184. image_height = self._metadata_parsed["height"] * self._metadata_parsed["pixel_microns"]
  185. # positions are taken from the center of the image as a fraction of the half width/height of the image
  186. position = np.array((0.5 * image_width * (1 + animation_dict[six.b('m_dCenterX')]),
  187. 0.5 * image_height * (1 + animation_dict[six.b('m_dCenterY')]),
  188. animation_dict[six.b('m_dCenterZ')]))
  189. roi_dict["positions"].append(position)
  190. size_dict = animation_dict[six.b('m_sBoxShape')]
  191. # sizes are fractions of the half width/height of the image
  192. roi_dict["sizes"].append((size_dict[six.b('m_dSizeX')] * 0.25 * image_width,
  193. size_dict[six.b('m_dSizeY')] * 0.25 * image_height,
  194. size_dict[six.b('m_dSizeZ')]))
  195. return roi_dict
  196. def _parse_experiment_metadata(self):
  197. """Parse the metadata of the ND experiment
  198. """
  199. if not six.b('SLxExperiment') in self.image_metadata:
  200. return
  201. raw_data = self.image_metadata[six.b('SLxExperiment')]
  202. experimental_data = {
  203. 'description': 'unknown',
  204. 'loops': []
  205. }
  206. if six.b('wsApplicationDesc') in raw_data:
  207. experimental_data['description'] = raw_data[six.b('wsApplicationDesc')].decode('utf8')
  208. if six.b('uLoopPars') in raw_data:
  209. experimental_data['loops'] = self._parse_loop_data(raw_data[six.b('uLoopPars')])
  210. self._metadata_parsed['experiment'] = experimental_data
  211. @staticmethod
  212. def _parse_loop_data(loop_data):
  213. """
  214. Parse the experimental loop data
  215. Args:
  216. loop_data:
  217. Returns:
  218. """
  219. loops = [loop_data]
  220. if six.b('uiPeriodCount') in loop_data and loop_data[six.b('uiPeriodCount')] > 0:
  221. # special ND experiment
  222. if six.b('pPeriod') not in loop_data:
  223. return []
  224. # take the first dictionary element, it contains all loop data
  225. loops = loop_data[six.b('pPeriod')][list(loop_data[six.b('pPeriod')].keys())[0]]
  226. # take into account the absolute time in ms
  227. time_offset = 0
  228. parsed_loops = []
  229. for loop in loops:
  230. # duration of this loop
  231. duration = loop[six.b('dDuration')]
  232. # uiLoopType == 6 is a stimulation loop
  233. is_stimulation = False
  234. if six.b('uiLoopType') in loop:
  235. is_stimulation = loop[six.b('uiLoopType')] == 6
  236. # sampling interval in ms
  237. interval = loop[six.b('dAvgPeriodDiff')]
  238. parsed_loop = {
  239. 'start': time_offset,
  240. 'duration': duration,
  241. 'stimulation': is_stimulation,
  242. 'sampling_interval': interval
  243. }
  244. parsed_loops.append(parsed_loop)
  245. # increase the time offset
  246. time_offset += duration
  247. return parsed_loops
  248. @property
  249. @ignore_missing
  250. def image_text_info(self):
  251. """
  252. Returns:
  253. """
  254. return read_metadata(read_chunk(self._fh, self._label_map.image_text_info), 1)
  255. @property
  256. @ignore_missing
  257. def image_metadata_sequence(self):
  258. """
  259. Returns:
  260. """
  261. return read_metadata(read_chunk(self._fh, self._label_map.image_metadata_sequence), 1)
  262. @property
  263. @ignore_missing
  264. def image_calibration(self):
  265. """
  266. Returns:
  267. """
  268. return read_metadata(read_chunk(self._fh, self._label_map.image_calibration), 1)
  269. @property
  270. @ignore_missing
  271. def image_attributes(self):
  272. """
  273. Returns:
  274. """
  275. return read_metadata(read_chunk(self._fh, self._label_map.image_attributes), 1)
  276. @property
  277. @ignore_missing
  278. def x_data(self):
  279. """
  280. Returns:
  281. """
  282. return read_array(self._fh, 'double', self._label_map.x_data)
  283. @property
  284. @ignore_missing
  285. def y_data(self):
  286. """
  287. Returns:
  288. """
  289. return read_array(self._fh, 'double', self._label_map.y_data)
  290. @property
  291. @ignore_missing
  292. def z_data(self):
  293. """
  294. Returns:
  295. """
  296. return read_array(self._fh, 'double', self._label_map.z_data)
  297. @property
  298. @ignore_missing
  299. def roi_metadata(self):
  300. """
  301. Returns:
  302. """
  303. return read_metadata(read_chunk(self._fh, self._label_map.roi_metadata), 1)
  304. @property
  305. @ignore_missing
  306. def pfs_status(self):
  307. """
  308. Returns:
  309. """
  310. return read_array(self._fh, 'int', self._label_map.pfs_status)
  311. @property
  312. @ignore_missing
  313. def pfs_offset(self):
  314. """
  315. Returns:
  316. """
  317. return read_array(self._fh, 'int', self._label_map.pfs_offset)
  318. @property
  319. @ignore_missing
  320. def camera_exposure_time(self):
  321. """
  322. Returns:
  323. """
  324. return read_array(self._fh, 'double', self._label_map.camera_exposure_time)
  325. @property
  326. @ignore_missing
  327. def lut_data(self):
  328. """
  329. Returns:
  330. """
  331. return xmltodict.parse(read_chunk(self._fh, self._label_map.lut_data))
  332. @property
  333. @ignore_missing
  334. def grabber_settings(self):
  335. """
  336. Returns:
  337. """
  338. return xmltodict.parse(read_chunk(self._fh, self._label_map.grabber_settings))
  339. @property
  340. @ignore_missing
  341. def custom_data(self):
  342. """
  343. Returns:
  344. """
  345. return xmltodict.parse(read_chunk(self._fh, self._label_map.custom_data))
  346. @property
  347. @ignore_missing
  348. def app_info(self):
  349. """
  350. Returns:
  351. """
  352. return xmltodict.parse(read_chunk(self._fh, self._label_map.app_info))
  353. @property
  354. @ignore_missing
  355. def camera_temp(self):
  356. """
  357. Yields:
  358. float: the temperature
  359. """
  360. camera_temp = read_array(self._fh, 'double', self._label_map.camera_temp)
  361. if camera_temp:
  362. for temp in map(lambda x: round(x * 100.0, 2), camera_temp):
  363. yield temp
  364. @property
  365. @ignore_missing
  366. def acquisition_times(self):
  367. """
  368. Yields:
  369. float: the acquisition time
  370. """
  371. acquisition_times = read_array(self._fh, 'double', self._label_map.acquisition_times)
  372. if acquisition_times:
  373. for acquisition_time in map(lambda x: x / 1000.0, acquisition_times):
  374. yield acquisition_time
  375. @property
  376. @ignore_missing
  377. def image_metadata(self):
  378. """
  379. Returns:
  380. """
  381. if self._label_map.image_metadata:
  382. return read_metadata(read_chunk(self._fh, self._label_map.image_metadata), 1)