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.

551 lines
17 KiB

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