data_overview_1.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. # -*- coding: utf-8 -*-
  2. """
  3. Code for generating the first 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 numpy as np
  34. from scipy import stats
  35. import quantities as pq
  36. import matplotlib.pyplot as plt
  37. from matplotlib import gridspec, ticker
  38. from reachgraspio import reachgraspio
  39. import odml.tools
  40. from neo import utils as neo_utils
  41. import odml_utils
  42. # =============================================================================
  43. # Define data and metadata directories
  44. # =============================================================================
  45. def get_monkey_datafile(monkey):
  46. if monkey == "Lilou":
  47. return "l101210-001" # ns2 (behavior) and ns5 present
  48. elif monkey == "Nikos2":
  49. return "i140703-001" # ns2 and ns6 present
  50. else:
  51. return ""
  52. # Enter your dataset directory here
  53. datasetdir = "../datasets/"
  54. trialtype_colors = {
  55. 'SGHF': 'MediumBlue', 'SGLF': 'Turquoise',
  56. 'PGHF': 'DarkGreen', 'PGLF': 'YellowGreen',
  57. 'LFSG': 'Orange', 'LFPG': 'Yellow',
  58. 'HFSG': 'DarkRed', 'HFPG': 'OrangeRed',
  59. 'SGSG': 'SteelBlue', 'PGPG': 'LimeGreen',
  60. 'NONE': 'k', 'PG': 'k', 'SG': 'k', 'LF': 'k', 'HF': 'k'}
  61. event_colors = {
  62. 'TS-ON': 'Gray', # 'TS-OFF': 'Gray',
  63. 'WS-ON': 'Gray', # 'WS-OFF': 'Gray',
  64. 'CUE-ON': 'Gray',
  65. 'CUE-OFF': 'Gray',
  66. 'GO-ON': 'Gray', # 'GO-OFF': 'Gray',
  67. # 'GO/RW-OFF': 'Gray',
  68. 'SR': 'Gray', # 'SR-REP': 'Gray',
  69. 'RW-ON': 'Gray', # 'RW-OFF': 'Gray',
  70. 'STOP': 'Gray'}
  71. # =============================================================================
  72. # Plot helper functions
  73. # =============================================================================
  74. def force_aspect(ax, aspect=1):
  75. ax.set_aspect(abs(
  76. (ax.get_xlim()[1] - ax.get_xlim()[0]) /
  77. (ax.get_ylim()[1] - ax.get_ylim()[0])) / aspect)
  78. def get_arraygrid(blackrock_elid_list, chosen_el, rej_el=None):
  79. if rej_el is None:
  80. rej_el = []
  81. array_grid = np.zeros((10, 10))
  82. for m in range(10):
  83. for n in range(10):
  84. idx = (9 - m) * 10 + n
  85. bl_id = blackrock_elid_list[idx]
  86. if bl_id == -1:
  87. array_grid[m, n] = 0.7
  88. elif bl_id == chosen_el:
  89. array_grid[m, n] = -0.7
  90. elif bl_id in rej_el:
  91. array_grid[m, n] = -0.35
  92. else:
  93. array_grid[m, n] = 0
  94. return np.ma.array(array_grid, mask=np.isnan(array_grid))
  95. # =============================================================================
  96. # Load data and metadata for a monkey
  97. # =============================================================================
  98. # CHANGE this parameter to load data of the different monkeys
  99. # monkey = 'Nikos2'
  100. monkey = 'Lilou'
  101. nsx_none = {'Lilou': None, 'Nikos2': None}
  102. nsx_lfp = {'Lilou': 2, 'Nikos2': 2}
  103. nsx_raw = {'Lilou': 5, 'Nikos2': 6}
  104. chosen_el = {'Lilou': 71, 'Nikos2': 63}
  105. chosen_units = {'Lilou': range(1, 5), 'Nikos2': range(1, 5)}
  106. datafile = get_monkey_datafile(monkey)
  107. session = reachgraspio.ReachGraspIO(
  108. filename=os.path.join(datasetdir, datafile),
  109. odml_directory=datasetdir)
  110. bl = session.read_block(lazy=True, load_waveforms=False)
  111. seg = bl.segments[0]
  112. # Displaying loaded data structure as string output
  113. print("\nBlock")
  114. print('Attributes ', bl.__dict__.keys())
  115. print('Annotations', bl.annotations)
  116. print("\nSegment")
  117. print('Attributes ', seg.__dict__.keys())
  118. print('Annotations', seg.annotations)
  119. print("\nEvents")
  120. for x in seg.events:
  121. print('\tEvent with name', x.name)
  122. print('\t\tAttributes ', x.__dict__.keys())
  123. print('\t\tAnnotation keys', x.annotations.keys())
  124. print('\t\tArray annotation keys', x.array_annotations.keys())
  125. print('\t\ttimes', x.times[:20])
  126. for anno_key in ['trial_id', 'trial_timestamp_id', 'trial_event_labels',
  127. 'trial_reject_IFC']:
  128. if anno_key in x.array_annotations:
  129. print('\t\t'+anno_key, x.array_annotations[anno_key][:20])
  130. print("\nGroup")
  131. for x in bl.groups:
  132. print('\tGroup with name', x.name)
  133. print('\t\tAttributes ', x.__dict__.keys())
  134. print('\t\tAnnotations', x.annotations)
  135. print("\nSpikeTrains")
  136. for x in seg.spiketrains:
  137. print('\tSpiketrain with name', x.name)
  138. print('\t\tAttributes ', x.__dict__.keys())
  139. print('\t\tAnnotations', x.annotations)
  140. print('\t\tArray annotations', x.array_annotations)
  141. print('\t\tchannel_id', x.annotations['channel_id'])
  142. print('\t\tunit_id', x.annotations['unit_id'])
  143. print("\nAnalogSignals")
  144. for x in seg.analogsignals:
  145. print('\tAnalogSignal with name', x.name)
  146. print('\t\tAttributes ', x.__dict__.keys())
  147. print('\t\tAnnotations', x.annotations)
  148. print('\t\tArray annotations', x.array_annotations)
  149. print('\t\tchannel_id', x.array_annotations['channel_ids'])
  150. # get start and stop events of trials
  151. start_events = neo_utils.get_events(seg, properties={'name': 'TrialEvents'})[0]
  152. start_event_mask = np.logical_and(start_events.array_annotations['trial_event_labels'] == 'TS-ON',
  153. start_events.array_annotations['performance_in_trial'] == 255)
  154. start_events = start_events[start_event_mask]
  155. stop_events = neo_utils.get_events( seg, properties={'name': 'TrialEvents'})[0]
  156. stop_event_mask = np.logical_and(stop_events.array_annotations['trial_event_labels'] == 'STOP',
  157. stop_events.array_annotations['performance_in_trial' == 255])
  158. stop_events = stop_events[stop_event_mask]
  159. # insert epochs between 10ms before TS to 50ms after RW corresponding to trails
  160. neo_utils.add_epoch(
  161. seg,
  162. start_events[0],
  163. stop_events[0],
  164. pre=-250 * pq.ms,
  165. post=500 * pq.ms,
  166. trial_status='complete_trials',
  167. trial_type=start_events[0].annotations['belongs_to_trialtype'],
  168. trial_performance=start_events[0].annotations['performance_in_trial'])
  169. # access single epoch of this data_segment
  170. epochs = neo_utils.get_epochs(seg,
  171. properties={'trial_status': 'complete_trials'})
  172. assert len(epochs) == 1
  173. # cut segments according to inserted 'complete_trials' epochs and reset trial
  174. # times
  175. cut_segments = neo_utils.cut_segment_by_epoch(
  176. seg, epochs[0], reset_time=True)
  177. # =============================================================================
  178. # Define data for overview plots
  179. # =============================================================================
  180. trial_index = {'Lilou': 0, 'Nikos2': 6}
  181. trial_seg = cut_segments[trial_index[monkey]]
  182. blackrock_elid_list = bl.annotations['avail_electrode_ids']
  183. # get 'TrialEvents'
  184. event = trial_seg.events[2]
  185. start = event.annotations['trial_event_labels'].index('TS-ON')
  186. trialx_trty = event.annotations['belongs_to_trialtype'][start]
  187. trialx_trtimeid = event.annotations['trial_timestamp_id'][start]
  188. trialx_color = trialtype_colors[trialx_trty]
  189. # find trial index for next trial with opposite force type (for ax5b plot)
  190. if 'LF' in trialx_trty:
  191. trialz_trty = trialx_trty.replace('LF', 'HF')
  192. else:
  193. trialz_trty = trialx_trty.replace('HF', 'LF')
  194. for i, tr in enumerate(cut_segments):
  195. eventz = tr.events[2]
  196. nextft = eventz.annotations['trial_event_labels'].index('TS-ON')
  197. if eventz.annotations['belongs_to_trialtype'][nextft] == trialz_trty:
  198. trialz_trtimeid = eventz.annotations['trial_timestamp_id'][nextft]
  199. trialz_color = trialtype_colors[trialz_trty]
  200. trialz_seg = tr
  201. break
  202. # =============================================================================
  203. # Define figure and subplot axis for first data overview
  204. # =============================================================================
  205. fig = plt.figure()
  206. fig.set_size_inches(6.5, 10.) # (w, h) in inches
  207. gs = gridspec.GridSpec(
  208. nrows=5,
  209. ncols=4,
  210. left=0.05,
  211. bottom=0.07,
  212. right=0.9,
  213. top=0.975,
  214. wspace=0.3,
  215. hspace=0.5,
  216. width_ratios=None,
  217. height_ratios=[1, 3, 3, 6, 3])
  218. ax1 = plt.subplot(gs[0, :]) # top row / odml data
  219. # second row
  220. ax2a = plt.subplot(gs[1, 0]) # electrode overview plot
  221. ax2b = plt.subplot(gs[1, 1]) # waveforms unit 1
  222. ax2c = plt.subplot(gs[1, 2]) # waveforms unit 2
  223. ax2d = plt.subplot(gs[1, 3]) # waveforms unit 3
  224. ax3 = plt.subplot(gs[2, :]) # third row / spiketrains
  225. ax4 = plt.subplot(gs[3, :], sharex=ax3) # fourth row / raw signal
  226. ax5a = plt.subplot(gs[4, 0:3]) # fifth row / behavioral signals
  227. ax5b = plt.subplot(gs[4, 3])
  228. fontdict_titles = {'fontsize': 'small', 'fontweight': 'bold'}
  229. fontdict_axis = {'fontsize': 'x-small'}
  230. wf_time_unit = pq.ms
  231. wf_signal_unit = pq.microvolt
  232. plotting_time_unit = pq.s
  233. raw_signal_unit = wf_signal_unit
  234. behav_signal_unit = pq.V
  235. # =============================================================================
  236. # PLOT TRIAL SEQUENCE OF SUBSESSION
  237. # =============================================================================
  238. # load complete metadata collection
  239. odmldoc = odml.tools.xmlparser.load(datasetdir + datafile + '.odml')
  240. # get total trial number
  241. trno_tot = odml_utils.get_TrialCount(odmldoc)
  242. trno_ctr = odml_utils.get_TrialCount(odmldoc, performance_code=255)
  243. trno_ertr = trno_tot - trno_ctr
  244. # get trial id of chosen trial (and next trial with opposite force)
  245. trtimeids = odml_utils.get_TrialIDs(odmldoc, idtype='TrialTimestampID')
  246. trids = odml_utils.get_TrialIDs(odmldoc)
  247. trialx_trid = trids[trtimeids.index(trialx_trtimeid)]
  248. trialz_trid = trids[trtimeids.index(trialz_trtimeid)]
  249. # get all trial ids for grip error trials
  250. trids_pc191 = odml_utils.get_trialids_pc(odmldoc, 191)
  251. # get all trial ids for correct trials
  252. trids_pc255 = odml_utils.get_trialids_pc(odmldoc, 255)
  253. # get occurring trial types
  254. octrty = odml_utils.get_OccurringTrialTypes(odmldoc, code=False)
  255. # Subplot 1: Trial sequence
  256. boxes, labels = [], []
  257. for tt in octrty:
  258. # Plot trial ids of current trial type into trial sequence bar plot
  259. left = odml_utils.get_trialids_trty(odmldoc, tt)
  260. height = np.ones_like(left)
  261. width = 1.
  262. if tt in ['NONE', 'PG', 'SG', 'LF', 'HF']:
  263. color = 'w'
  264. else:
  265. color = trialtype_colors[tt]
  266. B = ax1.bar(
  267. x=left, height=height, width=width, color=color, linewidth=0.001, align='edge')
  268. # Mark trials of current trial type (left) if a grip error occurred
  269. x = [i for i in list(set(left) & set(trids_pc191))]
  270. y = np.ones_like(x) * 2.0
  271. ax1.scatter(x, y, s=5, color='k', marker='*')
  272. # Mark trials of current trial type (left) if any other error occurred
  273. x = [i for i in list(
  274. set(left) - set(trids_pc255) - set(trids_pc191))]
  275. y = np.ones_like(x) * 2.0
  276. ax1.scatter(x, y, s=5, color='gray', marker='*')
  277. # Collect information for trial type legend
  278. if tt not in ['PG', 'SG', 'LF', 'HF']:
  279. boxes.append(B[0])
  280. if tt == 'NONE':
  281. # use errors for providing total trial number
  282. labels.append('total: # %i' % trno_tot)
  283. # add another box and label for error numbers
  284. boxes.append(B[0])
  285. labels.append('* errors: # %i' % trno_ertr)
  286. else:
  287. # trial type trial numbers
  288. labels.append(tt + ': # %i' % len(left))
  289. # mark chosen trial
  290. x = [trialx_trid]
  291. y = np.ones_like(x) * 2.0
  292. ax1.scatter(x, y, s=5, marker='D', color='Red', edgecolors='Red')
  293. # mark next trial with opposite force
  294. x = [trialz_trid]
  295. y = np.ones_like(x) * 2.0
  296. ax1.scatter(x, y, s=5, marker='D', color='orange', edgecolors='orange')
  297. # Generate trial type legend; bbox: (left, bottom, width, height)
  298. leg = ax1.legend(
  299. boxes, labels, bbox_to_anchor=(0., 1., 0.5, 0.1), loc=3, handlelength=1.1,
  300. ncol=len(labels), borderaxespad=0., handletextpad=0.4,
  301. prop={'size': 'xx-small'})
  302. leg.draw_frame(False)
  303. # adjust x and y axis
  304. xticks = [i for i in range(1, 101, 10)] + [100]
  305. ax1.set_xticks(xticks)
  306. ax1.set_xticklabels([str(int(t)) for t in xticks], size='xx-small')
  307. ax1.set_xlabel('trial ID', size='x-small')
  308. ax1.set_xlim(1.-width/2., 100.+width/2.)
  309. ax1.yaxis.set_visible(False)
  310. ax1.set_ylim(0, 3)
  311. ax1.spines['top'].set_visible(False)
  312. ax1.spines['left'].set_visible(False)
  313. ax1.spines['right'].set_visible(False)
  314. ax1.tick_params(direction='out', top='off')
  315. ax1.set_title('sequence of the first 100 trials', fontdict_titles, y=2)
  316. ax1.set_aspect('equal')
  317. # =============================================================================
  318. # PLOT ELECTRODE POSITION of chosen electrode
  319. # =============================================================================
  320. arraygrid = get_arraygrid(blackrock_elid_list, chosen_el[monkey])
  321. cmap = plt.cm.RdGy
  322. ax2a.pcolormesh(
  323. np.flipud(arraygrid), vmin=-1, vmax=1, lw=1, cmap=cmap, edgecolors='k',
  324. shading='faceted')
  325. force_aspect(ax2a, aspect=1)
  326. ax2a.tick_params(
  327. bottom='off', top='off', left='off', right='off',
  328. labelbottom='off', labeltop='off', labelleft='off', labelright='off')
  329. ax2a.set_title('electrode pos.', fontdict_titles)
  330. # =============================================================================
  331. # PLOT WAVEFORMS of units of the chosen electrode
  332. # =============================================================================
  333. unit_ax_translator = {1: ax2b, 2: ax2c, 3: ax2d}
  334. unit_type = {1: '', 2: '', 3: ''}
  335. wf_lim = []
  336. # plotting waveform for all spiketrains available
  337. for spiketrain in trial_seg.spiketrains:
  338. unit_id = spiketrain.annotations['unit_id']
  339. # get unit type
  340. if spiketrain.annotations['sua']:
  341. unit_type[unit_id] = 'SUA'
  342. elif spiketrain.annotations['mua']:
  343. unit_type[unit_id] = 'MUA'
  344. else:
  345. pass
  346. # get correct ax
  347. ax = unit_ax_translator[unit_id]
  348. # get wf sampling time before threshold crossing
  349. left_sweep = spiketrain.left_sweep
  350. # plot waveforms in subplots according to unit id
  351. for st_id, st in enumerate(spiketrain):
  352. wf = spiketrain.waveforms[st_id]
  353. wf_lim.append((np.min(wf), np.max(wf)))
  354. wf_color = str(
  355. (st / spiketrain.t_stop).rescale('dimensionless').magnitude)
  356. times = range(len(wf[0])) * spiketrain.units - left_sweep
  357. ax.plot(
  358. times.rescale(wf_time_unit), wf[0].rescale(wf_signal_unit),
  359. color=wf_color)
  360. ax.set_xlim(
  361. times.rescale(wf_time_unit)[0], times.rescale(wf_time_unit)[-1])
  362. # adding xlabels and titles
  363. for unit_id, ax in unit_ax_translator.items():
  364. ax.set_title('unit %i (%s)' % (unit_id, unit_type[unit_id]),
  365. fontdict_titles)
  366. ax.tick_params(direction='in', length=3, labelsize='xx-small',
  367. labelleft='off', labelright='off')
  368. ax.set_xlabel(wf_time_unit.dimensionality.latex, fontdict_axis)
  369. xticklocator = ticker.MaxNLocator(nbins=5)
  370. ax.xaxis.set_major_locator(xticklocator)
  371. ax.set_ylim(np.min(wf_lim), np.max(wf_lim))
  372. force_aspect(ax, aspect=1)
  373. # adding ylabel
  374. ax2d.tick_params(labelsize='xx-small', labelright='on')
  375. ax2d.set_ylabel(wf_signal_unit.dimensionality.latex, fontdict_axis)
  376. ax2d.yaxis.set_label_position("right")
  377. # =============================================================================
  378. # PLOT SPIKETRAINS of units of chosen electrode
  379. # =============================================================================
  380. plotted_unit_ids = []
  381. # plotting all available spiketrains
  382. for st in trial_seg.spiketrains:
  383. unit_id = st.annotations['unit_id']
  384. plotted_unit_ids.append(unit_id)
  385. ax3.plot(st.times.rescale(plotting_time_unit),
  386. np.zeros(len(st.times)) + unit_id,
  387. 'k|')
  388. # setting layout of spiktrain plot
  389. ax3.set_ylim(min(plotted_unit_ids) - 0.5, max(plotted_unit_ids) + 0.5)
  390. ax3.set_ylabel(r'unit ID', fontdict_axis)
  391. ax3.yaxis.set_major_locator(ticker.MultipleLocator(base=1))
  392. ax3.yaxis.set_label_position("right")
  393. ax3.tick_params(axis='y', direction='in', length=3, labelsize='xx-small',
  394. labelleft='off', labelright='on')
  395. ax3.invert_yaxis()
  396. ax3.set_title('spiketrains', fontdict_titles)
  397. # =============================================================================
  398. # PLOT "raw" SIGNAL of chosen trial of chosen electrode
  399. # =============================================================================
  400. # get "raw" data from chosen electrode
  401. assert len(trial_seg.analogsignals) == 1
  402. el_sig = trial_seg.analogsignals[0]
  403. # plotting raw signal trace
  404. ax4.plot(el_sig.times.rescale(plotting_time_unit),
  405. el_sig.squeeze().rescale(raw_signal_unit),
  406. color='k')
  407. # setting layout of raw signal plot
  408. ax4.set_ylabel(raw_signal_unit.units.dimensionality.latex, fontdict_axis)
  409. ax4.yaxis.set_label_position("right")
  410. ax4.tick_params(axis='y', direction='in', length=3, labelsize='xx-small',
  411. labelleft='off', labelright='on')
  412. ax4.set_title('"raw" signal', fontdict_titles)
  413. ax4.set_xlim(trial_seg.t_start.rescale(plotting_time_unit),
  414. trial_seg.t_stop.rescale(plotting_time_unit))
  415. ax4.xaxis.set_major_locator(ticker.MultipleLocator(base=1))
  416. # =============================================================================
  417. # PLOT EVENTS across ax3 and ax4 and add time bar
  418. # =============================================================================
  419. # find trial relevant events
  420. startidx = event.annotations['trial_event_labels'].index('TS-ON')
  421. stopidx = event.annotations['trial_event_labels'][startidx:].index('STOP') + \
  422. startidx + 1
  423. for ax in [ax3, ax4]:
  424. xticks = []
  425. xticklabels = []
  426. for ev_id, ev in enumerate(event[startidx:stopidx]):
  427. ev_labels = event.annotations['trial_event_labels'][startidx:stopidx]
  428. if ev_labels[ev_id] in event_colors.keys():
  429. ev_color = event_colors[ev_labels[ev_id]]
  430. ax.axvline(
  431. ev.rescale(plotting_time_unit), color=ev_color, zorder=0.5)
  432. xticks.append(ev.rescale(plotting_time_unit))
  433. if ev_labels[ev_id] == 'CUE-OFF':
  434. xticklabels.append('-OFF')
  435. elif ev_labels[ev_id] == 'GO-ON':
  436. xticklabels.append('GO')
  437. else:
  438. xticklabels.append(ev_labels[ev_id])
  439. ax.set_xticks(xticks)
  440. ax.set_xticklabels(xticklabels)
  441. ax.tick_params(axis='x', direction='out', length=3, labelsize='xx-small',
  442. labeltop='off', top='off')
  443. timebar_ypos = ax4.get_ylim()[0] + np.diff(ax4.get_ylim())[0] / 10
  444. timebar_labeloffset = np.diff(ax4.get_ylim())[0] * 0.01
  445. timebar_xmin = xticks[-2] + ((xticks[-1] - xticks[-2]) / 2 - 0.25 * pq.s)
  446. timebar_xmax = timebar_xmin + 0.5 * pq.s
  447. ax4.plot([timebar_xmin, timebar_xmax], [timebar_ypos, timebar_ypos], '-',
  448. linewidth=3, color='k')
  449. ax4.text(timebar_xmin + 0.25 * pq.s, timebar_ypos + timebar_labeloffset,
  450. '500 ms', ha='center', va='bottom', size='xx-small', color='k')
  451. # =============================================================================
  452. # PLOT BEHAVIORAL SIGNALS of chosen trial
  453. # =============================================================================
  454. # get behavioral signals
  455. ainp_signals = [nsig for nsig in trial_seg.analogsignals if
  456. nsig.annotations['channel_id'] > 96]
  457. ainp_trialz = [nsig for nsig in trialz_seg.analogsignals if
  458. nsig.annotations['channel_id'] == 141][0]
  459. # find out what signal to use
  460. trialx_sec = odmldoc['Recording']['TaskSettings']['Trial_%03i' % trialx_trid]
  461. # get correct channel id
  462. trialx_chids = [143]
  463. FSRi = trialx_sec['AnalogEvents'].properties['UsedForceSensor'].values[0]
  464. FSRinfosec = odmldoc['Setup']['Apparatus']['TargetObject']['FSRSensor']
  465. if 'SG' in trialx_trty:
  466. sgchids = FSRinfosec.properties['SGChannelIDs'].values
  467. trialx_chids.append(min(sgchids) if FSRi == 1 else max(sgchids))
  468. else:
  469. pgchids = FSRinfosec.properties['PGChannelIDs'].values
  470. trialx_chids.append(min(pgchids) if FSRi == 1 else max(pgchids))
  471. # define time epoch
  472. startidx = event.annotations['trial_event_labels'].index('SR')
  473. stopidx = event.annotations['trial_event_labels'].index('OBB')
  474. sr = event[startidx].rescale(plotting_time_unit)
  475. stop = event[stopidx].rescale(plotting_time_unit) + 0.050 * pq.s
  476. startidx = event.annotations['trial_event_labels'].index('FSRplat-ON')
  477. stopidx = event.annotations['trial_event_labels'].index('FSRplat-OFF')
  478. fplon = event[startidx].rescale(plotting_time_unit)
  479. fploff = event[stopidx].rescale(plotting_time_unit)
  480. # define time epoch trialz
  481. startidx = eventz.annotations['trial_event_labels'].index('FSRplat-ON')
  482. stopidx = eventz.annotations['trial_event_labels'].index('FSRplat-OFF')
  483. fplon_trz = eventz[startidx].rescale(plotting_time_unit)
  484. fploff_trz = eventz[stopidx].rescale(plotting_time_unit)
  485. # plotting grip force and object displacement
  486. ai_legend = []
  487. ai_legend_txt = []
  488. for ainp in ainp_signals:
  489. if ainp.annotations['channel_id'] in trialx_chids:
  490. ainp_times = ainp.times.rescale(plotting_time_unit)
  491. mask = (ainp_times > sr) & (ainp_times < stop)
  492. ainp_ampli = stats.zscore(ainp.magnitude[mask])
  493. if ainp.annotations['channel_id'] != 143:
  494. color = 'gray'
  495. ai_legend_txt.append('grip force')
  496. else:
  497. color = 'k'
  498. ai_legend_txt.append('object disp.')
  499. ai_legend.append(
  500. ax5a.plot(ainp_times[mask], ainp_ampli, color=color)[0])
  501. # get force load of this trial for next plot
  502. elif ainp.annotations['channel_id'] == 141:
  503. ainp_times = ainp.times.rescale(plotting_time_unit)
  504. mask = (ainp_times > fplon) & (ainp_times < fploff)
  505. force_av_01 = np.mean(ainp.rescale(behav_signal_unit).magnitude[mask])
  506. # setting layout of grip force and object displacement plot
  507. ax5a.set_title('grip force and object displacement', fontdict_titles)
  508. ax5a.yaxis.set_label_position("left")
  509. ax5a.tick_params(direction='in', length=3, labelsize='xx-small',
  510. labelleft='off', labelright='on')
  511. ax5a.set_ylabel('zscore', fontdict_axis)
  512. ax5a.legend(
  513. ai_legend, ai_legend_txt,
  514. bbox_to_anchor=(0.65, .85, 0.25, 0.1), loc=2, handlelength=1.1,
  515. ncol=len(labels), borderaxespad=0., handletextpad=0.4,
  516. prop={'size': 'xx-small'})
  517. # plotting load/pull force of LF and HF trial
  518. force_times = ainp_trialz.times.rescale(plotting_time_unit)
  519. mask = (force_times > fplon_trz) & (force_times < fploff_trz)
  520. force_av_02 = np.mean(ainp_trialz.rescale(behav_signal_unit).magnitude[mask])
  521. bar_width = [0.4, 0.4]
  522. color = [trialx_color, trialz_color]
  523. ax5b.bar([0, 0.6], [force_av_01, force_av_02], bar_width, color=color)
  524. ax5b.set_title('load/pull force', fontdict_titles)
  525. ax5b.set_ylabel(behav_signal_unit.units.dimensionality.latex, fontdict_axis)
  526. ax5b.set_xticks([0, 0.6])
  527. ax5b.set_xticklabels([trialx_trty, trialz_trty], fontdict_axis)
  528. ax5b.yaxis.set_label_position("right")
  529. ax5b.tick_params(direction='in', length=3, labelsize='xx-small',
  530. labelleft='off', labelright='on')
  531. # =============================================================================
  532. # PLOT EVENTS across ax5a and add time bar
  533. # =============================================================================
  534. # find trial relevant events
  535. startidx = event.annotations['trial_event_labels'].index('SR')
  536. stopidx = event.annotations['trial_event_labels'].index('OBB')
  537. xticks = []
  538. xticklabels = []
  539. for ev_id, ev in enumerate(event[startidx:stopidx]):
  540. ev_labels = event.annotations['trial_event_labels'][startidx:stopidx + 1]
  541. if ev_labels[ev_id] in ['RW-ON']:
  542. ax5a.axvline(ev.rescale(plotting_time_unit), color='k', zorder=0.5)
  543. xticks.append(ev.rescale(plotting_time_unit))
  544. xticklabels.append(ev_labels[ev_id])
  545. elif ev_labels[ev_id] in ['OT', 'OR', 'DO', 'OBB', 'FSRplat-ON',
  546. 'FSRplat-OFF', 'HEplat-ON']:
  547. ev_color = 'k'
  548. xticks.append(ev.rescale(plotting_time_unit))
  549. xticklabels.append(ev_labels[ev_id])
  550. ax5a.axvline(
  551. ev.rescale(plotting_time_unit), color='k', ls='-.', zorder=0.5)
  552. elif ev_labels[ev_id] == 'HEplat-OFF':
  553. ev_color = 'k'
  554. ax5a.axvline(
  555. ev.rescale(plotting_time_unit), color='k', ls='-.', zorder=0.5)
  556. ax5a.set_xticks(xticks)
  557. ax5a.set_xticklabels(xticklabels, fontdict_axis, rotation=90)
  558. ax5a.tick_params(axis='x', direction='out', length=3, labelsize='xx-small',
  559. labeltop='off', top='off')
  560. ax5a.set_ylim([-2.0, 2.0])
  561. timebar_ypos = ax5a.get_ylim()[0] + np.diff(ax5a.get_ylim())[0] / 10
  562. timebar_labeloffset = np.diff(ax5a.get_ylim())[0] * 0.02
  563. timebar_xmax = xticks[xticklabels.index('RW-ON')] - 0.1 * pq.s
  564. timebar_xmin = timebar_xmax - 0.25 * pq.s
  565. ax5a.plot([timebar_xmin, timebar_xmax], [timebar_ypos, timebar_ypos], '-',
  566. linewidth=3, color='k')
  567. ax5a.text(timebar_xmin + 0.125 * pq.s, timebar_ypos + timebar_labeloffset,
  568. '250 ms', ha='center', va='bottom', size='xx-small', color='k')
  569. # add time window of ax5a to ax4
  570. ax4.axvspan(ax5a.get_xlim()[0], ax5a.get_xlim()[1], facecolor=[0.9, 0.9, 0.9],
  571. zorder=-0.1, ec=None)
  572. # =============================================================================
  573. # SAVE FIGURE
  574. # =============================================================================
  575. fname = 'data_overview_1_%s' % monkey
  576. for file_format in ['eps', 'png', 'pdf']:
  577. fig.savefig(fname + '.%s' % file_format, dpi=400, format=file_format)