1
1

example.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # -*- coding: utf-8 -*-
  2. """
  3. Example code for loading and processing of a recording of the reach-
  4. to-grasp experiments conducted at the Institute de Neurosciences de la Timone
  5. by Thomas Brochier and Alexa Riehle.
  6. Authors: Julia Sprenger, Lyuba Zehl, Michael Denker
  7. Copyright (c) 2017, Institute of Neuroscience and Medicine (INM-6),
  8. Forschungszentrum Juelich, Germany
  9. All rights reserved.
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions are met:
  12. * Redistributions of source code must retain the above copyright notice, this
  13. list of conditions and the following disclaimer.
  14. * Redistributions in binary form must reproduce the above copyright notice,
  15. this list of conditions and the following disclaimer in the documentation
  16. and/or other materials provided with the distribution.
  17. * Neither the names of the copyright holders nor the names of the contributors
  18. may be used to endorse or promote products derived from this software without
  19. specific prior written permission.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  21. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  24. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  25. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  26. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  27. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  28. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """
  31. import os
  32. import numpy as np
  33. import matplotlib.pyplot as plt
  34. import quantities as pq
  35. from neo import Block, Segment
  36. from elephant.signal_processing import butter
  37. from reachgraspio import reachgraspio
  38. from neo.utils import cut_segment_by_epoch, add_epoch, get_events
  39. from neo_utils import load_segment
  40. # =============================================================================
  41. # Load data
  42. #
  43. # As a first step, we partially load the data file into memory as a Neo object.
  44. # =============================================================================
  45. # Specify the path to the recording session to load, eg,
  46. # '/home/user/l101210-001'
  47. session_name = os.path.join('..', 'datasets', 'i140703-001')
  48. # session_name = os.path.join('..', 'datasets', 'l101210-001')
  49. odml_dir = os.path.join('..', 'datasets')
  50. # Open the session for reading
  51. session = reachgraspio.ReachGraspIO(session_name, odml_directory=odml_dir)
  52. # Read a the complete dataset in lazy mode generating all neo objects,
  53. # but not loading data into memory. The lazy neo structure will contain objects
  54. # to capture all recorded data types (time series at 1000Hz (ns2) and 30kHz (ns6)
  55. # scaled to units of voltage, sorted spike trains, spike waveforms and events)
  56. # of the recording session and return it as a Neo Block. The
  57. # time shift of the ns2 signal (LFP) induced by the online filter is
  58. # automatically corrected for by a heuristic factor stored in the metadata
  59. # (correct_filter_shifts=True).
  60. block = session.read_block(lazy=True, correct_filter_shifts=True)
  61. # Validate there is only a single Segment present in the block
  62. assert len(block.segments) == 1
  63. # loading data content of all data objects during the first 300 seconds
  64. data_segment = load_segment(block.segments[0], time_range=(None, 300*pq.s))
  65. # =============================================================================
  66. # Create offline filtered LFP
  67. #
  68. # Here, we construct one offline filtered LFP from each ns5 (monkey L) or ns6
  69. # (monkey N) raw recording trace. For monkey N, this filtered LFP can be
  70. # compared to the LFPs in the ns2 file (note that monkey L contains only
  71. # behavioral signals in the ns2 file). Also, we assign telling names to each
  72. # Neo AnalogSignal, which is used for plotting later on in this script.
  73. # =============================================================================
  74. target_channel_id = 62
  75. nsx_to_anasig_name = {2: 'LFP signal (online filtered)',
  76. 5: 'raw signal',
  77. 6: 'raw signal'}
  78. filtered_anasig = None
  79. raw_anasig = None
  80. # identify neuronal signals and provide labels for plotting
  81. for anasig in data_segment.analogsignals:
  82. # skip non-neuronal signals
  83. if not anasig.annotations['neural_signal']:
  84. continue
  85. # identify nsx source of signals in this AnalogSignal object
  86. nsx = np.unique(anasig.array_annotations['nsx'])
  87. assert len(nsx) == 1, 'Different nsx sources in AnalogSignal'
  88. nsx = nsx[0]
  89. if nsx == 2:
  90. # AnalogSignal is LFP from ns2
  91. anasig.name = f'LFP (online filter, ns2)'
  92. filtered_anasig = anasig
  93. elif nsx in [5, 6]:
  94. # AnalogSignal is raw signal from ns5 or ns6
  95. anasig.name = f'raw (ns{nsx})'
  96. raw_anasig = anasig
  97. # Create LFP signal by filtering raw signal if not present already
  98. if filtered_anasig is None:
  99. # Use the Elephant library to filter the signal, filter only target channel
  100. target_channel_index = np.where(target_channel_id == raw_anasig.array_annotations['channel_ids'])[0]
  101. raw_signal = raw_anasig[:, target_channel_index]
  102. f_anasig = butter(
  103. raw_signal,
  104. highpass_freq=None,
  105. lowpass_freq=250 * pq.Hz,
  106. order=4)
  107. f_anasig.name = f'LFP (offline filtered ns{anasig.array_annotations["nsx"][0]})'
  108. # Attach all offline filtered LFPs to the segment of data
  109. data_segment.analogsignals.append(f_anasig)
  110. # =============================================================================
  111. # Construct analysis epochs
  112. #
  113. # In this step we extract and cut the data into time segments (termed analysis
  114. # epochs) that we wish to analyze. We contrast these analysis epochs to the
  115. # behavioral trials that are defined by the experiment as occurrence of a Trial
  116. # Start (TS-ON) event in the experiment. Concretely, here our analysis epochs
  117. # are constructed as a cutout of 25ms of data around the TS-ON event of all
  118. # successful behavioral trials.
  119. # =============================================================================
  120. # Get Trial Start (TS-ON) events of all successful behavioral trials
  121. # (corresponds to performance code 255, which is accessed for convenience and
  122. # better legibility in the dictionary attribute performance_codes of the
  123. # ReachGraspIO class).
  124. #
  125. # To this end, we filter all event objects of the loaded data to match the name
  126. # "TrialEvents", which is the Event object containing all Events available (see
  127. # documentation of ReachGraspIO). From this Event object we extract only events
  128. # matching "TS-ON" and the desired trial performance code (which are
  129. # annotations of the Event object).
  130. start_events = get_events(
  131. data_segment,
  132. name='TrialEvents',
  133. trial_event_labels='TS-ON',
  134. performance_in_trial=session.performance_codes['correct_trial'])
  135. print('got start events.')
  136. # Extract single Neo Event object containing all TS-ON triggers
  137. assert len(start_events) == 1
  138. start_event = start_events[0]
  139. # Construct analysis epochs from 10ms before the TS-ON of a successful
  140. # behavioral trial to 15ms after TS-ON. The name "analysis_epochs" is given to
  141. # the resulting Neo Epoch object. The object is not attached to the Neo
  142. # Segment. The parameter event2 of add_epoch() is left empty, since we are
  143. # cutting around a single event, as opposed to cutting between two events.
  144. pre = -10 * pq.ms
  145. post = 15 * pq.ms
  146. epoch = add_epoch(
  147. data_segment,
  148. event1=start_event, event2=None,
  149. pre=pre, post=post,
  150. attach_result=False,
  151. name='analysis_epochs',
  152. array_annotations=start_event.array_annotations)
  153. print('added epoch.')
  154. # Create new segments of data cut according to the analysis epochs of the
  155. # 'analysis_epochs' Neo Epoch object. The time axes of all segments are aligned
  156. # such that each segment starts at time 0 (parameter reset_times); annotations
  157. # describing the analysis epoch are carried over to the segments. A new Neo
  158. # Block named "data_cut_to_analysis_epochs" is created to capture all cut
  159. # analysis epochs. For execution time reason, we are only considering the
  160. # first 10 epochs here.
  161. cut_trial_block = Block(name="data_cut_to_analysis_epochs")
  162. cut_trial_block.segments = cut_segment_by_epoch(
  163. data_segment, epoch[:10], reset_time=True)
  164. # =============================================================================
  165. # Plot data
  166. # =============================================================================
  167. # Determine the first existing trial ID i from the Event object containing all
  168. # start events. Then, by calling the filter() function of the Neo Block
  169. # "data_cut_to_analysis_epochs" containing the data cut into the analysis
  170. # epochs, we ask to return all Segments annotated by the behavioral trial ID i.
  171. # In this case this call should return one matching analysis epoch around TS-ON
  172. # belonging to behavioral trial ID i. For monkey N, this is trial ID 1, for
  173. # monkey L this is trial ID 2 since trial ID 1 is not a correct trial.
  174. trial_id = int(np.min(start_event.array_annotations['trial_id']))
  175. trial_segments = cut_trial_block.filter(
  176. targdict={"trial_id": trial_id}, objects=Segment)
  177. assert len(trial_segments) == 1
  178. trial_segment = trial_segments[0]
  179. # Create figure
  180. fig = plt.figure(facecolor='w')
  181. time_unit = pq.CompoundUnit('1./30000*s')
  182. amplitude_unit = pq.microvolt
  183. nsx_colors = {2: 'k', 5: 'r', 6: 'b'}
  184. # Loop through all AnalogSignal objects and plot the signal of the target channel
  185. # in a color corresponding to its sampling frequency (i.e., originating from the ns2/ns5 or ns2/ns6).
  186. for i, anasig in enumerate(trial_segment.analogsignals):
  187. # only visualize neural data
  188. if anasig.annotations['neural_signal']:
  189. nsx = anasig.array_annotations['nsx'][0]
  190. target_channel_index = np.where(anasig.array_annotations['channel_ids'] == target_channel_id)[0]
  191. target_signal = anasig[:, target_channel_index]
  192. plt.plot(
  193. target_signal.times.rescale(time_unit),
  194. target_signal.squeeze().rescale(amplitude_unit),
  195. label=target_signal.name,
  196. color=nsx_colors[nsx])
  197. # Loop through all spike trains and plot the spike time, and overlapping the
  198. # wave form of the spike used for spike sorting stored separately in the nev
  199. # file.
  200. for st in trial_segment.spiketrains:
  201. color = np.random.rand(3,)
  202. if st.annotations['channel_id'] == target_channel_id:
  203. for spike_id, spike in enumerate(st):
  204. # Plot spike times
  205. plt.axvline(
  206. spike.rescale(time_unit).magnitude,
  207. color=color,
  208. label='Unit ID %i' % st.annotations['unit_id'])
  209. # Plot waveforms
  210. waveform = st.waveforms[spike_id, 0, :]
  211. waveform_times = np.arange(len(waveform))*time_unit + spike
  212. plt.plot(
  213. waveform_times.rescale(time_unit).magnitude,
  214. waveform.rescale(amplitude_unit),
  215. '--',
  216. linewidth=2,
  217. color=color,
  218. zorder=0)
  219. # Loop through all events
  220. for event in trial_segment.events:
  221. if event.name == 'TrialEvents':
  222. for ev_id, ev in enumerate(event):
  223. plt.axvline(
  224. ev.rescale(time_unit),
  225. alpha=0.2,
  226. linewidth=3,
  227. linestyle='dashed',
  228. label=f'event {event.array_annotations["trial_event_labels"][ev_id]}')
  229. # Finishing touches on the plot
  230. plt.autoscale(enable=True, axis='x', tight=True)
  231. plt.xlabel(time_unit.name)
  232. plt.ylabel(amplitude_unit.name)
  233. plt.legend(loc=4, fontsize=10)
  234. # Save plot
  235. fname = 'example_plot'
  236. for file_format in ['eps', 'png', 'pdf']:
  237. fig.savefig(fname + '.%s' % file_format, dpi=400, format=file_format)