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.

623 lines
20 KiB

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