reachgraspio.py 80 KB

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