basefromrawio_orig.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. """
  2. BaseFromRaw
  3. ======
  4. BaseFromRaw implement a bridge between the new neo.rawio API
  5. and the neo.io legacy that give neo.core object.
  6. The neo.rawio API is more restricted and limited and do not cover tricky
  7. cases with asymetrical tree of neo object.
  8. But if a format is done in neo.rawio the neo.io is done for free
  9. by inheritance of this class.
  10. Furthermore, IOs that inherits this BaseFromRaw also have the ability
  11. of the lazy load with proxy objects.
  12. """
  13. import collections
  14. import warnings
  15. import numpy as np
  16. from neo import logging_handler
  17. from neo.core import (AnalogSignal, Block,
  18. Epoch, Event,
  19. IrregularlySampledSignal,
  20. ChannelIndex,
  21. Segment, SpikeTrain, Unit)
  22. from neo.io.baseio import BaseIO
  23. from neo.io.proxyobjects import (AnalogSignalProxy,
  24. SpikeTrainProxy, EventProxy, EpochProxy,
  25. ensure_signal_units, check_annotations,
  26. ensure_second, proxyobjectlist)
  27. import quantities as pq
  28. class BaseFromRaw(BaseIO):
  29. """
  30. This implement generic reader on top of RawIO reader.
  31. Arguments depend on `mode` (dir or file)
  32. File case::
  33. reader = BlackRockIO(filename='FileSpec2.3001.nev')
  34. Dir case::
  35. reader = NeuralynxIO(dirname='Cheetah_v5.7.4/original_data')
  36. Other arguments are IO specific.
  37. """
  38. is_readable = True
  39. is_writable = False
  40. supported_objects = [Block, Segment, AnalogSignal,
  41. SpikeTrain, Unit, ChannelIndex, Event, Epoch]
  42. readable_objects = [Block, Segment]
  43. writeable_objects = []
  44. support_lazy = True
  45. name = 'BaseIO'
  46. description = ''
  47. extentions = []
  48. mode = 'file'
  49. _prefered_signal_group_mode = 'group-by-same-units' # 'split-all'
  50. _prefered_units_group_mode = 'all-in-one' # 'split-all'
  51. _default_group_mode_have_change_in_0_9 = False
  52. def __init__(self, *args, **kargs):
  53. BaseIO.__init__(self, *args, **kargs)
  54. self.parse_header()
  55. def read_block(self, block_index=0, lazy=False, signal_group_mode=None,
  56. units_group_mode=None, load_waveforms=False):
  57. """
  58. :param block_index: int default 0. In case of several block block_index can be specified.
  59. :param lazy: False by default.
  60. :param signal_group_mode: 'split-all' or 'group-by-same-units' (default depend IO):
  61. This control behavior for grouping channels in AnalogSignal.
  62. * 'split-all': each channel will give an AnalogSignal
  63. * 'group-by-same-units' all channel sharing the same quantity units ar grouped in
  64. a 2D AnalogSignal
  65. :param units_group_mode: 'split-all' or 'all-in-one'(default depend IO)
  66. This control behavior for grouping Unit in ChannelIndex:
  67. * 'split-all': each neo.Unit is assigned to a new neo.ChannelIndex
  68. * 'all-in-one': all neo.Unit are grouped in the same neo.ChannelIndex
  69. (global spike sorting for instance)
  70. :param load_waveforms: False by default. Control SpikeTrains.waveforms is None or not.
  71. """
  72. if signal_group_mode is None:
  73. signal_group_mode = self._prefered_signal_group_mode
  74. if self._default_group_mode_have_change_in_0_9:
  75. warnings.warn('default "signal_group_mode" have change in version 0.9:'
  76. 'now all channels are group together in AnalogSignal')
  77. if units_group_mode is None:
  78. units_group_mode = self._prefered_units_group_mode
  79. # annotations
  80. bl_annotations = dict(self.raw_annotations['blocks'][block_index])
  81. bl_annotations.pop('segments')
  82. bl_annotations = check_annotations(bl_annotations)
  83. bl = Block(**bl_annotations)
  84. # ChannelIndex are plit in 2 parts:
  85. # * some for AnalogSignals
  86. # * some for Units
  87. # ChannelIndex for AnalogSignals
  88. all_channels = self.header['signal_channels']
  89. channel_indexes_list = self.get_group_channel_indexes()
  90. for channel_index in channel_indexes_list:
  91. for i, (ind_within, ind_abs) in self._make_signal_channel_subgroups(
  92. channel_index, signal_group_mode=signal_group_mode).items():
  93. if signal_group_mode == "split-all":
  94. chidx_annotations = self.raw_annotations['signal_channels'][i]
  95. elif signal_group_mode == "group-by-same-units":
  96. # this should be done with array_annotation soon:
  97. keys = list(self.raw_annotations['signal_channels'][ind_abs[0]].keys())
  98. # take key from first channel of the group
  99. chidx_annotations = {key: [] for key in keys}
  100. for j in ind_abs:
  101. for key in keys:
  102. v = self.raw_annotations['signal_channels'][j].get(key, None)
  103. chidx_annotations[key].append(v)
  104. if 'name' in list(chidx_annotations.keys()):
  105. chidx_annotations.pop('name')
  106. chidx_annotations = check_annotations(chidx_annotations)
  107. # this should be done with array_annotation soon:
  108. ch_names = all_channels[ind_abs]['name'].astype('U')
  109. neo_channel_index = ChannelIndex(index=ind_within,
  110. channel_names=ch_names,
  111. channel_ids=all_channels[ind_abs]['id'],
  112. name='Channel group {}'.format(i),
  113. )
  114. neo_channel_index.annotations.update(chidx_annotations)
  115. bl.channel_indexes.append(neo_channel_index)
  116. # ChannelIndex and Unit
  117. # 2 case are possible in neo defifferent IO have choosen one or other:
  118. # * All units are grouped in the same ChannelIndex and indexes are all channels:
  119. # 'all-in-one'
  120. # * Each units is assigned to one ChannelIndex: 'split-all'
  121. # This is kept for compatibility
  122. unit_channels = self.header['unit_channels']
  123. if units_group_mode == 'all-in-one':
  124. if unit_channels.size > 0:
  125. channel_index = ChannelIndex(index=np.array([], dtype='i'),
  126. name='ChannelIndex for all Unit')
  127. bl.channel_indexes.append(channel_index)
  128. for c in range(unit_channels.size):
  129. unit_annotations = self.raw_annotations['unit_channels'][c]
  130. unit_annotations = check_annotations(unit_annotations)
  131. unit = Unit(**unit_annotations)
  132. channel_index.units.append(unit)
  133. elif units_group_mode == 'split-all':
  134. for c in range(len(unit_channels)):
  135. unit_annotations = self.raw_annotations['unit_channels'][c]
  136. unit_annotations = check_annotations(unit_annotations)
  137. unit = Unit(**unit_annotations)
  138. channel_index = ChannelIndex(index=np.array([], dtype='i'),
  139. name='ChannelIndex for Unit')
  140. channel_index.units.append(unit)
  141. bl.channel_indexes.append(channel_index)
  142. # Read all segments
  143. for seg_index in range(self.segment_count(block_index)):
  144. seg = self.read_segment(block_index=block_index, seg_index=seg_index,
  145. lazy=lazy, signal_group_mode=signal_group_mode,
  146. load_waveforms=load_waveforms)
  147. bl.segments.append(seg)
  148. # create link to other containers ChannelIndex and Units
  149. for seg in bl.segments:
  150. for c, anasig in enumerate(seg.analogsignals):
  151. bl.channel_indexes[c].analogsignals.append(anasig)
  152. nsig = len(seg.analogsignals)
  153. for c, sptr in enumerate(seg.spiketrains):
  154. if units_group_mode == 'all-in-one':
  155. bl.channel_indexes[nsig].units[c].spiketrains.append(sptr)
  156. elif units_group_mode == 'split-all':
  157. bl.channel_indexes[nsig + c].units[0].spiketrains.append(sptr)
  158. bl.create_many_to_one_relationship()
  159. return bl
  160. def read_segment(self, block_index=0, seg_index=0, lazy=False,
  161. signal_group_mode=None, load_waveforms=False, time_slice=None,
  162. strict_slicing=True):
  163. """
  164. :param block_index: int default 0. In case of several blocks block_index can be specified.
  165. :param seg_index: int default 0. Index of segment.
  166. :param lazy: False by default.
  167. :param signal_group_mode: 'split-all' or 'group-by-same-units' (default depend IO):
  168. This control behavior for grouping channels in AnalogSignal.
  169. * 'split-all': each channel will give an AnalogSignal
  170. * 'group-by-same-units' all channel sharing the same quantity units ar grouped in
  171. a 2D AnalogSignal
  172. :param load_waveforms: False by default. Control SpikeTrains.waveforms is None or not.
  173. :param time_slice: None by default means no limit.
  174. A time slice is (t_start, t_stop) both are quantities.
  175. All object AnalogSignal, SpikeTrain, Event, Epoch will load only in the slice.
  176. :param strict_slicing: True by default.
  177. Control if an error is raised or not when t_start or t_stop
  178. is outside the real time range of the segment.
  179. """
  180. if lazy:
  181. assert time_slice is None,\
  182. 'For lazy=True you must specify time_slice when LazyObject.load(time_slice=...)'
  183. assert not load_waveforms,\
  184. 'For lazy=True you must specify load_waveforms when SpikeTrain.load(load_waveforms=...)'
  185. if signal_group_mode is None:
  186. signal_group_mode = self._prefered_signal_group_mode
  187. # annotations
  188. seg_annotations = dict(self.raw_annotations['blocks'][block_index]['segments'][seg_index])
  189. for k in ('signals', 'units', 'events'):
  190. seg_annotations.pop(k)
  191. seg_annotations = check_annotations(seg_annotations)
  192. seg = Segment(index=seg_index, **seg_annotations)
  193. # AnalogSignal
  194. signal_channels = self.header['signal_channels']
  195. if signal_channels.size > 0:
  196. channel_indexes_list = self.get_group_channel_indexes()
  197. for channel_indexes in channel_indexes_list:
  198. for i, (ind_within, ind_abs) in self._make_signal_channel_subgroups(
  199. channel_indexes,
  200. signal_group_mode=signal_group_mode).items():
  201. # make a proxy...
  202. anasig = AnalogSignalProxy(rawio=self, global_channel_indexes=ind_abs,
  203. block_index=block_index, seg_index=seg_index)
  204. if not lazy:
  205. # ... and get the real AnalogSIgnal if not lazy
  206. anasig = anasig.load(time_slice=time_slice, strict_slicing=strict_slicing)
  207. # TODO magnitude_mode='rescaled'/'raw'
  208. anasig.segment = seg
  209. seg.analogsignals.append(anasig)
  210. # SpikeTrain and waveforms (optional)
  211. unit_channels = self.header['unit_channels']
  212. for unit_index in range(len(unit_channels)):
  213. # make a proxy...
  214. sptr = SpikeTrainProxy(rawio=self, unit_index=unit_index,
  215. block_index=block_index, seg_index=seg_index)
  216. if not lazy:
  217. # ... and get the real SpikeTrain if not lazy
  218. sptr = sptr.load(time_slice=time_slice, strict_slicing=strict_slicing,
  219. load_waveforms=load_waveforms)
  220. # TODO magnitude_mode='rescaled'/'raw'
  221. sptr.segment = seg
  222. seg.spiketrains.append(sptr)
  223. # Events/Epoch
  224. event_channels = self.header['event_channels']
  225. for chan_ind in range(len(event_channels)):
  226. if event_channels['type'][chan_ind] == b'event':
  227. e = EventProxy(rawio=self, event_channel_index=chan_ind,
  228. block_index=block_index, seg_index=seg_index)
  229. if not lazy:
  230. e = e.load(time_slice=time_slice, strict_slicing=strict_slicing)
  231. e.segment = seg
  232. seg.events.append(e)
  233. elif event_channels['type'][chan_ind] == b'epoch':
  234. e = EpochProxy(rawio=self, event_channel_index=chan_ind,
  235. block_index=block_index, seg_index=seg_index)
  236. if not lazy:
  237. e = e.load(time_slice=time_slice, strict_slicing=strict_slicing)
  238. e.segment = seg
  239. seg.epochs.append(e)
  240. seg.create_many_to_one_relationship()
  241. return seg
  242. def _make_signal_channel_subgroups(self, channel_indexes,
  243. signal_group_mode='group-by-same-units'):
  244. """
  245. For some RawIO channel are already splitted in groups.
  246. But in any cases, channel need to be splitted again in sub groups
  247. because they do not have the same units.
  248. They can also be splitted one by one to match previous behavior for
  249. some IOs in older version of neo (<=0.5).
  250. This method aggregate signal channels with same units or split them all.
  251. """
  252. all_channels = self.header['signal_channels']
  253. if channel_indexes is None:
  254. channel_indexes = np.arange(all_channels.size, dtype=int)
  255. channels = all_channels[channel_indexes]
  256. groups = collections.OrderedDict()
  257. if signal_group_mode == 'group-by-same-units':
  258. all_units = np.unique(channels['units'])
  259. for i, unit in enumerate(all_units):
  260. ind_within, = np.nonzero(channels['units'] == unit)
  261. ind_abs = channel_indexes[ind_within]
  262. groups[i] = (ind_within, ind_abs)
  263. elif signal_group_mode == 'split-all':
  264. for i, chan_index in enumerate(channel_indexes):
  265. ind_within = [i]
  266. ind_abs = channel_indexes[ind_within]
  267. groups[i] = (ind_within, ind_abs)
  268. else:
  269. raise (NotImplementedError)
  270. return groups