example_nix.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 from the NIX files.
  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 neo.io import NixIO
  37. from neo.utils import cut_segment_by_epoch, add_epoch, get_events
  38. # =============================================================================
  39. # Load data
  40. #
  41. # As a first step, we load the data file into memory as a Neo object.
  42. # =============================================================================
  43. # Specify the path to the recording session to load, eg,
  44. # '/home/user/l101210-001'
  45. session_name = "i140703-001"
  46. # session_name = "l101210-001"
  47. session_path = os.path.join("..", "datasets_nix", session_name + ".nix")
  48. # Open the session for reading
  49. session = NixIO(session_path)
  50. # Channel ID to plot
  51. target_channel_id = 62
  52. # Read 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()
  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. data_segment = block.segments[0]
  66. print("Session loaded.")
  67. # =============================================================================
  68. # Construct analysis epochs
  69. #
  70. # In this step we extract and cut the data into time segments (termed analysis
  71. # epochs) that we wish to analyze. We contrast these analysis epochs to the
  72. # behavioral trials that are defined by the experiment as occurrence of a Trial
  73. # Start (TS-ON) event in the experiment. Concretely, here our analysis epochs
  74. # are constructed as a cutout of 25ms of data around the TS-ON event of all
  75. # successful behavioral trials.
  76. # =============================================================================
  77. # Get Trial Start (TS-ON) events of all successful behavioral trials
  78. # (corresponds to performance code 255, which is accessed for convenience and
  79. # better legibility in the dictionary attribute performance_codes of the
  80. # ReachGraspIO class).
  81. #
  82. # To this end, we filter all event objects of the loaded data to match the name
  83. # "TrialEvents", which is the Event object containing all Events available (see
  84. # documentation of ReachGraspIO). From this Event object we extract only events
  85. # matching "TS-ON" and the desired trial performance code (which are
  86. # annotations of the Event object).
  87. start_events = get_events(
  88. data_segment,
  89. name='TrialEvents',
  90. trial_event_labels='TS-ON',
  91. performance_in_trial_str='correct_trial')
  92. print('Determined start events.')
  93. # Extract single Neo Event object containing all TS-ON triggers
  94. assert len(start_events) == 1
  95. start_event = start_events[0]
  96. # Construct analysis epochs from 10ms before the TS-ON of a successful
  97. # behavioral trial to 15ms after TS-ON. The name "analysis_epochs" is given to
  98. # the resulting Neo Epoch object. The object is not attached to the Neo
  99. # Segment. The parameter event2 of add_epoch() is left empty, since we are
  100. # cutting around a single event, as opposed to cutting between two events.
  101. pre = -10 * pq.ms
  102. post = 15 * pq.ms
  103. epoch = add_epoch(
  104. data_segment,
  105. event1=start_event, event2=None,
  106. pre=pre, post=post,
  107. attach_result=False,
  108. name='analysis_epochs',
  109. array_annotations=start_event.array_annotations)
  110. print('Added epoch.')
  111. # Create new segments of data cut according to the analysis epochs of the
  112. # 'analysis_epochs' Neo Epoch object. The time axes of all segments are aligned
  113. # such that each segment starts at time 0 (parameter reset_times); annotations
  114. # describing the analysis epoch are carried over to the segments. A new Neo
  115. # Block named "data_cut_to_analysis_epochs" is created to capture all cut
  116. # analysis epochs. For execution time reason, we are only considering the
  117. # first 10 epochs here.
  118. cut_trial_block = Block(name="data_cut_to_analysis_epochs")
  119. cut_trial_block.segments = cut_segment_by_epoch(
  120. data_segment, epoch[:10], reset_time=True)
  121. print("Cut data.")
  122. # =============================================================================
  123. # Plot data
  124. # =============================================================================
  125. # Determine the first existing trial ID i from the Event object containing all
  126. # start events. Then, by calling the filter() function of the Neo Block
  127. # "data_cut_to_analysis_epochs" containing the data cut into the analysis
  128. # epochs, we ask to return all Segments annotated by the behavioral trial ID i.
  129. # In this case this call should return one matching analysis epoch around TS-ON
  130. # belonging to behavioral trial ID i. For monkey N, this is trial ID 1, for
  131. # monkey L this is trial ID 2 since trial ID 1 is not a correct trial.
  132. trial_id = int(np.min(start_event.array_annotations['trial_id']))
  133. trial_segments = cut_trial_block.filter(
  134. targdict={"trial_id": trial_id}, objects=Segment)
  135. assert len(trial_segments) == 1
  136. trial_segment = trial_segments[0]
  137. # Create figure
  138. fig = plt.figure(facecolor='w')
  139. time_unit = pq.CompoundUnit('1./30000*s')
  140. amplitude_unit = pq.microvolt
  141. nsx_colors = {2: 'k', 5: 'r', 6: 'b'}
  142. # Loop through all AnalogSignal objects and plot the signal of the target channel
  143. # in a color corresponding to its sampling frequency (i.e., originating from the ns2/ns5 or ns2/ns6).
  144. for i, anasig in enumerate(trial_segment.analogsignals):
  145. # only visualize neural data
  146. if anasig.annotations['neural_signal']:
  147. if 'nsx' in anasig.annotations:
  148. nsx = anasig.annotations['nsx']
  149. else:
  150. nsx = anasig.array_annotations['nsx'][0]
  151. channel_ids = np.asarray(anasig.array_annotations['channel_ids'], dtype=int)
  152. target_channel_index = np.where(channel_ids == target_channel_id)[0]
  153. target_signal = anasig[:, target_channel_index]
  154. plt.plot(
  155. target_signal.times.rescale(time_unit),
  156. target_signal.squeeze().rescale(amplitude_unit),
  157. label=target_signal.name,
  158. color=nsx_colors[nsx if nsx>0 else 2]) # offline LFP: nsx==-1
  159. # Loop through all spike trains and plot the spike time, and overlapping the
  160. # wave form of the spike used for spike sorting stored separately in the nev
  161. # file.
  162. for st in trial_segment.spiketrains:
  163. color = np.random.rand(3,)
  164. if st.annotations['channel_id'] == target_channel_id:
  165. for spike_id, spike in enumerate(st):
  166. # Plot spike times
  167. plt.axvline(
  168. spike.rescale(time_unit).magnitude,
  169. color=color,
  170. label='Unit ID %i' % st.annotations['unit_id'])
  171. # Plot waveforms
  172. waveform = st.waveforms[spike_id, 0, :]
  173. waveform_times = np.arange(len(waveform))*time_unit + spike
  174. plt.plot(
  175. waveform_times.rescale(time_unit).magnitude,
  176. waveform.rescale(amplitude_unit),
  177. '--',
  178. linewidth=2,
  179. color=color,
  180. zorder=0)
  181. # Loop through all events
  182. for event in trial_segment.events:
  183. if event.name == 'TrialEvents':
  184. for ev_id, ev in enumerate(event):
  185. plt.axvline(
  186. ev.rescale(time_unit),
  187. alpha=0.2,
  188. linewidth=3,
  189. linestyle='dashed',
  190. label=f'event {event.array_annotations["trial_event_labels"][ev_id]}')
  191. # Finishing touches on the plot
  192. plt.autoscale(enable=True, axis='x', tight=True)
  193. plt.xlabel(time_unit.name)
  194. plt.ylabel(amplitude_unit.name)
  195. plt.legend(loc=4, fontsize=10)
  196. # Save plot
  197. file_name = 'example_plot_from_nix_%s' % session_name
  198. for file_format in ['eps', 'png', 'pdf']:
  199. fig.savefig(file_name + '.%s' % file_format, dpi=400, format=file_format)