reachgraspio.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  1. # coding=utf-8
  2. '''
  3. Reach-to-grasp IO module
  4. This module provides an IO to load data recorded in the context of the reach-
  5. to-grasp experiments conducted by Thomas Brochier and Alexa Riehle at the
  6. Institute de Neurosciences de la Timone. The IO is based on the BlackrockIO of
  7. the Neo library, which is used in the background to load the primary data, and
  8. utilized the odML library to load metadata information. Specifically, this IO
  9. annotates the Neo object returned by BlackrockIO with semantic information,
  10. e.g., interpretation of digital event codes, and key-value pairs found in the
  11. corresponding odML file are attached to relevant Neo objects as annotations.
  12. Authors: Julia Sprenger, Lyuba Zehl, Michael Denker
  13. Copyright (c) 2017, Institute of Neuroscience and Medicine (INM-6),
  14. Forschungszentrum Juelich, Germany
  15. All rights reserved.
  16. Redistribution and use in source and binary forms, with or without
  17. modification, are permitted provided that the following conditions are met:
  18. * Redistributions of source code must retain the above copyright notice, this
  19. list of conditions and the following disclaimer.
  20. * Redistributions in binary form must reproduce the above copyright notice,
  21. this list of conditions and the following disclaimer in the documentation
  22. and/or other materials provided with the distribution.
  23. * Neither the names of the copyright holders nor the names of the contributors
  24. may be used to endorse or promote products derived from this software without
  25. specific prior written permission.
  26. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  27. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  28. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  29. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  30. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  31. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  32. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  33. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  34. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  35. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. '''
  37. import glob
  38. import os
  39. import re
  40. import numpy as np
  41. import odml.tools
  42. import quantities as pq
  43. import neo
  44. # Using old version of IO as long as available - should be deleted at some point
  45. try:
  46. from neo.io import OldBlackrockIO as BlackrockIO
  47. except ImportError:
  48. from neo.io.blackrockio import BlackrockIO
  49. class ReachGraspIO(BlackrockIO):
  50. """
  51. Derived class from Neo's BlackrockIO to load recordings obtained from the
  52. reach-to-grasp experiments.
  53. Args:
  54. filename (string):
  55. File name (without extension) of the set of Blackrock files to
  56. associate with. Any .nsX or .nev, .sif, or .ccf extensions are
  57. ignored when parsing this parameter. Note: unless the parameter
  58. nev_override is given, this IO will load the nev file containing
  59. the most recent spike sorted data of all nev files found in the
  60. same directory as filename. The spike sorting version is attached
  61. to filename by a postfix '-XX', where XX is the version, e.g.,
  62. l101010-001-02 for spike sorting version 2 of file l101010-001. If
  63. an odML file is specified, the version must be listed in the odML
  64. entries at
  65. "/PreProcessing/OfflineSpikeSorting/Sortings"
  66. and relates to the section
  67. "/PreProcessing/OfflineSpikeSorting/Sorting-XX".
  68. If no odML is present, no information on the spike sorting (e.g.,
  69. if a unit is SUA or MUA) is provided by this IO.
  70. odml_directory (string):
  71. Alternative directory where the odML file is stored. If None, the
  72. directory is assumed to be the same as the .nev and .nsX data
  73. files. Default: None.
  74. nsx_override (string):
  75. File name of the .nsX files (without extension). If None,
  76. filename is used.
  77. Default: None.
  78. nev_override (string):
  79. File name of the .nev file (without extension). If None, the
  80. current spike-sorted version filename is used (see parameter
  81. filename above). Default: None.
  82. sif_override (string):
  83. File name of the .sif file (without extension). If None,
  84. filename is used.
  85. Default: None.
  86. ccf_override (string):
  87. File name of the .ccf file (without extension). If None,
  88. filename is used.
  89. Default: None.
  90. odml_override (string):
  91. File name of the .odml file (without extension). If None,
  92. filename is used.
  93. Default: None.
  94. verbose (boolean):
  95. If True, the class will output additional diagnostic
  96. information on stdout.
  97. Default: False
  98. Returns:
  99. -
  100. Attributes:
  101. condition_str (dict):
  102. Dictionary containing a list of string codes reflecting the trial
  103. types that occur in recordings in a certain condition code
  104. (dictionary keys). For example, for condition 1 (all grip first
  105. conditions), condition_str[1] contains the list
  106. ['SGHF', 'SGLF', 'PGHF', 'PGLF'].
  107. Possible conditions:
  108. 0:[]
  109. No trials, or condition not conclusive from file
  110. 4 types (two_cues_task):
  111. 1: all grip-first trial types with two different cues
  112. 2: all force-first trial types with two different cues
  113. 2 types (two_cues_task):
  114. 11: grip-first, but only LF types
  115. 12: grip-first, but only HF types
  116. 13: grip-first, but only SG types
  117. 14: grip-first, but only PG types
  118. 2 types (two_cues_task):
  119. 21: force-first, but only LF types
  120. 22: force-first, but only HF types
  121. 23: force-first, but only SG types
  122. 24: force-first, but only PG types
  123. 1 type (two_cues_task):
  124. 131: grip-first, but only SGLF type
  125. 132: grip-first, but only SGHF type
  126. 141: grip-first, but only PGLF type
  127. 142: grip-first, but only PGHF type
  128. 213: force-first, but only LFSG type
  129. 214: force-first, but only LFPG type
  130. 223: force-first, but only HFSG type
  131. 224: force-first, but only HFPG type
  132. 1 type (one_cue_task):
  133. 133: SGSG, only grip info, force unknown
  134. 144: PGPG, only grip info, force unknown
  135. 211: LFLF, only force info, grip unknown
  136. 222: HFHF, only force info, grip unknown
  137. event_labels_str (dict):
  138. Provides a text label for each digital event code returned as
  139. events by the parent BlackrockIO. For example,
  140. event_labels_str['65296'] contains the string 'TS-ON'.
  141. event_labels_codes (dict):
  142. Reverse of `event_labels_str`: Provides a list of event codes
  143. related to a specific text label for a trial event. For example,
  144. event_labels_codes['TS-ON'] contains the list ['65296']. In
  145. addition to the detailed codes, for convenience the meta codes
  146. 'CUE/GO', 'RW-ON', and 'SR' summarizing a set of digital events are
  147. defined for easier access.
  148. trial_const_sequence_str (dict):
  149. Dictionary contains the ordering of selected constant trial events
  150. for correct trials, e.g., as TS is the first trial event in a
  151. correct trial, trial_const_sequence_codes['TS'] is 0.
  152. trial_const_sequence_codes (dict):
  153. Reverse of trial_const_sequence_str: Dictionary contains the
  154. ordering of selected constant trial events for correct trials,
  155. e.g., trial_const_sequence_codes[0] is 'TS'.
  156. performance_str (dict):
  157. Text strings to help interpret the performance code of a trial. For
  158. example, correct trials have a performance code of 255, and thus
  159. performance_str[255] == 'correct_trial'
  160. performance_codes (dict):
  161. Reverse of performance_const_sequence_str. Returns the performance
  162. code of a given text string indicating trial performance. For
  163. example, performance_str['correct_trial'] == 255
  164. """
  165. # Create a dictionary of conditions (i.e., the trial types presented in a
  166. # given recording session)
  167. condition_str = {
  168. 0: [],
  169. 1: ['SGHF', 'SGLF', 'PGHF', 'PGLF'],
  170. 2: ['HFSG', 'HFPG', 'LFSG', 'LFPG'],
  171. 11: ['SGLF', 'PGLF'],
  172. 12: ['SGHF', 'PGHF'],
  173. 13: ['SGHF', 'SGLF'],
  174. 14: ['PGHF', 'PGLF'],
  175. 21: ['LFSG', 'LFPG'],
  176. 22: ['HFSG', 'HFPG'],
  177. 23: ['HFSG', 'LFSG'],
  178. 24: ['HFPG', 'LFPG'],
  179. 131: ['SGLF'],
  180. 132: ['SGHF'],
  181. 133: ['SGSG'],
  182. 141: ['PGLF'],
  183. 142: ['PGHF'],
  184. 144: ['PGPG'],
  185. 211: ['LFLF'],
  186. 213: ['LFSG'],
  187. 214: ['LFPG'],
  188. 222: ['HFHF'],
  189. 223: ['HFSG'],
  190. 224: ['HFPG']}
  191. ###########################################################################
  192. # event labels, the corresponding first 8 digits of their binary
  193. # representation and their meaning
  194. #
  195. # R L T T L L L L
  196. # w E a r E E E E
  197. # P D S S D D D D in
  198. # u c w t b t t b mo-
  199. # l r l r nk-
  200. # label:| ^ ^ ^ ^ ^ ^ ^ ^ | status of devices: | trial event label:| ey
  201. # 65280 < 0 0 0 0 0 0 0 0 > TS-OFF > TS-OFF/STOP > L,T
  202. # 65296 < 0 0 0 1 0 0 0 0 > TS-ON > TS-ON > all
  203. # 65312 < 0 0 1 0 0 0 0 0 > TaSw > STOP > all
  204. # 65344 < 0 1 0 0 0 0 0 0 > LEDc (+TS-OFF) > WS-ON/CUE-OFF > L,T
  205. # 65349 < 0 1 0 0 0 1 0 1 > LEDc|rt|rb (+TS-OFF) > PG-ON (CUE/GO-ON) > L,T
  206. # 65350 < 0 1 0 0 0 1 1 0 > LEDc|tl|tr (+TS-OFF) > HF-ON (CUE/GO-ON) > L,T
  207. # 65353 < 0 1 0 0 1 0 0 1 > LEDc|bl|br (+TS-OFF) > LF-ON (CUE/GO-ON) > L,T
  208. # 65354 < 0 1 0 0 1 0 1 0 > LEDc|lb|lt (+TS-OFF) > SG-ON (CUE/GO-ON) > L,T
  209. # 65359 < 0 1 0 0 1 1 1 1 > LEDall > ERROR-FLASH-ON > L,T
  210. # 65360 < 0 1 0 1 0 0 0 0 > LEDc (+TS-ON) > WS-ON/CUE-OFF > N
  211. # 65365 < 0 1 0 1 0 1 0 1 > LEDc|rt|rb (+TS-ON) > PG-ON (CUE/GO-ON) > N
  212. # 65366 < 0 1 0 1 0 1 1 0 > LEDc|tl|tr (+TS-ON) > HF-ON (CUE/GO-ON) > N
  213. # 65369 < 0 1 0 1 1 0 0 1 > LEDc|bl|br (+TS-ON) > LF-ON (CUE/GO-ON) > N
  214. # 65370 < 0 1 0 1 1 0 1 0 > LEDc|lb|lt (+TS-ON) > SG-ON (CUE/GO-ON) > N
  215. # 65376 < 0 1 1 0 0 0 0 0 > LEDc+TaSw > GO-OFF/RW-OFF > all
  216. # 65381 < 0 1 1 0 0 1 0 1 > TaSw (+LEDc|rt|rb) > SR (+PG) > all
  217. # 65382 < 0 1 1 0 0 1 1 0 > TaSw (+LEDc|tl|tr) > SR (+HF) > all
  218. # 65383 < 0 1 1 0 0 1 1 1 > TaSw (+LEDc|rt|rb|tl) > SR (+PGHF/HFPG) >
  219. # 65385 < 0 1 1 0 1 0 0 1 > TaSw (+LEDc|bl|br) > SR (+LF) > all
  220. # 65386 < 0 1 1 0 1 0 1 0 > TaSw (+LEDc|lb|lt) > SR (+SG) > all
  221. # 65387 < 0 1 1 0 1 0 1 1 > TaSw (+LEDc|lb|lt|br) > SR (+SGLF/LGSG) >
  222. # 65389 < 0 1 1 0 1 1 0 1 > TaSw (+LEDc|rt|rb|bl) > SR (+PGLF/LFPG) >
  223. # 65390 < 0 1 1 0 1 1 1 0 > TaSw (+LEDc|lb|lt|tr) > SR (+SGHF/HFSG) >
  224. # 65391 < 0 1 1 0 1 1 1 1 > LEDall (+TaSw) > ERROR-FLASH-ON > L,T
  225. # 65440 < 1 0 1 0 0 0 0 0 > RwPu (+TaSw) > RW-ON (noLEDs) > N
  226. # 65504 < 1 1 1 0 0 0 0 0 > RwPu (+LEDc) > RW-ON (-CONF) > L,T
  227. # 65509 < 1 1 1 0 0 1 0 1 > RwPu (+LEDcr) > RW-ON (+CONF-PG) > all
  228. # 65510 < 1 1 1 0 0 1 1 0 > RwPu (+LEDct) > RW-ON (+CONF-HF) > N?
  229. # 65513 < 1 1 1 0 1 0 0 1 > RwPu (+LEDcb) > RW-ON (+CONF-LF) > N?
  230. # 65514 < 1 1 1 0 1 0 1 0 > RwPu (+LEDcl) > RW-ON (+CONF-SG) > all
  231. # ^ ^ ^ ^ ^ ^ ^ ^
  232. # label binary code
  233. #
  234. # ABBREVIATIONS:
  235. # c (central), l (left), t (top), b (bottom), r (right),
  236. # HF (high force, LEDt), LF (low force, LEDb), SG (side grip, LEDl),
  237. # PG (precision grip, LEDr), RwPu (reward pump), TaSw (table switch),
  238. # TS (trial start), SR (switch release), WS (warning signal), RW (reward),
  239. # L (Lilou), T (Tanya t+a), N (Nikos n+i)
  240. ###########################################################################
  241. # Create dictionaries for event labels
  242. event_labels_str = {
  243. '65280': 'TS-OFF/STOP',
  244. '65296': 'TS-ON',
  245. '65312': 'STOP',
  246. '65344': 'WS-ON/CUE-OFF',
  247. '65349': 'PG-ON',
  248. '65350': 'HF-ON',
  249. '65353': 'LF-ON',
  250. '65354': 'SG-ON',
  251. '65359': 'ERROR-FLASH-ON',
  252. '65360': 'WS-ON/CUE-OFF',
  253. '65365': 'PG-ON',
  254. '65366': 'HF-ON',
  255. '65369': 'LF-ON',
  256. '65370': 'SG-ON',
  257. '65376': 'GO/RW-OFF',
  258. '65381': 'SR (+PG)',
  259. '65382': 'SR (+HF)',
  260. '65383': 'SR (+PGHF/HFPG)',
  261. '65385': 'SR (+LF)',
  262. '65386': 'SR (+SG)',
  263. '65387': 'SR (+SGLF/LFSG)',
  264. '65389': 'SR (+PGLF/LFPG)',
  265. '65390': 'SR (+SGHF/HFSG)',
  266. '65391': 'ERROR-FLASH-ON',
  267. '65440': 'RW-ON (noLEDs)',
  268. '65504': 'RW-ON (-CONF)',
  269. '65509': 'RW-ON (+CONF-PG)',
  270. '65510': 'RW-ON (+CONF-HF)',
  271. '65513': 'RW-ON (+CONF-LF)',
  272. '65514': 'RW-ON (+CONF-SG)'}
  273. event_labels_codes = dict(
  274. [(k, []) for k in np.unique(list(event_labels_str.values()))]) #inefficient in Python2
  275. for k in list(event_labels_codes):
  276. for l, v in event_labels_str.items(): #inefficient in Python2
  277. if v == k:
  278. event_labels_codes[k].append(l)
  279. # additional summaries
  280. event_labels_codes['CUE/GO'] = \
  281. event_labels_codes['SG-ON'] + \
  282. event_labels_codes['PG-ON'] + \
  283. event_labels_codes['LF-ON'] + \
  284. event_labels_codes['HF-ON']
  285. event_labels_codes['RW-ON'] = \
  286. event_labels_codes['RW-ON (+CONF-PG)'] + \
  287. event_labels_codes['RW-ON (+CONF-HF)'] + \
  288. event_labels_codes['RW-ON (+CONF-LF)'] + \
  289. event_labels_codes['RW-ON (+CONF-SG)'] + \
  290. event_labels_codes['RW-ON (-CONF)'] + \
  291. event_labels_codes['RW-ON (noLEDs)']
  292. event_labels_codes['SR'] = \
  293. event_labels_codes['SR (+PG)'] + \
  294. event_labels_codes['SR (+HF)'] + \
  295. event_labels_codes['SR (+LF)'] + \
  296. event_labels_codes['SR (+SG)'] + \
  297. event_labels_codes['SR (+PGHF/HFPG)'] + \
  298. event_labels_codes['SR (+SGHF/HFSG)'] + \
  299. event_labels_codes['SR (+PGLF/LFPG)'] + \
  300. event_labels_codes['SR (+SGLF/LFSG)']
  301. del k, l, v
  302. # Create dictionaries for constant trial sequences (in all monkeys)
  303. # (bit position (value) set if trial event (key) occurred)
  304. trial_const_sequence_codes = {
  305. 'TS-ON': 0,
  306. 'WS-ON': 1,
  307. 'CUE-ON': 2,
  308. 'CUE-OFF': 3,
  309. 'GO-ON': 4,
  310. 'SR': 5,
  311. 'RW-ON': 6,
  312. 'STOP': 7}
  313. trial_const_sequence_str = dict(
  314. (v, k) for k, v in trial_const_sequence_codes.items()) #inefficient in Python2
  315. # Create dictionaries for trial performances
  316. # (resulting decimal number from binary number created from trial_sequence)
  317. performance_codes = {
  318. 'incomplete_trial': 0,
  319. 'error<SR-ON': 159,
  320. 'error<WS': 161,
  321. 'error<CUE-ON': 163,
  322. 'error<CUE-OFF': 167,
  323. 'error<GO-ON': 175,
  324. 'grip_error': 191,
  325. 'correct_trial': 255}
  326. performance_str = dict((v, k) for k, v in performance_codes.items()) #inefficient in Python2
  327. def __init__(
  328. self, filename, odml_directory=None,
  329. nsx_override=None, nev_override=None,
  330. sif_override=None, ccf_override=None, odml_filename=None,
  331. verbose=False):
  332. """
  333. Constructor
  334. """
  335. # Remember choice whether to print diagnostic messages or not
  336. self._verbose = verbose
  337. # Remove known extensions from input filename
  338. for ext in self.extensions:
  339. filename = re.sub(os.path.extsep + ext + '$', '', filename)
  340. if nev_override:
  341. # check if sorting postfix is appended to nev_override name
  342. if nev_override[-3] == '-':
  343. sorting_postfix = nev_override[-2:]
  344. else:
  345. sorting_postfix = None
  346. sorting_version = nev_override
  347. else:
  348. # find most recent spike sorting version
  349. nev_versions = [re.sub(
  350. os.path.extsep + 'nev$', '', p) for p in glob.glob(
  351. filename + '*.nev')]
  352. nev_versions = [p.replace(filename, '') for p in nev_versions]
  353. if len(nev_versions):
  354. sorting_postfix = sorted(nev_versions)[-1]
  355. else:
  356. sorting_postfix = ''
  357. sorting_version = filename + sorting_postfix
  358. # Initialize file
  359. BlackrockIO.__init__(
  360. self, filename, nsx_override=nsx_override,
  361. nev_override=sorting_version, sif_override=sif_override,
  362. ccf_override=ccf_override, verbose=verbose)
  363. # if no odML directory is specified, use same directory as main files
  364. if not odml_directory:
  365. odml_directory = os.path.dirname(self.filename)[:-1]
  366. # remove extensions from odml override
  367. filen = os.path.split(self.filename)[-1]
  368. if odml_filename:
  369. self._filenames['odml'] = ''.join(
  370. [odml_directory, os.path.sep, odml_filename])
  371. else:
  372. self._filenames['odml'] = ''.join(
  373. [odml_directory, os.path.sep, filen])
  374. file2check = ''.join([self._filenames['odml'], os.path.extsep, 'odml'])
  375. if os.path.exists(file2check):
  376. self._avail_files['odml'] = True
  377. self.odmldoc = odml.load(file2check)
  378. else:
  379. self._avail_files['odml'] = False
  380. self.odmldoc = None
  381. # If we did not specify an explicit sorting version, and there is an
  382. # odML, then make sure the detected sorting version matches the odML
  383. if self.odmldoc:
  384. if sorting_postfix not in self.odmldoc.sections['PreProcessing'].sections[
  385. 'OfflineSpikeSorting'].properties['Sortings'].values:
  386. self._print_verbose(
  387. "Attempting to utilize the most recent "
  388. "sorting version in file %s, but the sorting version "
  389. "specified in odML is %s" % (
  390. sorting_version,
  391. self.odmldoc.sections['PreProcessing'].sections[
  392. 'OfflineSpikeSorting'].properties['Sortings'].values))
  393. self._load_spikesorting_info = False
  394. else:
  395. self._load_spikesorting_info = True
  396. else:
  397. self._load_spikesorting_info = False
  398. def __is_set(self, flag, pos):
  399. """
  400. Checks if bit is set at the given position for flag. If flag is an
  401. array, an array will be returned.
  402. """
  403. return flag & (1 << pos) > 0
  404. def __set_bit(self, flag, pos):
  405. """
  406. Returns the given flag with an additional bit set at the given
  407. position. for flag. If flag is an array, an array will be returned.
  408. """
  409. return flag | (1 << pos)
  410. def __add_rejection_to_event(self, event):
  411. """
  412. Given an event with annotation trial_id, adds information on whether to
  413. reject the trial or not.
  414. """
  415. if self.odmldoc:
  416. # Get rejection bands
  417. sec = self.odmldoc['PreProcessing']
  418. bands = sec.properties['LFPBands'].values
  419. for band in bands:
  420. sec = self.odmldoc['PreProcessing'][band]
  421. if type(sec.properties['RejTrials'].values) != [-1]:
  422. rej_trials = [int(_) for _ in sec.properties['RejTrials'].values]
  423. rej_index = np.in1d(event.array_annotations['trial_id'], rej_trials)
  424. elif sec.properties['RejTrials'].values == [-1]:
  425. rej_index = np.zeros((len(event.array_annotations['trial_id'])), dtype=bool)
  426. else:
  427. raise ValueError(
  428. "Invalid entry %s in odML for rejected trials in LFP band %s." %
  429. (sec.properties['RejTrials'].values, band))
  430. event.array_annotate(**{str('trial_reject_' + band): list(rej_index)})
  431. def __extract_task_condition(self, trialtypes):
  432. """
  433. Extracts task condition from trialtypes.
  434. """
  435. occurring_trtys = np.unique(trialtypes).tolist()
  436. # reduce occurring_trtys to actual trialtypes
  437. # (remove all not identifiable trialtypes (incomplete/error trial))
  438. if 'NONE' in occurring_trtys:
  439. occurring_trtys.remove('NONE')
  440. # (remove all trialtypes where only the CUE was detected (error trial))
  441. if 'SG' in occurring_trtys:
  442. occurring_trtys.remove('SG')
  443. if 'PG' in occurring_trtys:
  444. occurring_trtys.remove('PG')
  445. if 'LF' in occurring_trtys:
  446. occurring_trtys.remove('LF')
  447. if 'HF' in occurring_trtys:
  448. occurring_trtys.remove('HF')
  449. # first set to unidentified task condition
  450. task_condition = 0
  451. if len(occurring_trtys) > 0:
  452. for cnd, trtys in self.condition_str.items(): #inefficient in Python2
  453. if set(trtys) == set(occurring_trtys):
  454. # replace with detected task condition
  455. task_condition = cnd
  456. return task_condition
  457. def __extract_analog_events_from_odml(self, t_start, t_stop):
  458. event_name = []
  459. event_time = []
  460. trial_id = []
  461. trial_timestamp_id = []
  462. performance_code = []
  463. trial_type = []
  464. # Look for all Trial Sections
  465. sec = self.odmldoc['Recording']['TaskSettings']
  466. ff = lambda x: x.name.startswith('Trial_')
  467. tr_secs = sec.itersections(filter_func=ff)
  468. for trial_sec in tr_secs:
  469. for signalname in ['GripForceSignals', 'DisplacementSignal']:
  470. for analog_events in trial_sec[
  471. 'AnalogEvents'][signalname].properties:
  472. time = analog_events.values * \
  473. pq.CompoundUnit(analog_events.unit)
  474. if time >= t_start and time < t_stop:
  475. event_name.append(analog_events.name)
  476. event_time.append(time)
  477. trial_id.extend(
  478. trial_sec.properties['TrialID'].values)
  479. trial_timestamp_id.extend(
  480. trial_sec.properties[
  481. 'TrialTimestampID'].values)
  482. performance_code.extend(
  483. trial_sec.properties['PerformanceCode'].values)
  484. trial_type.extend(
  485. trial_sec.properties['TrialType'].values)
  486. # Create event object with analog events
  487. analog_events = neo.Event(
  488. times=pq.Quantity(
  489. [_.magnitude for _ in event_time],
  490. units=event_time[0].units).rescale('ms').flatten(),
  491. labels=np.array(event_name),
  492. name='AnalogTrialEvents',
  493. description='Events extracted from analog signals')
  494. analog_events.array_annotate(
  495. trial_id=trial_id,
  496. trial_timestamp_id=trial_timestamp_id,
  497. performance_in_trial=performance_code,
  498. belongs_to_trialtype=trial_type,
  499. trial_event_labels=event_name)
  500. return analog_events
  501. def __annotate_dig_trial_events(self, events):
  502. """
  503. Modifies events of digital input port to trial events of the
  504. reach-to-grasp project.
  505. """
  506. # Modifiy name and description
  507. events.name = "DigitalTrialEvents"
  508. events.description = "Trial " + events.description.lower()
  509. # Uncomment for event and trial sequence debugging
  510. # for ev in events.labels:
  511. # if ev in list(self.event_labels_str):
  512. # print ev, self.event_labels_str[ev]
  513. # else:
  514. # print ev
  515. # Extract beginning of first complete trial
  516. tson_label = self.event_labels_codes['TS-ON'][0]
  517. if tson_label in events.labels:
  518. first_TSon_idx = list(events.labels).index(tson_label)
  519. else:
  520. first_TSon_idx = len(events.labels)
  521. # Extract end of last complete trial
  522. stop_label = self.event_labels_codes['STOP'][0]
  523. if stop_label in events.labels:
  524. last_WSoff_idx = len(events.labels) - \
  525. list(events.labels[::-1]).index(stop_label) - 1
  526. else:
  527. last_WSoff_idx = -1
  528. # Annotate events with modified labels, trial ids, and trial types
  529. trial_event_labels = []
  530. trial_ID = []
  531. trial_timestamp_ID = []
  532. trialtypes = {-1: 'NONE'}
  533. trialsequence = {-1: 0}
  534. for i, l in enumerate(events.labels):
  535. if i < first_TSon_idx or i > last_WSoff_idx:
  536. trial_event_labels.append('NONE')
  537. trial_ID.append(-1)
  538. trial_timestamp_ID.append(-1)
  539. else:
  540. # interpretation of TS-ON
  541. if self.event_labels_str[l] == 'TS-ON':
  542. if i > 0:
  543. prev_ev = events.labels[i - 1]
  544. if self.event_labels_str[prev_ev] in \
  545. ['STOP', 'TS-OFF/STOP']:
  546. timestamp_id = int(events.times[i].rescale(
  547. self._BlackrockIO__nev_params(
  548. 'event_unit')).item())
  549. trial_timestamp_ID.append(timestamp_id)
  550. trial_event_labels.append('TS-ON')
  551. trialsequence[timestamp_id] = self.__set_bit(
  552. 0, self.trial_const_sequence_codes['TS-ON'])
  553. else:
  554. timestamp_id = trial_timestamp_ID[-1]
  555. trial_timestamp_ID.append(timestamp_id)
  556. trial_event_labels.append('TS-ON-ERROR')
  557. else:
  558. timestamp_id = int(events.times[i].rescale(
  559. self._BlackrockIO__nev_params(
  560. 'event_unit')).item())
  561. trial_timestamp_ID.append(timestamp_id)
  562. trial_event_labels.append('TS-ON')
  563. trialsequence[timestamp_id] = self.__set_bit(
  564. 0, self.trial_const_sequence_codes['TS-ON'])
  565. # Identify trial ID if odML exists
  566. ID = -1
  567. if self.odmldoc:
  568. sec = self.odmldoc['Recording']['TaskSettings']
  569. ff = lambda x: x.name.startswith('Trial_')
  570. tr_secs = sec.itersections(filter_func=ff)
  571. for trial_sec in tr_secs:
  572. if trial_sec.properties[
  573. 'TrialTimestampID'].values[0] == \
  574. timestamp_id:
  575. ID = trial_sec.properties['TrialID'].values[0]
  576. trial_ID.append(ID)
  577. # interpretation of GO/RW-OFF
  578. elif self.event_labels_str[l] == 'GO/RW-OFF':
  579. trial_timestamp_ID.append(timestamp_id)
  580. trial_ID.append(ID)
  581. trial_event_labels.append('GO/RW-OFF')
  582. # interpretation of ERROR-FLASH-ON
  583. elif l in self.event_labels_codes['ERROR-FLASH-ON']:
  584. trial_timestamp_ID.append(timestamp_id)
  585. trial_ID.append(ID)
  586. trial_event_labels.append('ERROR-FLASH-ON')
  587. # Error-Flash hides too early activation of SR
  588. # SR is set to 1 here to match perf codes between monkeys
  589. trialsequence[timestamp_id] = self.__set_bit(
  590. trialsequence[timestamp_id],
  591. self.trial_const_sequence_codes['SR'])
  592. # TS-OFF/STOP
  593. elif self.event_labels_str[l] == 'TS-OFF/STOP':
  594. trial_timestamp_ID.append(timestamp_id)
  595. trial_ID.append(ID)
  596. prev_ev = events.labels[i - 1]
  597. if self.event_labels_str[prev_ev] == 'TS-ON':
  598. trial_event_labels.append('TS-OFF')
  599. elif prev_ev in self.event_labels_codes['ERROR-FLASH-ON']:
  600. trial_event_labels.append('STOP')
  601. trialsequence[timestamp_id] = self.__set_bit(
  602. trialsequence[timestamp_id],
  603. self.trial_const_sequence_codes['STOP'])
  604. else:
  605. trial_event_labels.append('STOP')
  606. trialsequence[timestamp_id] = self.__set_bit(
  607. trialsequence[timestamp_id],
  608. self.trial_const_sequence_codes['STOP'])
  609. # interpretation of WS-ON/CUE-OFF
  610. elif self.event_labels_str[l] == 'WS-ON/CUE-OFF':
  611. trial_timestamp_ID.append(timestamp_id)
  612. trial_ID.append(ID)
  613. prev_ev = events.labels[i - 1]
  614. if self.event_labels_str[prev_ev] in \
  615. ['TS-ON', 'TS-OFF/STOP']:
  616. trial_event_labels.append('WS-ON')
  617. trialsequence[timestamp_id] = self.__set_bit(
  618. trialsequence[timestamp_id],
  619. self.trial_const_sequence_codes['WS-ON'])
  620. elif (prev_ev in self.event_labels_codes['CUE/GO'] or
  621. prev_ev in self.event_labels_codes['GO/RW-OFF']):
  622. trial_event_labels.append('CUE-OFF')
  623. trialsequence[timestamp_id] = self.__set_bit(
  624. trialsequence[timestamp_id],
  625. self.trial_const_sequence_codes['CUE-OFF'])
  626. else:
  627. raise ValueError("Unknown trial event sequence.")
  628. # interpretation of CUE and GO events and trialtype detection
  629. elif l in self.event_labels_codes['CUE/GO']:
  630. trial_timestamp_ID.append(timestamp_id)
  631. trial_ID.append(ID)
  632. prprev_ev = events.labels[i - 2]
  633. if self.event_labels_str[prprev_ev] in \
  634. ['TS-ON', 'TS-OFF/STOP']:
  635. trial_event_labels.append('CUE-ON')
  636. trialsequence[timestamp_id] = self.__set_bit(
  637. trialsequence[timestamp_id],
  638. self.trial_const_sequence_codes['CUE-ON'])
  639. trialtypes[timestamp_id] = self.event_labels_str[l][:2]
  640. elif prprev_ev in self.event_labels_codes['CUE/GO']:
  641. trial_event_labels.append('GO-ON')
  642. trialsequence[timestamp_id] = self.__set_bit(
  643. trialsequence[timestamp_id],
  644. self.trial_const_sequence_codes['GO-ON'])
  645. trialtypes[timestamp_id] += \
  646. self.event_labels_str[l][:2]
  647. else:
  648. raise ValueError("Unknown trial event sequence.")
  649. # interpretation of WS-OFF
  650. elif self.event_labels_str[l] == 'STOP':
  651. trial_timestamp_ID.append(timestamp_id)
  652. trial_ID.append(ID)
  653. prev_ev = self.event_labels_str[events.labels[i - 1]]
  654. if prev_ev == 'ERROR-FLASH-ON':
  655. trial_event_labels.append('ERROR-FLASH-OFF')
  656. else:
  657. trial_event_labels.append('STOP')
  658. trialsequence[timestamp_id] = self.__set_bit(
  659. trialsequence[timestamp_id],
  660. self.trial_const_sequence_codes['STOP'])
  661. # interpretation of SR events
  662. elif l in self.event_labels_codes['SR']:
  663. trial_timestamp_ID.append(timestamp_id)
  664. trial_ID.append(ID)
  665. prev_ev = events.labels[i - 1]
  666. if prev_ev in self.event_labels_codes['SR']:
  667. trial_event_labels.append('SR-REP')
  668. elif prev_ev in self.event_labels_codes['RW-ON']:
  669. trial_event_labels.append('RW-OFF')
  670. else:
  671. trial_event_labels.append('SR')
  672. trialsequence[timestamp_id] = self.__set_bit(
  673. trialsequence[timestamp_id],
  674. self.trial_const_sequence_codes['SR'])
  675. # interpretation of RW events
  676. elif l in self.event_labels_codes['RW-ON']:
  677. trial_timestamp_ID.append(timestamp_id)
  678. trial_ID.append(ID)
  679. prev_ev = events.labels[i - 1]
  680. if prev_ev in self.event_labels_codes['RW-ON']:
  681. trial_event_labels.append('RW-ON-REP')
  682. else:
  683. trial_event_labels.append('RW-ON')
  684. trialsequence[timestamp_id] = self.__set_bit(
  685. trialsequence[timestamp_id],
  686. self.trial_const_sequence_codes['RW-ON'])
  687. else:
  688. raise ValueError("Unknown event label.")
  689. # add modified trial_event_labels to annotations
  690. events.array_annotate(trial_event_labels=trial_event_labels)
  691. # add trial timestamp IDs
  692. events.array_annotate(trial_timestamp_id=trial_timestamp_ID)
  693. # add trial IDs
  694. events.array_annotate(trial_id=trial_ID)
  695. # add modified belongs_to_trialtype to annotations
  696. for tid in trial_timestamp_ID:
  697. if tid not in list(trialtypes):
  698. trialtypes[tid] = 'NONE'
  699. belongs_to_trialtype = [
  700. trialtypes[tid] for tid in trial_timestamp_ID]
  701. events.array_annotate(belongs_to_trialtype=belongs_to_trialtype)
  702. # add modified trial_performance_codes to annotations
  703. performance_in_trial = [trialsequence[tid] for tid in trial_timestamp_ID]
  704. performance_in_trial_str = []
  705. for pit in performance_in_trial:
  706. if pit in self.performance_str:
  707. performance_in_trial_str.append(self.performance_str[pit])
  708. else:
  709. performance_in_trial_str.append('unknown')
  710. events.array_annotate(performance_in_trial=performance_in_trial)
  711. events.array_annotate(performance_in_trial_str=performance_in_trial_str)
  712. def __annotate_units_with_odml(self, units):
  713. """
  714. Annotates units with metadata from odml file.
  715. """
  716. # Can the spike sorting info from the odML be matched with the odML?
  717. if not self._load_spikesorting_info:
  718. return
  719. for un in units:
  720. an_dict = dict(
  721. sua=False,
  722. mua=False,
  723. noise=False)
  724. try:
  725. sec = self.odmldoc['UtahArray']['Array'][
  726. 'Electrode_%03d' % un.annotations['channel_id']][
  727. 'OfflineSpikeSorting']
  728. except KeyError:
  729. return
  730. suaids = sec.properties['SUAIDs'].values
  731. muaid = sec.properties['MUAID'].values[0]
  732. noiseids = sec.properties['NoiseIDs'].values
  733. if un.annotations['unit_id'] in suaids:
  734. an_dict['sua'] = True
  735. elif un.annotations['unit_id'] in noiseids:
  736. an_dict['noise'] = True
  737. elif un.annotations['unit_id'] == muaid:
  738. an_dict['mua'] = True
  739. else:
  740. raise ValueError(
  741. "Unit %i is not registered for channel %i in odML file."
  742. % (un.annotations['unit_id'],
  743. un.annotations['channel_id']))
  744. if ('Unit_%02i' % un.annotations['unit_id']) in sec.sections:
  745. unit_sec = sec['Unit_%02i' % un.annotations['unit_id']]
  746. if an_dict['sua']:
  747. an_dict['SNR'] = unit_sec.properties['SNR'].values[0]
  748. # TODO: Add units here
  749. an_dict['spike_duration'] = unit_sec.properties['SpikeDuration'].values[0]
  750. an_dict['spike_amplitude'] = unit_sec.properties['SpikeAmplitude'].values[0]
  751. an_dict['spike_count'] = unit_sec.properties['SpikeCount'].values[0]
  752. # Annotate Unit and all children for convenience
  753. un.annotate(**an_dict)
  754. for st in un.spiketrains:
  755. st.annotate(**an_dict)
  756. def __annotate_spiketrains_with_odml(self, sts):
  757. """
  758. Annotates spiketrains with metadata from odml file.
  759. """
  760. def __annotate_analogsignals_with_odml(self, asig):
  761. """
  762. Annotates analogsignals with metadata from odml file.
  763. """
  764. if self.odmldoc and asig.annotations['channel_id'] in range(1, 129):
  765. # Annotate filter settings from odML
  766. sec = self.odmldoc[
  767. 'Cerebus']['NeuralSignalProcessor']['NeuralSignals'][
  768. 'Filter_ns%i' % asig.annotations['nsx']]
  769. asig.annotate(
  770. filter_hi_pass_freq=pq.Quantity(
  771. sec.properties['HighPassFreq'].values[0],
  772. sec.properties['HighPassFreq'].unit),
  773. filter_lo_pass_freq=pq.Quantity(
  774. sec.properties['LowPassFreq'].values[0],
  775. sec.properties['LowPassFreq'].unit),
  776. filter_hi_pass_order=sec.properties[
  777. 'HighPassOrder'].values[0],
  778. filter_lo_pass_order=sec.properties[
  779. 'LowPassOrder'].values[0],
  780. filter_type=sec.properties[
  781. 'Type'].values[0])
  782. def __annotate_channelindex_with_odml(self, chidx):
  783. """
  784. Annotates channelindex with metadata from odml file.
  785. """
  786. if self.odmldoc:
  787. # Get rejection bands
  788. sec = self.odmldoc['PreProcessing']
  789. bands = sec.properties['LFPBands'].values
  790. if hasattr(bands, '__iter__'):
  791. for band in bands:
  792. sec = self.odmldoc['PreProcessing'][band]
  793. if type(sec.properties['RejElectrodes'].values) is list:
  794. rej_electrodes = [int(_) for _ in sec.properties[
  795. 'RejElectrodes'].values]
  796. rej = chidx.channel_ids[0] in rej_electrodes
  797. elif sec.properties['RejElectrodes'].values == -1:
  798. rej = False
  799. elif sec.properties['RejElectrodes'].values >= 0:
  800. rej_electrodes = sec.properties[
  801. 'RejElectrodes'].values
  802. rej = (chidx.channel_ids[0] == rej_electrodes)
  803. else:
  804. raise ValueError(
  805. "Invalid entry %s in odML for rejected electrodes "
  806. "in LFP band %s." % (
  807. sec.properties['RejElectrodes'].values,
  808. band))
  809. rej_dict = {str('electrode_reject_' + band): rej}
  810. # Annotate ChannelIndex and all children for convenience
  811. chidx.annotate(**rej_dict)
  812. for asig in chidx.analogsignals:
  813. asig.annotate(**rej_dict)
  814. for unit in chidx.units:
  815. unit.annotate(**rej_dict)
  816. for st in unit.spiketrains:
  817. st.annotate(**rej_dict)
  818. # Annotate connector aligned ID to channel
  819. if chidx.channel_ids[0] in \
  820. chidx.block.annotations['avail_electrode_ids']:
  821. ca_dict = {
  822. 'connector_aligned_id': chidx.block.annotations[
  823. 'avail_electrode_ids'].index(chidx.channel_ids[0])+1}
  824. chidx.coordinates = pq.Quantity(np.array([
  825. np.mod(ca_dict['connector_aligned_id']-1, 10)*.4,
  826. (ca_dict['connector_aligned_id']-1)/10*.4]),
  827. units=pq.mm)
  828. chidx.annotate(**ca_dict)
  829. for asig in chidx.analogsignals:
  830. asig.annotate(**ca_dict)
  831. for unit in chidx.units:
  832. unit.annotate(**ca_dict)
  833. for st in unit.spiketrains:
  834. st.annotate(**ca_dict)
  835. def __annotate_block_with_odml(self, bl):
  836. """
  837. Annotates block with metadata from odml file.
  838. """
  839. sec = self.odmldoc['Project']
  840. bl.annotate(
  841. project_name=sec.properties['Name'].values,
  842. project_type=sec.properties['Type'].values,
  843. project_subtype=sec.properties['Subtype'].values)
  844. sec = self.odmldoc['Project']['TaskDesigns']
  845. bl.annotate(
  846. taskdesigns=[v for v in sec.properties['UsedDesign'].values])
  847. sec = self.odmldoc['Subject']
  848. bl.annotate(
  849. subject_name=sec.properties['GivenName'].values,
  850. subject_gender=sec.properties['Gender'].values,
  851. subject_activehand=sec.properties['ActiveHand'].values,
  852. subject_birthday=sec.properties['Birthday'].values)
  853. sec = self.odmldoc['Setup']
  854. bl.annotate(setup_location=sec.properties['Location'].values)
  855. sec = self.odmldoc['UtahArray']
  856. bl.annotate(array_serialnum=sec.properties['SerialNo'].values)
  857. sec = self.odmldoc['UtahArray']['Connector']
  858. bl.annotate(connector_type=sec.properties['Style'].values)
  859. sec = self.odmldoc['UtahArray']['Array']
  860. bl.annotate(arraygrids_tot_num=sec.properties['GridCount'].values)
  861. sec = self.odmldoc['UtahArray']['Array']['Grid_01']
  862. bl.annotate(
  863. electrodes_tot_num=sec.properties['ElectrodeCount'].values,
  864. electrodes_pitch=pq.Quantity(
  865. sec.properties['ElectrodePitch'].values,
  866. units=sec.properties['ElectrodePitch'].unit),
  867. arraygrid_row_num=sec.properties['GridRows'].values,
  868. arraygrid_col_num=sec.properties['GridColumns'].values)
  869. secs = self.odmldoc['UtahArray']['Array'].sections
  870. bl.annotate(
  871. avail_electrode_ids=[])
  872. for i in range(1, 101):
  873. elidx = [s.properties['ID'].values for s in secs if
  874. s.name.startswith('Electrode') and
  875. s.properties['ConnectorAlignedID'].values[0] == i]
  876. if len(elidx) == 0:
  877. bl.annotations['avail_electrode_ids'].append(-1)
  878. elif len(elidx) == 1:
  879. bl.annotations['avail_electrode_ids'].append(elidx[0])
  880. else:
  881. raise ValueError("Electrode IDs in odML file are corrupt. "
  882. "ID %i occurs %i times" % (i, len(elidx)))
  883. # TODO: add list of behavioral channels
  884. # bl.annotate(avail_behavsig_indexes=[])
  885. def __correct_filter_shifts(self, asig):
  886. if self.odmldoc and asig.annotations['channel_id'] in range(1, 129):
  887. # Get and correct for shifts
  888. sec = self.odmldoc[
  889. 'Cerebus']['NeuralSignalProcessor']['NeuralSignals'][
  890. 'Filter_ns%i' % asig.annotations['nsx']]
  891. shift = pq.Quantity(
  892. sec.properties['EstimatedShift'].values[0],
  893. sec.properties['EstimatedShift'].unit)
  894. asig.t_start = asig.t_start - shift
  895. # Annotate shift
  896. asig.annotate(filter_shift_correction=shift)
  897. def __merge_digital_analog_events(self, events):
  898. """
  899. Merge the two event arrays AnalogTrialEvents and DigitalTrialEvents
  900. into one common event array TrialEvents.
  901. """
  902. event_name = []
  903. event_time = None
  904. trial_id = []
  905. trial_timestamp_id = []
  906. performance_code = []
  907. trial_type = []
  908. for event in events:
  909. if event.name in ['AnalogTrialEvents', 'DigitalTrialEvents']:
  910. # Extract event times
  911. if event_time is None:
  912. event_time = event.times.magnitude
  913. event_units = event.times.units
  914. else:
  915. event_time = np.concatenate((
  916. event_time,
  917. event.times.rescale(event_units).magnitude.flatten()))
  918. # Transfer annotations
  919. trial_id.extend(
  920. event.array_annotations['trial_id'])
  921. trial_timestamp_id.extend(
  922. event.array_annotations['trial_timestamp_id'])
  923. performance_code.extend(
  924. event.array_annotations['performance_in_trial'])
  925. trial_type.extend(
  926. event.array_annotations['belongs_to_trialtype'])
  927. event_name.extend(
  928. event.array_annotations['trial_event_labels'])
  929. # Sort time stamps and save sort order
  930. sort_idx = np.argsort(event_time)
  931. event_time = event_time[sort_idx]
  932. # Create event object with analog events
  933. merged_event = neo.Event(
  934. times=pq.Quantity(event_time, units=event_units),
  935. labels=np.array([event_name[_] for _ in sort_idx]),
  936. name='TrialEvents',
  937. description='All trial events (digital and analog)')
  938. merged_event.array_annotate(
  939. trial_id=[trial_id[_] for _ in sort_idx],
  940. trial_timestamp_id=[trial_timestamp_id[_] for _ in sort_idx],
  941. performance_in_trial=[performance_code[_] for _ in sort_idx],
  942. belongs_to_trialtype=[trial_type[_] for _ in sort_idx],
  943. trial_event_labels=[event_name[_] for _ in sort_idx])
  944. return merged_event
  945. def read_block(
  946. self, index=None, name=None, description=None, nsx_to_load='none',
  947. n_starts=None, n_stops=None, channels=range(1, 97), units='none',
  948. load_waveforms=False, load_events=False, scaling='raw',
  949. correct_filter_shifts=True, lazy=False, cascade=True):
  950. """
  951. Reads file contents as a Neo Block.
  952. The Block contains one Segment for each entry in zip(n_starts,
  953. n_stops). If these parameters are not specified, the default is
  954. to store all data in one Segment.
  955. The Block contains one ChannelIndex per channel.
  956. Args:
  957. index (None, int):
  958. If not None, index of block is set to user input.
  959. name (None, str):
  960. If None, name is set to default, otherwise it is set to user
  961. input.
  962. description (None, str):
  963. If None, description is set to default, otherwise it is set to
  964. user input.
  965. nsx_to_load (int, list, str):
  966. ID(s) of nsx file(s) from which to load data, e.g., if set to
  967. 5 only data from the ns5 file are loaded. If 'none' or empty
  968. list, no nsx files and therefore no analog signals are loaded.
  969. If 'all', data from all available nsx are loaded.
  970. n_starts (None, Quantity, list):
  971. Start times for data in each segment. Number of entries must be
  972. equal to length of n_stops. If None, intrinsic recording start
  973. times of files set are used.
  974. n_stops (None, Quantity, list):
  975. Stop times for data in each segment. Number of entries must be
  976. equal to length of n_starts. If None, intrinsic recording stop
  977. times of files set are used.
  978. channels (int, list, str):
  979. Channel id(s) from which to load data. If 'none' or empty list,
  980. no channels and therefore no analog signal or spiketrains are
  981. loaded. If 'all', all available channels are loaded. By
  982. default, all neural channels (1-96) are loaded.
  983. units (int, list, str, dict):
  984. ID(s) of unit(s) to load. If 'none' or empty list, no units and
  985. therefore no spiketrains are loaded. If 'all', all available
  986. units are loaded. If dict, the above can be specified
  987. individually for each channel (keys), e.g. {1: 5, 2: 'all'}
  988. loads unit 5 from channel 1 and all units from channel 2.
  989. load_waveforms (boolean):
  990. If True, waveforms are attached to all loaded spiketrains.
  991. load_events (boolean):
  992. If True, all recorded events are loaded.
  993. scaling (str):
  994. Determines whether time series of individual
  995. electrodes/channels are returned as AnalogSignals containing
  996. raw integer samples ('raw'), or scaled to arrays of floats
  997. representing voltage ('voltage'). Note that for file
  998. specification 2.1 and lower, the option 'voltage' requires a
  999. nev file to be present.
  1000. correct_filter_shifts (bool):
  1001. If True, shifts of the online-filtered neural signals (e.g.,
  1002. ns2, channels 1-128) are corrected by time-shifting the signal
  1003. by a heuristically determined estimate stored in the metadata,
  1004. in the property EstimatedShift, under the path
  1005. /Cerebus/NeuralSignalProcessor/NeuralSignals/Filter_nsX/
  1006. lazy (bool):
  1007. If True, only the shape of the data is loaded.
  1008. cascade (bool or "lazy"):
  1009. If True, only the block without children is returned.
  1010. Returns:
  1011. Block (neo.segment.Block):
  1012. Block linking to all loaded Neo objects.
  1013. Block annotations:
  1014. avail_file_set (list of str):
  1015. List of file extensions of the files found to be
  1016. associated to the project, and which are used in
  1017. loading the data, e.g., ccf, odml, nev, ns2,...
  1018. avail_nsx (list of int):
  1019. List of integers specifying the .nsX files available,
  1020. e.g., [2, 5] indicates that an ns2 and and ns5 file are
  1021. available.
  1022. avail_nev (bool):
  1023. True if a .nev file is available.
  1024. avail_ccf (bool):
  1025. True if a .ccf file is available.
  1026. avail_sif (bool):
  1027. True if a .sif file is available.
  1028. nb_segments (int):
  1029. Number of segments created after merging recording
  1030. times specified by user with the intrinsic ones of the
  1031. file set.
  1032. project_name (str):
  1033. Identifier for the project/experiment.
  1034. project_type (str):
  1035. Identifier for the type of project/experiment.
  1036. project_subtype (str):
  1037. Identifier of the subtype of the project/experiment.
  1038. taskdesigns (list of str):
  1039. List of strings identifying the task designed presented
  1040. during the recording. The standard task reach-to-grasp
  1041. is denoted by the string "TwoCues".
  1042. conditions (list of int):
  1043. List of condition codes (each code describing the set
  1044. of trial types presented to the subject during a
  1045. segment of the recording) present during the recording.
  1046. For a mapping of condition codes to trial types, see
  1047. the condition_str attribute of the ReachGraspIO class.
  1048. subject_name (str):
  1049. Name of the recorded subject.
  1050. subject_gender (bool):
  1051. 'male' or 'female'.
  1052. subject_birthday (datetime):
  1053. Birthday of the recorded subject.
  1054. subject_activehand (str):
  1055. Handedness of the subject.
  1056. setup_location (str):
  1057. Physical location of the recording setup.
  1058. avail_electrode_ids (list of int):
  1059. List of length 100 of electrode channel IDs (Blackrock
  1060. IDs) ordered corresponding to the connector-aligned
  1061. linear electrode IDs. The connector-aligned IDs start
  1062. at 1 in the bottom left corner, and increase from left
  1063. to right, and from bottom to top assuming the array is
  1064. placed in front of the observer pins facing down,
  1065. connector extruding to the right:
  1066. 91 92 ... 99 100 \
  1067. 81 82 ... 89 90 \
  1068. ... ... --- Connector Wires
  1069. 11 12 ... 19 20 /
  1070. 1 2 ... 9 10 /
  1071. Thus,
  1072. avail_electrode_ids[k-1]
  1073. is the Blackrock channel ID corresponding to connector-
  1074. aligned ID k. Unconnected/unavailable channels are
  1075. marked by -1.
  1076. arraygrids_tot_num (int):
  1077. Number of Utah arrays (not necessarily all connected).
  1078. electrodes_tot_num (int):
  1079. Number of electrodes of the Utah array (not necessarily
  1080. all connected).
  1081. electrodes_pitch (float):
  1082. Distance in micrometers between neighboring electrodes
  1083. in one row/column.
  1084. array_serial_num (str):
  1085. Serial number of the recording array.
  1086. array_grid_col_num, array_grid_row_num (int):
  1087. Number of columns / rows of the array.
  1088. connector_type (str):
  1089. Type of connector used for recording.
  1090. rec_pauses (bool):
  1091. True if the session contains a recording pause (i.e.,
  1092. multiple segments).
  1093. Segment annotations:
  1094. condition (int):
  1095. Condition code (describing the set of trial types
  1096. presented to the subject) of this segment. For a
  1097. mapping of condition codes to trial types, see the
  1098. condition_str attribute of the ReachGraspIO class.
  1099. ChannelIndex annotations:
  1100. connector_aligned_id (int):
  1101. Connector-aligned channel ID from which the spikes were
  1102. loaded. This is a channel ID between 1 and 100 that is
  1103. related to the location of an electrode on the Utah
  1104. array and thus common across different arrays
  1105. (independent of the Blackrock channel ID). The ID
  1106. considers a top-view of the array with the connector
  1107. wires extruding to the right. Electrodes are then
  1108. numbered from bottom left to top right:
  1109. 91 92 ... 99 100 \
  1110. 81 82 ... 89 90 \
  1111. ... ... --- Connector Wires
  1112. 11 12 ... 19 20 /
  1113. 1 2 ... 9 10 /
  1114. Note: The Blackrock IDs are given in the 'channel_ids'
  1115. property of the ChannelIndex object.
  1116. waveform_size (Quantitiy):
  1117. Length of time used to save spike waveforms (in units
  1118. of 1/30000 s).
  1119. nev_hi_freq_corner (Quantitiy),
  1120. nev_lo_freq_corner (Quantitiy),
  1121. nev_hi_freq_order (int), nev_lo_freq_order (int),
  1122. nev_hi_freq_type (str), nev_lo_freq_type (str),
  1123. nev_hi_threshold, nev_lo_threshold,
  1124. nev_energy_threshold (Quantity):
  1125. Indicates parameters of spike detection.
  1126. nev_dig_factor (int):
  1127. Digitization factor in microvolts of the nev file, used
  1128. to convert raw samples to volt.
  1129. connector_ID, connector_pinID (int):
  1130. ID of connector and pin on the connector where the
  1131. channel was recorded from.
  1132. nb_sorted_units (int):
  1133. Number of sorted units on this channel (noise, mua and
  1134. sua).
  1135. electrode_reject_XXX (bool):
  1136. For different filter ranges XXX (as defined in the odML
  1137. file), if this variable is True it indicates whether
  1138. the spikes were recorded on an electrode that should be
  1139. rejected based on preprocessing analysis for removing
  1140. electrodes due to noise/artefacts in the respective
  1141. frequency range.
  1142. Unit annotations:
  1143. coordinates (Quantity):
  1144. Contains the x and y coordinate of the electrode in mm
  1145. (spacing: 0.4mm). The coordinates use the same
  1146. representation as the connector_aligned_id with the
  1147. origin located at the bottom left electrode. Thus,
  1148. e.g., connector aligned ID 14 is at coordinates:
  1149. (1.2 mm, 0.4 mm)
  1150. unit_id (int):
  1151. ID of the unit.
  1152. channel_id (int):
  1153. Channel ID (Blackrock ID) from which the unit was
  1154. loaded (equiv. to the single list entry in the
  1155. attribute channel_ids of ChannelIndex parent).
  1156. connector_aligned_id (int):
  1157. Connector-aligned channel ID from which the unit was
  1158. loaded. This is a channel ID between 1 and 100 that is
  1159. related to the location of an electrode on the Utah
  1160. array and thus common across different arrays
  1161. (independent of the Blackrock channel ID). The ID
  1162. considers a top-view of the array with the connector
  1163. wires extruding to the right. Electrodes are then
  1164. numbered from bottom left to top right:
  1165. 91 92 ... 99 100 \
  1166. 81 82 ... 89 90 \
  1167. ... ... --- Connector Wires
  1168. 11 12 ... 19 20 /
  1169. 1 2 ... 9 10 /
  1170. electrode_reject_XXX (bool):
  1171. For different filter ranges XXX (as defined in the odML
  1172. file), if this variable is True it indicates whether
  1173. the spikes were recorded on an electrode that should be
  1174. rejected based on preprocessing analysis for removing
  1175. electrodes due to noise/artefacts in the respective
  1176. frequency range.
  1177. noise, mua, sua (bool):
  1178. True, if the unit is classified as a noise unit, i.e.,
  1179. not considered neural activity (noise), a multi-unit
  1180. (mua), or a single unit (sua).
  1181. SNR (float):
  1182. Signal to noise ratio of SUA/MUA waveforms. A higher
  1183. value indicates that the unit could be better
  1184. distinguished in the spike detection and spike sorting
  1185. procedure.
  1186. spike_duration (float):
  1187. Approximate duration of the spikes of SUAs/MUAs in
  1188. microseconds.
  1189. spike_amplitude (float):
  1190. Maximum amplitude of the spike waveform.
  1191. spike_count (int):
  1192. Number of spikes sorted into this unit.
  1193. AnalogSignal annotations:
  1194. nsx (int):
  1195. nsX file the signal was loaded from, e.g., 5 indicates
  1196. the .ns5 file.
  1197. channel_id (int):
  1198. Channel ID (Blackrock ID) from which the signal was
  1199. loaded.
  1200. connector_aligned_id (int):
  1201. Connector-aligned channel ID from which the signal was
  1202. loaded. This is a channel ID between 1 and 100 that is
  1203. related to the location of an electrode on the Utah
  1204. array and thus common across different arrays
  1205. (independent of the Blackrock channel ID). The ID
  1206. considers a top-view of the array with the connector
  1207. wires extruding to the right. Electrodes are then
  1208. numbered from bottom left to top right:
  1209. 91 92 ... 99 100 \
  1210. 81 82 ... 89 90 \
  1211. ... ... --- Connector Wires
  1212. 11 12 ... 19 20 /
  1213. 1 2 ... 9 10 /
  1214. electrode_reject_XXX (bool):
  1215. For different filter ranges XXX (as defined in the odML
  1216. file), if this variable is True it indicates whether
  1217. the spikes were recorded on an electrode that should be
  1218. rejected based on preprocessing analysis for removing
  1219. electrodes due to noise/artefacts in the respective
  1220. frequency range.
  1221. filter_shift_correction (Quantity):
  1222. If the parameter correct_filter_shift is True, and a
  1223. shift estimate was found in the odML, this annotation
  1224. indicates the amount of time by which the signal was
  1225. shifted. I.e., adding this number to t_start will
  1226. result in the uncorrected, originally recorded time
  1227. axis.
  1228. Spiketrain annotations:
  1229. unit_id (int):
  1230. ID of the unit from which the spikes were recorded.
  1231. channel_id (int):
  1232. Channel ID (Blackrock ID) from which the spikes were
  1233. loaded.
  1234. connector_aligned_id (int):
  1235. Connector-aligned channel ID from which the spikes were
  1236. loaded. This is a channel ID between 1 and 100 that is
  1237. related to the location of an electrode on the Utah
  1238. array and thus common across different arrays
  1239. (independent of the Blackrock channel ID). The ID
  1240. considers a top-view of the array with the connector
  1241. wires extruding to the right. Electrodes are then
  1242. numbered from bottom left to top right:
  1243. 91 92 ... 99 100 \
  1244. 81 82 ... 89 90 \
  1245. ... ... --- Connector Wires
  1246. 11 12 ... 19 20 /
  1247. 1 2 ... 9 10 /
  1248. electrode_reject_XXX (bool):
  1249. For different filter ranges XXX (as defined in the odML
  1250. file), if this variable is True it indicates whether
  1251. the spikes were recorded on an electrode that should be
  1252. rejected based on preprocessing analysis for removing
  1253. electrodes due to noise/artefacts in the respective
  1254. frequency range.
  1255. noise, mua, sua (bool):
  1256. True, if the unit is classified as a noise unit, i.e.,
  1257. not considered neural activity (noise), a multi-unit
  1258. (mua), or a single unit (sua).
  1259. SNR (float):
  1260. Signal to noise ratio of SUA/MUA waveforms. A higher
  1261. value indicates that the unit could be better
  1262. distinguished in the spike detection and spike sorting
  1263. procedure.
  1264. spike_duration (float):
  1265. Approximate duration of the spikes of SUAs/MUAs in
  1266. microseconds.
  1267. spike_amplitude (float):
  1268. Maximum amplitude of the spike waveform.
  1269. spike_count (int):
  1270. Number of spikes sorted into this unit.
  1271. Event annotations:
  1272. The resulting Block contains three Event objects with the
  1273. following names:
  1274. "DigitalTrialEvents' contains all digitally recorded events
  1275. returned by BlackrockIO, annotated with semantic labels
  1276. in accordance with the reach-to-grasp experiment (e.g.,
  1277. 'TS-ON').
  1278. 'AnalogTrialEvents' contains events extracted from the
  1279. analog behavioral signals during preprocessing and
  1280. stored in the odML (e.g., 'OT').
  1281. 'TrialEvents' contains all events of DigitalTrialEvents and
  1282. AnalogTrialEvents merged into a single Neo object.
  1283. Each annotation is a list containing one entry per time
  1284. point stored in the event.
  1285. trial_event_labels (list of str):
  1286. Name identifying the name of the event, e.g., 'TS-ON'.
  1287. trial_id (list of int):
  1288. Trial ID the event belongs to.
  1289. trial_timestamp_id (list of int):
  1290. Timestamp-based trial ID (equivalent to the time of TS-
  1291. ON of a trial) the event belongs to.
  1292. belongs_to_trialtype (str):
  1293. String identifying the trial type (e.g., SGHF) the
  1294. trial belongs to.
  1295. performance_in_trial (list of int):
  1296. Performance code of the trial that the event belongs
  1297. to. Compare to the performance_codes and
  1298. performance_str attributes of ReachGraspIO class.
  1299. trial_reject_XXX:
  1300. For different filter ranges XXX (defined in the odML
  1301. file), if True this variable indicates whether the
  1302. trial was rejected based on preprocessing analysis.
  1303. """
  1304. if not name:
  1305. name = 'Reachgrasp Recording Data Block'
  1306. if not description:
  1307. description = \
  1308. "Block of reach-to-grasp project data from Blackrock file set."
  1309. # Load neo block
  1310. bl = BlackrockIO.read_block(
  1311. self, index=index, name=name, description=description,
  1312. nsx_to_load=nsx_to_load, n_starts=n_starts, n_stops=n_stops,
  1313. channels=channels, units=units, load_waveforms=load_waveforms,
  1314. load_events=load_events, scaling=scaling, lazy=lazy,
  1315. cascade=cascade)
  1316. bl.annotate(conditions=[])
  1317. for seg in bl.segments:
  1318. if load_events and not lazy:
  1319. if 'condition' in list(seg.annotations):
  1320. bl.annotations['conditions'].append(
  1321. seg.annotations['condition'])
  1322. if self.odmldoc:
  1323. self.__annotate_block_with_odml(bl)
  1324. for chidx in bl.channel_indexes:
  1325. self.__annotate_channelindex_with_odml(chidx)
  1326. self.__annotate_units_with_odml(chidx.units)
  1327. for chidx in bl.channel_indexes:
  1328. if isinstance(chidx.index, int):
  1329. chidx.index = [chidx.index]
  1330. return bl
  1331. def read_segment(
  1332. self, n_start, n_stop, name=None, description=None, index=None,
  1333. nsx_to_load='none', channels=range(1, 97), units='none',
  1334. load_waveforms=False, load_events=False, scaling='raw',
  1335. correct_filter_shifts=True, lazy=False, cascade=True):
  1336. """
  1337. Reads file contents as a Neo Block.
  1338. The Block contains one Segment for each entry in zip(n_starts,
  1339. n_stops). If these parameters are not specified, the default is
  1340. to store all data in one Segment.
  1341. The Block contains one ChannelIndex per channel.
  1342. Args:
  1343. n_start (Quantity):
  1344. Start time of maximum time range of signals contained in this
  1345. segment.
  1346. n_stop (Quantity):
  1347. Stop time of maximum time range of signals contained in this
  1348. segment.
  1349. name (None, string):
  1350. If None, name is set to default, otherwise it is set to user
  1351. input.
  1352. description (None, string):
  1353. If None, description is set to default, otherwise it is set to
  1354. user input.
  1355. index (None, int):
  1356. If not None, index of segment is set to user index.
  1357. nsx_to_load (int, list, str):
  1358. ID(s) of nsx file(s) from which to load data, e.g., if set to
  1359. 5 only data from the ns5 file are loaded. If 'none' or empty
  1360. list, no nsx files and therefore no analog signals are loaded.
  1361. If 'all', data from all available nsx are loaded.
  1362. channels (int, list, str):
  1363. Channel id(s) from which to load data. If 'none' or empty list,
  1364. no channels and therefore no analog signal or spiketrains are
  1365. loaded. If 'all', all available channels are loaded. By
  1366. default, all neural channels (1-96) are loaded.
  1367. units (int, list, str, dict):
  1368. ID(s) of unit(s) to load. If 'none' or empty list, no units and
  1369. therefore no spiketrains are loaded. If 'all', all available
  1370. units are loaded. If dict, the above can be specified
  1371. individually for each channel (keys), e.g. {1: 5, 2: 'all'}
  1372. loads unit 5 from channel 1 and all units from channel 2.
  1373. load_waveforms (boolean):
  1374. If True, waveforms are attached to all loaded spiketrains.
  1375. load_events (boolean):
  1376. If True, all recorded events are loaded.
  1377. scaling (str):
  1378. Determines whether time series of individual
  1379. electrodes/channels are returned as AnalogSignals containing
  1380. raw integer samples ('raw'), or scaled to arrays of floats
  1381. representing voltage ('voltage'). Note that for file
  1382. specification 2.1 and lower, the option 'voltage' requires a
  1383. nev file to be present.
  1384. correct_filter_shifts (bool):
  1385. If True, shifts of the online-filtered neural signals (e.g.,
  1386. ns2, channels 1-128) are corrected by time-shifting the signal
  1387. by a heuristically determined estimate stored in the metadata,
  1388. in the property EstimatedShift, under the path
  1389. /Cerebus/NeuralSignalProcessor/NeuralSignals/Filter_nsX/
  1390. lazy (boolean):
  1391. If True, only the shape of the data is loaded.
  1392. cascade (boolean):
  1393. If True, only the segment without children is returned.
  1394. Returns:
  1395. Segment (neo.segment.Segment):
  1396. Segment linking to all loaded Neo objects. See documentation of
  1397. read_block() for a full list of annotations per Neo object.
  1398. """
  1399. # Load neo block
  1400. seg = BlackrockIO.read_segment(
  1401. self, n_start, n_stop, name=name, description=description,
  1402. index=index, nsx_to_load=nsx_to_load, channels=channels,
  1403. units=units, load_waveforms=load_waveforms,
  1404. load_events=load_events, scaling=scaling, lazy=lazy,
  1405. cascade=cascade)
  1406. for asig in seg.analogsignals:
  1407. asig.name = str(asig.name)
  1408. self.__annotate_analogsignals_with_odml(asig)
  1409. if correct_filter_shifts:
  1410. self.__correct_filter_shifts(asig)
  1411. if load_events and not lazy:
  1412. for ev in seg.events:
  1413. # Modify digital trial events to include semantic event
  1414. # informations
  1415. if ev.name == 'digital_input_port':
  1416. self.__annotate_dig_trial_events(ev)
  1417. self.__add_rejection_to_event(ev)
  1418. cnd = self.__extract_task_condition(
  1419. ev.array_annotations['belongs_to_trialtype'])
  1420. seg.annotate(condition=cnd)
  1421. # If digital trial events exist, extract analog events from odML
  1422. # and create one common event array
  1423. if len(seg.events) > 0 and self.odmldoc:
  1424. analog_event = self.__extract_analog_events_from_odml(
  1425. seg.t_start, seg.t_stop)
  1426. self.__add_rejection_to_event(analog_event)
  1427. seg.events.append(analog_event)
  1428. merged_event = self.__merge_digital_analog_events(
  1429. seg.events)
  1430. self.__add_rejection_to_event(merged_event)
  1431. seg.events.append(merged_event)
  1432. return seg
  1433. if __name__ == '__main__':
  1434. pass