data_overview_2.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. # -*- coding: utf-8 -*-
  2. """
  3. Code for generating the second data figure in the manuscript.
  4. Authors: Julia Sprenger, Lyuba Zehl, Michael Denker
  5. Copyright (c) 2017, Institute of Neuroscience and Medicine (INM-6),
  6. Forschungszentrum Juelich, Germany
  7. All rights reserved.
  8. Redistribution and use in source and binary forms, with or without
  9. modification, are permitted provided that the following conditions are met:
  10. * Redistributions of source code must retain the above copyright notice, this
  11. list of conditions and the following disclaimer.
  12. * Redistributions in binary form must reproduce the above copyright notice,
  13. this list of conditions and the following disclaimer in the documentation
  14. and/or other materials provided with the distribution.
  15. * Neither the names of the copyright holders nor the names of the contributors
  16. may be used to endorse or promote products derived from this software without
  17. specific prior written permission.
  18. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  22. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  24. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  26. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """
  29. # This loads the Neo and odML libraries shipped with this code. For production
  30. # use, please use the newest releases of odML and Neo.
  31. import load_local_neo_odml_elephant
  32. import os
  33. import matplotlib.pyplot as plt
  34. from matplotlib import gridspec, transforms
  35. import quantities as pq
  36. import numpy as np
  37. from neo import (AnalogSignal, SpikeTrain)
  38. from reachgraspio import reachgraspio
  39. import neo_utils
  40. # =============================================================================
  41. # Define data and metadata directories and general settings
  42. # =============================================================================
  43. def get_monkey_datafile(monkey):
  44. if monkey == "Lilou":
  45. return "l101210-001" # ns2 (behavior) and ns5 present
  46. elif monkey == "Nikos2":
  47. return "i140703-001" # ns2 and ns6 present
  48. else:
  49. return ""
  50. # Enter your dataset directory here
  51. datasetdir = os.path.join('..', 'datasets')
  52. nsx_none = {'Lilou': None, 'Nikos2': None}
  53. nsx_lfp = {'Lilou': 5, 'Nikos2': 2}
  54. chosen_els = {'Lilou': range(3, 97, 7), 'Nikos2': range(1, 97, 7)}
  55. chosen_el = {
  56. 'Lilou': chosen_els['Lilou'][0],
  57. 'Nikos2': chosen_els['Nikos2'][0]}
  58. trial_indexes = range(14)
  59. trial_index = trial_indexes[0]
  60. chosen_events = ['TS-ON', 'WS-ON', 'CUE-ON', 'CUE-OFF', 'GO-ON', 'SR-ON',
  61. 'RW-ON', 'WS-OFF'] # , 'RW-OFF'
  62. # =============================================================================
  63. # Load data and metadata for a monkey
  64. # =============================================================================
  65. # CHANGE this parameter to load data of the different monkeys
  66. # monkey = 'Nikos2'
  67. monkey = 'Lilou'
  68. datafile = get_monkey_datafile(monkey)
  69. session = reachgraspio.ReachGraspIO(
  70. filename=os.path.join(datasetdir, datafile),
  71. odml_directory=datasetdir,
  72. verbose=False)
  73. bl = session.read_block(
  74. index=None,
  75. name=None,
  76. description=None,
  77. nsx_to_load=nsx_lfp[monkey],
  78. n_starts=None,
  79. n_stops=None,
  80. channels=chosen_els[monkey],
  81. units=[1], # loading only unit_id 1
  82. load_waveforms=False,
  83. load_events=True,
  84. scaling='voltage',
  85. lazy=False,
  86. cascade=True)
  87. seg = bl.segments[0]
  88. # get start and stop events of trials
  89. start_events = neo_utils.get_events(
  90. seg, properties={
  91. 'name': 'TrialEvents',
  92. 'trial_event_labels': 'TS-ON',
  93. 'performance_in_trial': session.performance_codes['correct_trial']})
  94. stop_events = neo_utils.get_events(
  95. seg, properties={
  96. 'name': 'TrialEvents',
  97. 'trial_event_labels': 'RW-ON',
  98. 'performance_in_trial': session.performance_codes['correct_trial']})
  99. # there should only be one event object for these conditions
  100. assert len(start_events) == 1
  101. assert len(stop_events) == 1
  102. # insert epochs between 10ms before TS to 50ms after RW corresponding to trails
  103. neo_utils.add_epoch(
  104. seg,
  105. start_events[0],
  106. stop_events[0],
  107. pre=-250 * pq.ms,
  108. post=500 * pq.ms,
  109. segment_type='complete_trials',
  110. trialtype=start_events[0].annotations[
  111. 'belongs_to_trialtype'])
  112. # access single epoch of this data_segment
  113. epochs = neo_utils.get_epochs(seg,
  114. properties={'segment_type': 'complete_trials'})
  115. assert len(epochs) == 1
  116. # cut segments according to inserted 'complete_trials' epochs and reset trial
  117. # times
  118. cut_segments = neo_utils.cut_segment_by_epoch(seg,
  119. epochs[0],
  120. reset_time=True)
  121. # explicitely adding trial type annotations to cut segments
  122. for i, cut_seg in enumerate(cut_segments):
  123. cut_seg.annotate(trialtype=epochs[0].annotations['trialtype'][i])
  124. # =============================================================================
  125. # Define figure and subplot axis for first data overview
  126. # =============================================================================
  127. fig = plt.figure(facecolor='w')
  128. fig.set_size_inches(7.0, 9.9) # (w, h) in inches
  129. # #(7.0, 9.9) corresponds to A4 portrait ratio
  130. gs = gridspec.GridSpec(
  131. nrows=2,
  132. ncols=2,
  133. left=0.1,
  134. bottom=0.05,
  135. right=0.9,
  136. top=0.975,
  137. wspace=0.1,
  138. hspace=0.1,
  139. width_ratios=None,
  140. height_ratios=[2, 1])
  141. ax1 = plt.subplot(gs[0, 0]) # top left
  142. ax2 = plt.subplot(gs[0, 1], sharex=ax1) # top right
  143. ax3 = plt.subplot(gs[1, 0], sharex=ax1) # bottom left
  144. ax4 = plt.subplot(gs[1, 1], sharex=ax1) # bottom right
  145. fontdict_titles = {'fontsize': 9, 'fontweight': 'bold'}
  146. fontdict_axis = {'fontsize': 10, 'fontweight': 'bold'}
  147. # the x coords of the event labels are data, and the y coord are axes
  148. event_label_transform = transforms.blended_transform_factory(ax1.transData,
  149. ax1.transAxes)
  150. trialtype_colors = {
  151. 'SGHF': 'MediumBlue', 'SGLF': 'Turquoise',
  152. 'PGHF': 'DarkGreen', 'PGLF': 'YellowGreen',
  153. 'LFSG': 'Orange', 'LFPG': 'Yellow',
  154. 'HFSG': 'DarkRed', 'HFPG': 'OrangeRed',
  155. 'SGSG': 'SteelBlue', 'PGPG': 'LimeGreen',
  156. None: 'black'}
  157. event_colors = {
  158. 'TS-ON': 'indigo', 'TS-OFF': 'indigo',
  159. 'WS-ON': 'purple', 'WS-OFF': 'purple',
  160. 'CUE-ON': 'crimson', 'CUE-OFF': 'crimson',
  161. 'GO-ON': 'orangered', 'GO-OFF': 'orangered',
  162. 'SR-ON': 'darkorange',
  163. 'RW-ON': 'orange', 'RW-OFF': 'orange'}
  164. electrode_cmap = plt.get_cmap('bone')
  165. electrode_colors = [electrode_cmap(x) for x in
  166. np.tile(np.array([0.3, 0.7]), len(chosen_els[monkey]) / 2)]
  167. time_unit = 'ms'
  168. lfp_unit = 'uV'
  169. # define scaling factors for analogsignals
  170. anasig_std = np.mean([np.std(anasig.rescale(lfp_unit)) for anasig in
  171. cut_segments[trial_index].analogsignals]) \
  172. * getattr(pq, lfp_unit)
  173. anasig_offset = 3 * anasig_std
  174. # =============================================================================
  175. # SUPPLEMENTORY PLOTTING functions
  176. # =============================================================================
  177. def add_scalebar(ax, std):
  178. # the x coords of the scale bar are axis, and the y coord are data
  179. scalebar_transform = transforms.blended_transform_factory(ax.transAxes,
  180. ax.transData)
  181. # adding scalebar
  182. yscalebar = max(int(std.rescale(lfp_unit)), 1) * getattr(pq, lfp_unit) * 2
  183. scalebar_offset = -2 * std
  184. ax.vlines(x=0.4,
  185. ymin=(scalebar_offset - yscalebar).magnitude,
  186. ymax=scalebar_offset.magnitude,
  187. color='k',
  188. linewidth=4,
  189. transform=scalebar_transform)
  190. ax.text(0.4, (scalebar_offset - 0.5 * yscalebar).magnitude,
  191. ' %i %s' % (yscalebar.magnitude, lfp_unit),
  192. ha="left", va="center", rotation=0, color='k',
  193. size=8, transform=scalebar_transform)
  194. # =============================================================================
  195. # PLOT DATA OF SINGLE TRIAL (left plots)
  196. # =============================================================================
  197. # get data of selected trial
  198. selected_trial = cut_segments[trial_index]
  199. # PLOT DATA FOR EACH CHOSEN ELECTRODE
  200. for el_idx, electrode_id in enumerate(chosen_els[monkey]):
  201. # PLOT ANALOGSIGNALS in upper plot
  202. anasigs = selected_trial.filter(
  203. channel_id=electrode_id, objects=AnalogSignal)
  204. for anasig in anasigs:
  205. ax1.plot(anasig.times.rescale(time_unit),
  206. np.asarray(anasig.rescale(lfp_unit))
  207. + anasig_offset.magnitude * el_idx,
  208. color=electrode_colors[el_idx])
  209. # PLOT SPIKETRAINS in lower plot
  210. spiketrains = selected_trial.filter(
  211. channel_id=electrode_id, objects=SpikeTrain)
  212. for spiketrain in spiketrains:
  213. ax3.plot(spiketrain.times.rescale(time_unit),
  214. np.zeros(len(spiketrain.times)) + el_idx, 'k|')
  215. # PLOT EVENTS in both plots
  216. for event_type in chosen_events:
  217. # get events of each chosen event type
  218. event_data = neo_utils.get_events(selected_trial,
  219. {'trial_event_labels': event_type})
  220. for event in event_data:
  221. event_color = event_colors[event.annotations['trial_event_labels'][0]]
  222. # adding lines
  223. for ax in [ax1, ax3]:
  224. ax.axvline(event.times.rescale(time_unit),
  225. color=event_color,
  226. zorder=0.5)
  227. # adding labels
  228. ax1.text(event.times.rescale(time_unit), 0,
  229. event.annotations['trial_event_labels'][0],
  230. ha="center", va="top", rotation=45, color=event_color,
  231. size=8, transform=event_label_transform)
  232. # SUBPLOT ADJUSTMENTS
  233. ax1.set_title('single trial', fontdict=fontdict_titles)
  234. ax1.set_ylabel('electrode id', fontdict=fontdict_axis)
  235. ax1.set_yticks(np.arange(len(chosen_els[monkey])) * anasig_offset)
  236. ax1.set_yticklabels(chosen_els[monkey])
  237. ax1.autoscale(enable=True, axis='y')
  238. plt.setp(ax1.get_xticklabels(), visible=False) # show no xticklabels
  239. ax3.set_ylabel('electrode id', fontdict=fontdict_axis)
  240. ax3.set_yticks(range(0, len(chosen_els[monkey])))
  241. ax3.set_yticklabels(np.asarray(chosen_els[monkey]))
  242. ax3.set_ylim(-1, len(chosen_els[monkey]))
  243. ax3.set_xlabel('time [%s]' % time_unit, fontdict=fontdict_axis)
  244. # ax3.autoscale(axis='y')
  245. # =============================================================================
  246. # PLOT DATA OF SINGLE ELECTRODE
  247. # =============================================================================
  248. # plot data for each chosen trial
  249. for trial_idx, trial_id in enumerate(trial_indexes):
  250. trial_data = cut_segments[trial_id].filter(channel_id=chosen_el[monkey])
  251. trial_type = trial_data[0].parents[0].annotations['trialtype']
  252. trial_color = trialtype_colors[trial_type]
  253. for t_data in trial_data:
  254. # PLOT ANALOGSIGNALS in upper plot
  255. if isinstance(t_data, AnalogSignal):
  256. ax2.plot(t_data.times.rescale(time_unit),
  257. np.asarray(t_data.rescale(lfp_unit))
  258. + anasig_offset.magnitude * trial_idx,
  259. color=trial_color, zorder=1)
  260. # PLOT SPIKETRAINS in lower plot
  261. elif isinstance(t_data, SpikeTrain):
  262. ax4.plot(t_data.times.rescale(time_unit),
  263. np.ones(len(t_data.times)) + trial_idx, 'k|')
  264. # PLOT EVENTS in both plots
  265. for event_type in chosen_events:
  266. # get events of each chosen event type
  267. event_data = neo_utils.get_events(cut_segments[trial_id],
  268. {'trial_event_labels': event_type})
  269. for event in event_data:
  270. color = event_colors[event.annotations['trial_event_labels'][0]]
  271. ax2.vlines(x=event.times.rescale(time_unit),
  272. ymin=(trial_idx - 0.5) * anasig_offset,
  273. ymax=(trial_idx + 0.5) * anasig_offset,
  274. color=color,
  275. zorder=2)
  276. ax4.vlines(x=event.times.rescale(time_unit),
  277. ymin=trial_idx + 1 - 0.4,
  278. ymax=trial_idx + 1 + 0.4,
  279. color=color,
  280. zorder=0.5)
  281. # SUBPLOT ADJUSTMENTS
  282. ax2.set_title('single electrode', fontdict=fontdict_titles)
  283. ax2.set_ylabel('trial id', fontdict=fontdict_axis)
  284. ax2.set_yticks(np.asarray(trial_indexes) * anasig_offset)
  285. ax2.set_yticklabels(
  286. [epochs[0].annotations['trial_id'][_] for _ in trial_indexes])
  287. ax2.yaxis.set_label_position("right")
  288. ax2.tick_params(direction='in', length=3, labelleft='off', labelright='on')
  289. ax2.autoscale(enable=True, axis='y')
  290. add_scalebar(ax2, anasig_std)
  291. plt.setp(ax2.get_xticklabels(), visible=False) # show no xticklabels
  292. ax4.set_ylabel('trial id', fontdict=fontdict_axis)
  293. ax4.set_xlabel('time [%s]' % time_unit, fontdict=fontdict_axis)
  294. start, end = ax4.get_xlim()
  295. ax4.xaxis.set_ticks(np.arange(start, end, 1000))
  296. ax4.xaxis.set_ticks(np.arange(start, end, 500), minor=True)
  297. ax4.set_yticks(range(1, len(trial_indexes) + 1))
  298. ax4.set_yticklabels(np.asarray(
  299. [epochs[0].annotations['trial_id'][_] for _ in trial_indexes]))
  300. ax4.yaxis.set_label_position("right")
  301. ax4.tick_params(direction='in', length=3, labelleft='off', labelright='on')
  302. ax4.autoscale(enable=True, axis='y')
  303. # GENERAL PLOT ADJUSTMENTS
  304. # adjust font sizes of ticks
  305. for ax in [ax4.yaxis, ax4.xaxis, ax3.xaxis, ax3.yaxis]:
  306. for tick in ax.get_major_ticks():
  307. tick.label.set_fontsize(10)
  308. # adjust time range on x axis
  309. t_min = np.min([cut_segments[tid].t_start.rescale(time_unit)
  310. for tid in trial_indexes])
  311. t_max = np.max([cut_segments[tid].t_stop.rescale(time_unit)
  312. for tid in trial_indexes])
  313. ax1.set_xlim(t_min, t_max)
  314. add_scalebar(ax1, anasig_std)
  315. # =============================================================================
  316. # SAVE FIGURE
  317. # =============================================================================
  318. fname = 'data_overview_2_%s' % monkey
  319. for file_format in ['eps', 'pdf', 'png']:
  320. fig.savefig(fname + '.%s' % file_format, dpi=400, format=file_format)