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.

529 lines
16 KiB

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