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.

646 lines
20 KiB

6 years ago
8 years ago
6 years ago
5 years ago
5 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
7 years ago
7 years ago
5 years ago
6 years ago
9 years ago
9 years ago
5 years ago
8 years ago
8 years ago
8 years ago
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
6 years ago
7 years ago
7 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
5 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. import xmltodict
  3. import six
  4. import numpy as np
  5. import warnings
  6. from nd2reader.common import read_chunk, read_array, read_metadata, parse_date, get_from_dict_if_exists
  7. from nd2reader.common_raw_metadata import parse_dimension_text_line, parse_if_not_none, parse_roi_shape, parse_roi_type, get_loops_from_data, determine_sampling_interval
  8. class RawMetadata(object):
  9. """RawMetadata class parses and stores the raw metadata that is read from the binary file in dict format.
  10. """
  11. def __init__(self, fh, label_map):
  12. self._fh = fh
  13. self._label_map = label_map
  14. self._metadata_parsed = None
  15. @property
  16. def __dict__(self):
  17. """Returns the parsed metadata in dictionary form.
  18. Returns:
  19. dict: the parsed metadata
  20. """
  21. return self.get_parsed_metadata()
  22. def get_parsed_metadata(self):
  23. """Returns the parsed metadata in dictionary form.
  24. Returns:
  25. dict: the parsed metadata
  26. """
  27. if self._metadata_parsed is not None:
  28. return self._metadata_parsed
  29. frames_per_channel = self._parse_total_images_per_channel()
  30. self._metadata_parsed = {
  31. "height": parse_if_not_none(self.image_attributes, self._parse_height),
  32. "width": parse_if_not_none(self.image_attributes, self._parse_width),
  33. "date": parse_if_not_none(self.image_text_info, self._parse_date),
  34. "fields_of_view": self._parse_fields_of_view(),
  35. "frames": self._parse_frames(),
  36. "z_levels": self._parse_z_levels(),
  37. "z_coordinates": parse_if_not_none(self.z_data, self._parse_z_coordinates),
  38. "total_images_per_channel": frames_per_channel,
  39. "channels": self._parse_channels(),
  40. "pixel_microns": parse_if_not_none(self.image_calibration, self._parse_calibration)
  41. }
  42. self._set_default_if_not_empty('fields_of_view')
  43. self._set_default_if_not_empty('frames')
  44. self._metadata_parsed['num_frames'] = len(self._metadata_parsed['frames'])
  45. self._parse_roi_metadata()
  46. self._parse_experiment_metadata()
  47. self._parse_events()
  48. return self._metadata_parsed
  49. def _set_default_if_not_empty(self, entry):
  50. total_images = self._metadata_parsed['total_images_per_channel'] \
  51. if self._metadata_parsed['total_images_per_channel'] is not None else 0
  52. if len(self._metadata_parsed[entry]) == 0 and total_images > 0:
  53. # if the file is not empty, we always have one of this entry
  54. self._metadata_parsed[entry] = [0]
  55. def _parse_width_or_height(self, key):
  56. try:
  57. length = self.image_attributes[six.b('SLxImageAttributes')][six.b(key)]
  58. except KeyError:
  59. length = None
  60. return length
  61. def _parse_height(self):
  62. return self._parse_width_or_height('uiHeight')
  63. def _parse_width(self):
  64. return self._parse_width_or_height('uiWidth')
  65. def _parse_date(self):
  66. try:
  67. return parse_date(self.image_text_info[six.b('SLxImageTextInfo')])
  68. except KeyError:
  69. return None
  70. def _parse_calibration(self):
  71. try:
  72. return self.image_calibration.get(six.b('SLxCalibration'), {}).get(six.b('dCalibration'))
  73. except KeyError:
  74. return None
  75. def _parse_frames(self):
  76. """The number of cycles.
  77. Returns:
  78. list: list of all the frame numbers
  79. """
  80. return self._parse_dimension(r""".*?T'?\((\d+)\).*?""")
  81. def _parse_channels(self):
  82. """These are labels created by the NIS Elements user. Typically they may a short description of the filter cube
  83. used (e.g. 'bright field', 'GFP', etc.)
  84. Returns:
  85. list: the color channels
  86. """
  87. if self.image_metadata_sequence is None:
  88. return []
  89. try:
  90. metadata = self.image_metadata_sequence[six.b('SLxPictureMetadata')][six.b('sPicturePlanes')]
  91. except KeyError:
  92. return []
  93. channels = self._process_channels_metadata(metadata)
  94. return channels
  95. def _process_channels_metadata(self, metadata):
  96. validity = self._get_channel_validity_list(metadata)
  97. # Channel information is contained in dictionaries with the keys a0, a1...an where the number
  98. # indicates the order in which the channel is stored. So by sorting the dicts alphabetically
  99. # we get the correct order.
  100. channels = []
  101. for valid, (label, chan) in zip(validity, sorted(metadata[six.b('sPlaneNew')].items())):
  102. if not valid:
  103. continue
  104. if chan[six.b('sDescription')] is not None:
  105. channels.append(chan[six.b('sDescription')].decode("utf8"))
  106. else:
  107. channels.append('Unknown')
  108. return channels
  109. def _get_channel_validity_list(self, metadata):
  110. try:
  111. validity = self.image_metadata[six.b('SLxExperiment')][six.b('ppNextLevelEx')][six.b('')][0][
  112. six.b('ppNextLevelEx')][six.b('')][0][six.b('pItemValid')]
  113. except (KeyError, TypeError):
  114. # If none of the channels have been deleted, there is no validity list, so we just make one
  115. validity = [True for _ in metadata]
  116. return validity
  117. def _parse_fields_of_view(self):
  118. """The metadata contains information about fields of view, but it contains it even if some fields
  119. of view were cropped. We can't find anything that states which fields of view are actually
  120. in the image data, so we have to calculate it. There probably is something somewhere, since
  121. NIS Elements can figure it out, but we haven't found it yet.
  122. """
  123. return self._parse_dimension(r""".*?XY\((\d+)\).*?""")
  124. def _parse_z_levels(self):
  125. """The different levels in the Z-plane.
  126. Returns:
  127. list: the z levels, just a sequence from 0 to n.
  128. """
  129. z_levels = self._parse_dimension(r""".*?Z\((\d+)\).*?""")
  130. if 0 == len(z_levels):
  131. z_levels = parse_if_not_none(self.z_data, self._parse_z_coordinates)
  132. if z_levels is None:
  133. z_levels = []
  134. else:
  135. z_levels = range(len(z_levels))
  136. warnings.warn("Z-levels details missing in metadata. Using Z-coordinates instead.")
  137. return z_levels
  138. def _parse_z_coordinates(self):
  139. """The coordinate in micron for all z planes.
  140. Returns:
  141. list: the z coordinates in micron
  142. """
  143. return self.z_data.tolist()
  144. def _parse_dimension_text(self):
  145. """While there are metadata values that represent a lot of what we want to capture, they seem to be unreliable.
  146. Sometimes certain elements don't exist, or change their data type randomly. However, the human-readable text
  147. is always there and in the same exact format, so we just parse that instead.
  148. """
  149. dimension_text = six.b("")
  150. if self.image_text_info is None:
  151. return dimension_text
  152. try:
  153. textinfo = self.image_text_info[six.b('SLxImageTextInfo')].values()
  154. except KeyError:
  155. return dimension_text
  156. for line in textinfo:
  157. entry = parse_dimension_text_line(line)
  158. if entry is not None:
  159. return entry
  160. return dimension_text
  161. def _parse_dimension(self, pattern):
  162. dimension_text = self._parse_dimension_text()
  163. if dimension_text is None:
  164. return []
  165. if six.PY3:
  166. dimension_text = dimension_text.decode("utf8")
  167. match = re.match(pattern, dimension_text)
  168. if not match:
  169. return []
  170. count = int(match.group(1))
  171. return range(count)
  172. def _parse_total_images_per_channel(self):
  173. """The total number of images per channel.
  174. Warning: this may be inaccurate as it includes 'gap' images.
  175. """
  176. if self.image_attributes is None:
  177. return 0
  178. try:
  179. total_images = self.image_attributes[six.b('SLxImageAttributes')][six.b('uiSequenceCount')]
  180. except KeyError:
  181. total_images = None
  182. return total_images
  183. def _parse_roi_metadata(self):
  184. """Parse the raw ROI metadata.
  185. """
  186. if self.roi_metadata is None or not six.b('RoiMetadata_v1') in self.roi_metadata:
  187. return
  188. raw_roi_data = self.roi_metadata[six.b('RoiMetadata_v1')]
  189. if not six.b('m_vectGlobal_Size') in raw_roi_data:
  190. return
  191. number_of_rois = raw_roi_data[six.b('m_vectGlobal_Size')]
  192. roi_objects = []
  193. for i in range(number_of_rois):
  194. current_roi = raw_roi_data[six.b('m_vectGlobal_%d' % i)]
  195. roi_objects.append(self._parse_roi(current_roi))
  196. self._metadata_parsed['rois'] = roi_objects
  197. def _parse_roi(self, raw_roi_dict):
  198. """Extract the vector animation parameters from the ROI.
  199. This includes the position and size at the given timepoints.
  200. Args:
  201. raw_roi_dict: dictionary of raw roi metadata
  202. Returns:
  203. dict: the parsed ROI metadata
  204. """
  205. number_of_timepoints = raw_roi_dict[six.b('m_vectAnimParams_Size')]
  206. roi_dict = {
  207. "timepoints": [],
  208. "positions": [],
  209. "sizes": [],
  210. "shape": parse_roi_shape(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiShapeType')]),
  211. "type": parse_roi_type(raw_roi_dict[six.b('m_sInfo')][six.b('m_uiInterpType')])
  212. }
  213. for i in range(number_of_timepoints):
  214. roi_dict = self._parse_vect_anim(roi_dict, raw_roi_dict[six.b('m_vectAnimParams_%d' % i)])
  215. # convert to NumPy arrays
  216. roi_dict["timepoints"] = np.array(roi_dict["timepoints"], dtype=np.float)
  217. roi_dict["positions"] = np.array(roi_dict["positions"], dtype=np.float)
  218. roi_dict["sizes"] = np.array(roi_dict["sizes"], dtype=np.float)
  219. return roi_dict
  220. def _parse_vect_anim(self, roi_dict, animation_dict):
  221. """
  222. Parses a ROI vector animation object and adds it to the global list of timepoints and positions.
  223. Args:
  224. roi_dict: the raw roi dictionary
  225. animation_dict: the raw animation dictionary
  226. Returns:
  227. dict: the parsed metadata
  228. """
  229. roi_dict["timepoints"].append(animation_dict[six.b('m_dTimeMs')])
  230. image_width = self._metadata_parsed["width"] * self._metadata_parsed["pixel_microns"]
  231. image_height = self._metadata_parsed["height"] * self._metadata_parsed["pixel_microns"]
  232. # positions are taken from the center of the image as a fraction of the half width/height of the image
  233. position = np.array((0.5 * image_width * (1 + animation_dict[six.b('m_dCenterX')]),
  234. 0.5 * image_height * (1 + animation_dict[six.b('m_dCenterY')]),
  235. animation_dict[six.b('m_dCenterZ')]))
  236. roi_dict["positions"].append(position)
  237. size_dict = animation_dict[six.b('m_sBoxShape')]
  238. # sizes are fractions of the half width/height of the image
  239. roi_dict["sizes"].append((size_dict[six.b('m_dSizeX')] * 0.25 * image_width,
  240. size_dict[six.b('m_dSizeY')] * 0.25 * image_height,
  241. size_dict[six.b('m_dSizeZ')]))
  242. return roi_dict
  243. def _parse_experiment_metadata(self):
  244. """Parse the metadata of the ND experiment
  245. """
  246. self._metadata_parsed['experiment'] = {
  247. 'description': 'unknown',
  248. 'loops': []
  249. }
  250. if self.image_metadata is None or six.b('SLxExperiment') not in self.image_metadata:
  251. return
  252. raw_data = self.image_metadata[six.b('SLxExperiment')]
  253. if six.b('wsApplicationDesc') in raw_data:
  254. self._metadata_parsed['experiment']['description'] = raw_data[six.b('wsApplicationDesc')].decode('utf8')
  255. if six.b('uLoopPars') in raw_data:
  256. self._metadata_parsed['experiment']['loops'] = self._parse_loop_data(raw_data[six.b('uLoopPars')])
  257. def _parse_loop_data(self, loop_data):
  258. """Parse the experimental loop data
  259. Args:
  260. loop_data: dictionary of experiment loops
  261. Returns:
  262. list: list of the parsed loops
  263. """
  264. loops = get_loops_from_data(loop_data)
  265. # take into account the absolute time in ms
  266. time_offset = 0
  267. parsed_loops = []
  268. for loop in loops:
  269. # duration of this loop
  270. duration = get_from_dict_if_exists('dDuration', loop) or 0
  271. interval = determine_sampling_interval(duration, loop)
  272. # if duration is not saved, infer it
  273. duration = self.get_duration_from_interval_and_loops(duration, interval, loop)
  274. # uiLoopType == 6 is a stimulation loop
  275. is_stimulation = get_from_dict_if_exists('uiLoopType', loop) == 6
  276. parsed_loop = {
  277. 'start': time_offset,
  278. 'duration': duration,
  279. 'stimulation': is_stimulation,
  280. 'sampling_interval': interval
  281. }
  282. parsed_loops.append(parsed_loop)
  283. # increase the time offset
  284. time_offset += duration
  285. return parsed_loops
  286. def get_duration_from_interval_and_loops(self, duration, interval, loop):
  287. """Infers the duration of the loop from the number of measurements and the interval
  288. Args:
  289. duration: loop duration in milliseconds
  290. duration: measurement interval in milliseconds
  291. loop: loop dictionary
  292. Returns:
  293. float: the loop duration in milliseconds
  294. """
  295. if duration == 0 and interval > 0:
  296. number_of_loops = get_from_dict_if_exists('uiCount', loop)
  297. number_of_loops = number_of_loops if number_of_loops is not None and number_of_loops > 0 else 1
  298. duration = interval * number_of_loops
  299. return duration
  300. def _parse_events(self):
  301. """Extract events
  302. """
  303. # list of event names manually extracted from an ND2 file that contains all manually
  304. # insertable events from NIS-Elements software (4.60.00 (Build 1171) Patch 02)
  305. event_names = {
  306. 1: 'Autofocus',
  307. 7: 'Command Executed',
  308. 9: 'Experiment Paused',
  309. 10: 'Experiment Resumed',
  310. 11: 'Experiment Stopped by User',
  311. 13: 'Next Phase Moved by User',
  312. 14: 'Experiment Paused for Refocusing',
  313. 16: 'External Stimulation',
  314. 33: 'User 1',
  315. 34: 'User 2',
  316. 35: 'User 3',
  317. 36: 'User 4',
  318. 37: 'User 5',
  319. 38: 'User 6',
  320. 39: 'User 7',
  321. 40: 'User 8',
  322. 44: 'No Acquisition Phase Start',
  323. 45: 'No Acquisition Phase End',
  324. 46: 'Hardware Error',
  325. 47: 'N-STORM',
  326. 48: 'Incubation Info',
  327. 49: 'Incubation Error'
  328. }
  329. self._metadata_parsed['events'] = []
  330. events = read_metadata(read_chunk(self._fh, self._label_map.image_events), 1)
  331. if events is None or six.b('RLxExperimentRecord') not in events:
  332. return
  333. events = events[six.b('RLxExperimentRecord')][six.b('pEvents')]
  334. if len(events) == 0:
  335. return
  336. for event in events[six.b('')]:
  337. event_info = {
  338. 'index': event[six.b('I')],
  339. 'time': event[six.b('T')],
  340. 'type': event[six.b('M')],
  341. }
  342. if event_info['type'] in event_names.keys():
  343. event_info['name'] = event_names[event_info['type']]
  344. self._metadata_parsed['events'].append(event_info)
  345. @property
  346. def image_text_info(self):
  347. """Textual image information
  348. Returns:
  349. dict: containing the textual image info
  350. """
  351. return read_metadata(read_chunk(self._fh, self._label_map.image_text_info), 1)
  352. @property
  353. def image_metadata_sequence(self):
  354. """Image metadata of the sequence
  355. Returns:
  356. dict: containing the metadata
  357. """
  358. return read_metadata(read_chunk(self._fh, self._label_map.image_metadata_sequence), 1)
  359. @property
  360. def image_calibration(self):
  361. """The amount of pixels per micron.
  362. Returns:
  363. dict: pixels per micron
  364. """
  365. return read_metadata(read_chunk(self._fh, self._label_map.image_calibration), 1)
  366. @property
  367. def image_attributes(self):
  368. """Image attributes
  369. Returns:
  370. dict: containing the image attributes
  371. """
  372. return read_metadata(read_chunk(self._fh, self._label_map.image_attributes), 1)
  373. @property
  374. def x_data(self):
  375. """X data
  376. Returns:
  377. dict: x_data
  378. """
  379. return read_array(self._fh, 'double', self._label_map.x_data)
  380. @property
  381. def y_data(self):
  382. """Y data
  383. Returns:
  384. dict: y_data
  385. """
  386. return read_array(self._fh, 'double', self._label_map.y_data)
  387. @property
  388. def z_data(self):
  389. """Z data
  390. Returns:
  391. dict: z_data
  392. """
  393. try:
  394. return read_array(self._fh, 'double', self._label_map.z_data)
  395. except ValueError:
  396. # Depending on the file format/exact settings, this value is
  397. # sometimes saved as float instead of double
  398. return read_array(self._fh, 'float', self._label_map.z_data)
  399. @property
  400. def roi_metadata(self):
  401. """Contains information about the defined ROIs: shape, position and type (reference/background/stimulation).
  402. Returns:
  403. dict: ROI metadata dictionary
  404. """
  405. return read_metadata(read_chunk(self._fh, self._label_map.roi_metadata), 1)
  406. @property
  407. def pfs_status(self):
  408. """Perfect focus system (PFS) status
  409. Returns:
  410. dict: Perfect focus system (PFS) status
  411. """
  412. return read_array(self._fh, 'int', self._label_map.pfs_status)
  413. @property
  414. def pfs_offset(self):
  415. """Perfect focus system (PFS) offset
  416. Returns:
  417. dict: Perfect focus system (PFS) offset
  418. """
  419. return read_array(self._fh, 'int', self._label_map.pfs_offset)
  420. @property
  421. def camera_exposure_time(self):
  422. """Exposure time information
  423. Returns:
  424. dict: Camera exposure time
  425. """
  426. return read_array(self._fh, 'double', self._label_map.camera_exposure_time)
  427. @property
  428. def lut_data(self):
  429. """LUT information
  430. Returns:
  431. dict: LUT information
  432. """
  433. return xmltodict.parse(read_chunk(self._fh, self._label_map.lut_data))
  434. @property
  435. def grabber_settings(self):
  436. """Grabber settings
  437. Returns:
  438. dict: Acquisition settings
  439. """
  440. return xmltodict.parse(read_chunk(self._fh, self._label_map.grabber_settings))
  441. @property
  442. def custom_data(self):
  443. """Custom user data
  444. Returns:
  445. dict: custom user data
  446. """
  447. return xmltodict.parse(read_chunk(self._fh, self._label_map.custom_data))
  448. @property
  449. def app_info(self):
  450. """NIS elements application info
  451. Returns:
  452. dict: (Version) information of the NIS Elements application
  453. """
  454. return xmltodict.parse(read_chunk(self._fh, self._label_map.app_info))
  455. @property
  456. def camera_temp(self):
  457. """Camera temperature
  458. Yields:
  459. float: the temperature
  460. """
  461. camera_temp = read_array(self._fh, 'double', self._label_map.camera_temp)
  462. if camera_temp:
  463. for temp in map(lambda x: round(x * 100.0, 2), camera_temp):
  464. yield temp
  465. @property
  466. def acquisition_times(self):
  467. """Acquisition times
  468. Yields:
  469. float: the acquisition time
  470. """
  471. acquisition_times = read_array(self._fh, 'double', self._label_map.acquisition_times)
  472. if acquisition_times:
  473. for acquisition_time in map(lambda x: x / 1000.0, acquisition_times):
  474. yield acquisition_time
  475. @property
  476. def image_metadata(self):
  477. """Image metadata
  478. Returns:
  479. dict: Extra image metadata
  480. """
  481. if self._label_map.image_metadata:
  482. return read_metadata(read_chunk(self._fh, self._label_map.image_metadata), 1)
  483. @property
  484. def image_events(self):
  485. """Image events
  486. Returns:
  487. dict: Image events
  488. """
  489. if self._label_map.image_metadata:
  490. for event in self._metadata_parsed["events"]:
  491. yield event