Scheduled service maintenance on November 22


On Friday, November 22, 2024, between 06:00 CET and 18:00 CET, GIN services will undergo planned maintenance. Extended service interruptions should be expected. We will try to keep downtimes to a minimum, but recommend that users avoid critical tasks, large data uploads, or DOI requests during this time.

We apologize for any inconvenience.

example.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. # This loads the Neo and odML libraries shipped with this code. For production
  32. # use, please use the newest releases of odML and Neo.
  33. import load_local_neo_odml_elephant
  34. import os
  35. import numpy as np
  36. import matplotlib.pyplot as plt
  37. import quantities as pq
  38. from neo import Block, Segment
  39. from elephant.signal_processing import butter
  40. from reachgraspio import reachgraspio
  41. from neo_utils import add_epoch, cut_segment_by_epoch, get_events
  42. # =============================================================================
  43. # Load data
  44. #
  45. # As a first step, we partially load the data file into memory as a Neo object.
  46. # =============================================================================
  47. # Specify the path to the recording session to load, eg,
  48. # '/home/user/l101210-001'
  49. session_name = os.path.join('..', 'datasets', 'i140703-001')
  50. # session_name = os.path.join('..', 'datasets', 'l101210-001')
  51. odml_dir = os.path.join('..', 'datasets')
  52. # Open the session for reading
  53. session = reachgraspio.ReachGraspIO(session_name, odml_directory=odml_dir)
  54. # Read the first 300s of data (time series at 1000Hz (ns2) and 30kHz (ns6)
  55. # scaled to units of voltage, sorted spike trains, spike waveforms and events)
  56. # from electrode 62 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. data_block = session.read_block(
  61. nsx_to_load='all',
  62. n_starts=None, n_stops=300 * pq.s,
  63. channels=[62], units='all',
  64. load_events=True, load_waveforms=True, scaling='voltage',
  65. correct_filter_shifts=True)
  66. # Access the single Segment of the data block, reaching up to 300s.
  67. assert len(data_block.segments) == 1
  68. data_segment = data_block.segments[0]
  69. # =============================================================================
  70. # Create offline filtered LFP
  71. #
  72. # Here, we construct one offline filtered LFP from each ns5 (monkey L) or ns6
  73. # (monkey N) raw recording trace. For monkey N, this filtered LFP can be
  74. # compared to the LFPs in the ns2 file (note that monkey L contains only
  75. # behavioral signals in the ns2 file). Also, we assign telling names to each
  76. # Neo AnalogSignal, which is used for plotting later on in this script.
  77. # =============================================================================
  78. filtered_anasig = []
  79. # Loop through all AnalogSignal objects in the loaded data
  80. for anasig in data_block.segments[0].analogsignals:
  81. if anasig.annotations['nsx'] == 2:
  82. # AnalogSignal is LFP from ns2
  83. anasig.name = 'LFP (online filter, ns%i)' % anasig.annotations['nsx']
  84. elif anasig.annotations['nsx'] in [5, 6]:
  85. # AnalogSignal is raw signal from ns5 or ns6
  86. anasig.name = 'raw (ns%i)' % anasig.annotations['nsx']
  87. # Use the Elephant library to filter the analog signal
  88. f_anasig = butter(
  89. anasig,
  90. highpass_freq=None,
  91. lowpass_freq=250 * pq.Hz,
  92. order=4)
  93. f_anasig.name = 'LFP (offline filtered ns%i)' % \
  94. anasig.annotations['nsx']
  95. filtered_anasig.append(f_anasig)
  96. # Attach all offline filtered LFPs to the segment of data
  97. data_block.segments[0].analogsignals.extend(filtered_anasig)
  98. # =============================================================================
  99. # Construct analysis epochs
  100. #
  101. # In this step we extract and cut the data into time segments (termed analysis
  102. # epochs) that we wish to analyze. We contrast these analysis epochs to the
  103. # behavioral trials that are defined by the experiment as occurrence of a Trial
  104. # Start (TS-ON) event in the experiment. Concretely, here our analysis epochs
  105. # are constructed as a cutout of 25ms of data around the TS-ON event of all
  106. # successful behavioral trials.
  107. # =============================================================================
  108. # Get Trial Start (TS-ON) events of all successful behavioral trials
  109. # (corresponds to performance code 255, which is accessed for convenience and
  110. # better legibility in the dictionary attribute performance_codes of the
  111. # ReachGraspIO class).
  112. #
  113. # To this end, we filter all event objects of the loaded data to match the name
  114. # "TrialEvents", which is the Event object containing all Events available (see
  115. # documentation of ReachGraspIO). From this Event object we extract only events
  116. # matching "TS-ON" and the desired trial performance code (which are
  117. # annotations of the Event object).
  118. start_events = get_events(
  119. data_segment,
  120. properties={
  121. 'name': 'TrialEvents',
  122. 'trial_event_labels': 'TS-ON',
  123. 'performance_in_trial': session.performance_codes['correct_trial']})
  124. # Extract single Neo Event object containing all TS-ON triggers
  125. assert len(start_events) == 1
  126. start_event = start_events[0]
  127. # Construct analysis epochs from 10ms before the TS-ON of a successful
  128. # behavioral trial to 15ms after TS-ON. The name "analysis_epochs" is given to
  129. # the resulting Neo Epoch object. The object is not attached to the Neo
  130. # Segment. The parameter event2 of add_epoch() is left empty, since we are
  131. # cutting around a single event, as opposed to cutting between two events.
  132. pre = -10 * pq.ms
  133. post = 15 * pq.ms
  134. epoch = add_epoch(
  135. data_segment,
  136. event1=start_event, event2=None,
  137. pre=pre, post=post,
  138. attach_result=False,
  139. name='analysis_epochs')
  140. # Create new segments of data cut according to the analysis epochs of the
  141. # 'analysis_epochs' Neo Epoch object. The time axes of all segments are aligned
  142. # such that each segment starts at time 0 (parameter reset_times); annotations
  143. # describing the analysis epoch are carried over to the segments. A new Neo
  144. # Block named "data_cut_to_analysis_epochs" is created to capture all cut
  145. # analysis epochs.
  146. cut_trial_block = Block(name="data_cut_to_analysis_epochs")
  147. cut_trial_block.segments = cut_segment_by_epoch(
  148. data_segment, epoch, reset_time=True)
  149. # =============================================================================
  150. # Plot data
  151. # =============================================================================
  152. # Determine the first existing trial ID i from the Event object containing all
  153. # start events. Then, by calling the filter() function of the Neo Block
  154. # "data_cut_to_analysis_epochs" containing the data cut into the analysis
  155. # epochs, we ask to return all Segments annotated by the behavioral trial ID i.
  156. # In this case this call should return one matching analysis epoch around TS-ON
  157. # belonging to behavioral trial ID i. For monkey N, this is trial ID 1, for
  158. # monkey L this is trial ID 2 since trial ID 1 is not a correct trial.
  159. trial_id = int(np.min(start_event.annotations['trial_id']))
  160. trial_segments = cut_trial_block.filter(
  161. targdict={"trial_id": trial_id}, objects=Segment)
  162. assert len(trial_segments) == 1
  163. trial_segment = trial_segments[0]
  164. # Create figure
  165. fig = plt.figure(facecolor='w')
  166. time_unit = pq.CompoundUnit('1./30000*s')
  167. amplitude_unit = pq.microvolt
  168. nsx_colors = ['b', 'k', 'r']
  169. # Loop through all analog signals and plot the signal in a color corresponding
  170. # to its sampling frequency (i.e., originating from the ns2/ns5 or ns2/ns6).
  171. for i, anasig in enumerate(trial_segment.analogsignals):
  172. plt.plot(
  173. anasig.times.rescale(time_unit),
  174. anasig.squeeze().rescale(amplitude_unit),
  175. label=anasig.name,
  176. color=nsx_colors[i])
  177. # Loop through all spike trains and plot the spike time, and overlapping the
  178. # wave form of the spike used for spike sorting stored separately in the nev
  179. # file.
  180. for st in trial_segment.spiketrains:
  181. color = np.random.rand(3,)
  182. for spike_id, spike in enumerate(st):
  183. # Plot spike times
  184. plt.axvline(
  185. spike.rescale(time_unit).magnitude,
  186. color=color,
  187. label='Unit ID %i' % st.annotations['unit_id'])
  188. # Plot waveforms
  189. waveform = st.waveforms[spike_id, 0, :]
  190. waveform_times = np.arange(len(waveform))*time_unit + spike
  191. plt.plot(
  192. waveform_times.rescale(time_unit).magnitude,
  193. waveform.rescale(amplitude_unit),
  194. '--',
  195. linewidth=2,
  196. color=color,
  197. zorder=0)
  198. # Loop through all events
  199. for event in trial_segment.events:
  200. if event.name == 'TrialEvents':
  201. for ev_id, ev in enumerate(event):
  202. plt.axvline(
  203. ev,
  204. alpha=0.2,
  205. linewidth=3,
  206. linestyle='dashed',
  207. label='event ' + event.annotations[
  208. 'trial_event_labels'][ev_id])
  209. # Finishing touches on the plot
  210. plt.autoscale(enable=True, axis='x', tight=True)
  211. plt.xlabel(time_unit.name)
  212. plt.ylabel(amplitude_unit.name)
  213. plt.legend(loc=4, fontsize=10)
  214. # Save plot
  215. fname = 'example_plot'
  216. for file_format in ['eps', 'png', 'pdf']:
  217. fig.savefig(fname + '.%s' % file_format, dpi=400, format=file_format)