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.

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