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.

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