reachgraspio.py 78 KB

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