1
1

reachgraspio.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  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. warnings.warn(
  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. # skip invalid values
  492. if analog_events.values == [-1]: # this was used as default time
  493. continue
  494. time = analog_events.values * pq.CompoundUnit(analog_events.unit)
  495. time = time.rescale('ms')
  496. if time >= t_start and time < t_stop:
  497. event_name.append(analog_events.name)
  498. event_time.append(time)
  499. trial_id.extend(trial_sec.properties['TrialID'].values)
  500. trial_timestamp_id.extend(trial_sec.properties['TrialTimestampID'].values)
  501. performance_code.extend(trial_sec.properties['PerformanceCode'].values)
  502. trial_type.extend(trial_sec.properties['TrialType'].values)
  503. # Create event object with analog events
  504. analog_events = neo.Event(
  505. times=pq.Quantity(event_time, '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. events_rescaled = events.rescale(pq.CompoundUnit('1/30000*s'))
  532. # Extract beginning of first complete trial
  533. tson_label = self.event_labels_codes['TS-ON'][0]
  534. if tson_label in events_rescaled.labels:
  535. first_TSon_idx = list(events_rescaled.labels).index(tson_label)
  536. else:
  537. first_TSon_idx = len(events_rescaled.labels)
  538. # Extract end of last complete trial
  539. stop_label = self.event_labels_codes['STOP'][0]
  540. if stop_label in events_rescaled.labels:
  541. last_WSoff_idx = len(events_rescaled.labels) - list(events_rescaled.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_rescaled.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_rescaled.labels[i - 1]
  560. if self.event_labels_str[prev_ev] in ['STOP', 'TS-OFF/STOP']:
  561. timestamp_id = int(round(events_rescaled.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_rescaled.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['TrialTimestampID'].values[0] == timestamp_id:
  584. ID = trial_sec.properties['TrialID'].values[0]
  585. trial_ID.append(ID)
  586. # interpretation of GO/RW-OFF
  587. elif self.event_labels_str[l] == 'GO/RW-OFF':
  588. trial_timestamp_ID.append(timestamp_id)
  589. trial_ID.append(ID)
  590. trial_event_labels.append('GO/RW-OFF')
  591. # interpretation of ERROR-FLASH-ON
  592. elif l in self.event_labels_codes['ERROR-FLASH-ON']:
  593. trial_timestamp_ID.append(timestamp_id)
  594. trial_ID.append(ID)
  595. trial_event_labels.append('ERROR-FLASH-ON')
  596. # Error-Flash hides too early activation of SR
  597. # SR is set to 1 here to match perf codes between monkeys
  598. trialsequence[timestamp_id] = self.__set_bit(
  599. trialsequence[timestamp_id],
  600. self.trial_const_sequence_codes['SR'])
  601. # TS-OFF/STOP
  602. elif self.event_labels_str[l] == 'TS-OFF/STOP':
  603. trial_timestamp_ID.append(timestamp_id)
  604. trial_ID.append(ID)
  605. prev_ev = events_rescaled.labels[i - 1]
  606. if self.event_labels_str[prev_ev] == 'TS-ON':
  607. trial_event_labels.append('TS-OFF')
  608. elif prev_ev in self.event_labels_codes['ERROR-FLASH-ON']:
  609. trial_event_labels.append('STOP')
  610. trialsequence[timestamp_id] = self.__set_bit(
  611. trialsequence[timestamp_id],
  612. self.trial_const_sequence_codes['STOP'])
  613. else:
  614. trial_event_labels.append('STOP')
  615. trialsequence[timestamp_id] = self.__set_bit(
  616. trialsequence[timestamp_id],
  617. self.trial_const_sequence_codes['STOP'])
  618. # interpretation of WS-ON/CUE-OFF
  619. elif self.event_labels_str[l] == 'WS-ON/CUE-OFF':
  620. trial_timestamp_ID.append(timestamp_id)
  621. trial_ID.append(ID)
  622. prev_ev = events_rescaled.labels[i - 1]
  623. if self.event_labels_str[prev_ev] in ['TS-ON', 'TS-OFF/STOP']:
  624. trial_event_labels.append('WS-ON')
  625. trialsequence[timestamp_id] = self.__set_bit(
  626. trialsequence[timestamp_id],
  627. self.trial_const_sequence_codes['WS-ON'])
  628. elif (prev_ev in self.event_labels_codes['CUE/GO'] or
  629. prev_ev in self.event_labels_codes['GO/RW-OFF']):
  630. trial_event_labels.append('CUE-OFF')
  631. trialsequence[timestamp_id] = self.__set_bit(
  632. trialsequence[timestamp_id],
  633. self.trial_const_sequence_codes['CUE-OFF'])
  634. else:
  635. raise ValueError("Unknown trial event sequence.")
  636. # interpretation of CUE and GO events and trialtype detection
  637. elif l in self.event_labels_codes['CUE/GO']:
  638. trial_timestamp_ID.append(timestamp_id)
  639. trial_ID.append(ID)
  640. prprev_ev = events_rescaled.labels[i - 2]
  641. if self.event_labels_str[prprev_ev] in ['TS-ON', 'TS-OFF/STOP']:
  642. trial_event_labels.append('CUE-ON')
  643. trialsequence[timestamp_id] = self.__set_bit(
  644. trialsequence[timestamp_id],
  645. self.trial_const_sequence_codes['CUE-ON'])
  646. trialtypes[timestamp_id] = self.event_labels_str[l][:2]
  647. elif prprev_ev in self.event_labels_codes['CUE/GO']:
  648. trial_event_labels.append('GO-ON')
  649. trialsequence[timestamp_id] = self.__set_bit(
  650. trialsequence[timestamp_id],
  651. self.trial_const_sequence_codes['GO-ON'])
  652. trialtypes[timestamp_id] += self.event_labels_str[l][:2]
  653. else:
  654. raise ValueError("Unknown trial event sequence.")
  655. # interpretation of WS-OFF
  656. elif self.event_labels_str[l] == 'STOP':
  657. trial_timestamp_ID.append(timestamp_id)
  658. trial_ID.append(ID)
  659. prev_ev = self.event_labels_str[events_rescaled.labels[i - 1]]
  660. if prev_ev == 'ERROR-FLASH-ON':
  661. trial_event_labels.append('ERROR-FLASH-OFF')
  662. else:
  663. trial_event_labels.append('STOP')
  664. trialsequence[timestamp_id] = self.__set_bit(
  665. trialsequence[timestamp_id],
  666. self.trial_const_sequence_codes['STOP'])
  667. # interpretation of SR events
  668. elif l in self.event_labels_codes['SR']:
  669. trial_timestamp_ID.append(timestamp_id)
  670. trial_ID.append(ID)
  671. prev_ev = events_rescaled.labels[i - 1]
  672. if prev_ev in self.event_labels_codes['SR']:
  673. trial_event_labels.append('SR-REP')
  674. elif prev_ev in self.event_labels_codes['RW-ON']:
  675. trial_event_labels.append('RW-OFF')
  676. else:
  677. trial_event_labels.append('SR')
  678. trialsequence[timestamp_id] = self.__set_bit(
  679. trialsequence[timestamp_id],
  680. self.trial_const_sequence_codes['SR'])
  681. # interpretation of RW events_rescaled
  682. elif l in self.event_labels_codes['RW-ON']:
  683. trial_timestamp_ID.append(timestamp_id)
  684. trial_ID.append(ID)
  685. prev_ev = events_rescaled.labels[i - 1]
  686. if prev_ev in self.event_labels_codes['RW-ON']:
  687. trial_event_labels.append('RW-ON-REP')
  688. else:
  689. trial_event_labels.append('RW-ON')
  690. trialsequence[timestamp_id] = self.__set_bit(
  691. trialsequence[timestamp_id],
  692. self.trial_const_sequence_codes['RW-ON'])
  693. else:
  694. raise ValueError("Unknown event label.")
  695. # add modified trial_event_labels to annotations
  696. events.array_annotate(trial_event_labels=trial_event_labels)
  697. # add trial timestamp IDs
  698. events.array_annotate(trial_timestamp_id=trial_timestamp_ID)
  699. # add trial IDs
  700. events.array_annotate(trial_id=trial_ID)
  701. # add modified belongs_to_trialtype to annotations
  702. for tid in trial_timestamp_ID:
  703. if tid not in list(trialtypes):
  704. trialtypes[tid] = 'NONE'
  705. belongs_to_trialtype = [trialtypes[tid] for tid in trial_timestamp_ID]
  706. events.array_annotate(belongs_to_trialtype=belongs_to_trialtype)
  707. # add modified trial_performance_codes to annotations
  708. performance_in_trial = [trialsequence[tid] for tid in trial_timestamp_ID]
  709. performance_in_trial_str = []
  710. for pit in performance_in_trial:
  711. if pit in self.performance_str:
  712. performance_in_trial_str.append(self.performance_str[pit])
  713. else:
  714. performance_in_trial_str.append('unknown')
  715. events.array_annotate(performance_in_trial=performance_in_trial)
  716. events.array_annotate(performance_in_trial_str=performance_in_trial_str)
  717. def __create_unit_groups(self, block, view_dict=None):
  718. unit_dict = {}
  719. for seg in block.segments:
  720. for st in seg.spiketrains:
  721. chid = st.annotations['channel_id']
  722. unit_id = st.annotations['unit_id']
  723. if chid not in unit_dict:
  724. unit_dict[chid] = {}
  725. if unit_id not in unit_dict[chid]:
  726. group = neo.Group(name='Unit {} on channel {}'.format(unit_id, chid),
  727. description='Group for neuronal data related to unit {} on '
  728. 'channel {}'.format(unit_id, chid),
  729. group_type='unit',
  730. allowed_types=[neo.SpikeTrain, SpikeTrainProxy,
  731. neo.AnalogSignal, AnalogSignalProxy,
  732. neo.ChannelView],
  733. channel_id=chid,
  734. unit_id=unit_id)
  735. block.groups.append(group)
  736. unit_dict[chid][unit_id] = group
  737. unit_dict[chid][unit_id].add(st)
  738. # if views are already created, link them to unit groups
  739. if view_dict:
  740. for chid, channel_dict in unit_dict.items():
  741. if chid in view_dict:
  742. for unit_id, group in channel_dict.items():
  743. group.add(view_dict[chid])
  744. def __create_channel_views(self, block):
  745. view_dict = {}
  746. for seg in block.segments:
  747. for anasig in seg.analogsignals:
  748. for chidx, chid in enumerate(anasig.array_annotations['channel_ids']):
  749. if chid not in view_dict:
  750. view = neo.ChannelView(anasig, [chidx],
  751. name='Channel {} of {}'.format(chid, anasig.name),
  752. channel_id=chid)
  753. view_dict[chid] = view
  754. return view_dict
  755. def __annotate_units_with_odml(self, groups):
  756. """
  757. Annotates units with metadata from odml file.
  758. """
  759. units = [g for g in groups if
  760. 'group_type' in g.annotations and g.annotations['group_type'] == 'unit']
  761. if not self._load_spikesorting_info:
  762. return
  763. for un in units:
  764. an_dict = dict(
  765. sua=False,
  766. mua=False,
  767. noise=False)
  768. try:
  769. sec = self.odmldoc['UtahArray']['Array'][
  770. 'Electrode_%03d' % un.annotations['channel_id']][
  771. 'OfflineSpikeSorting']
  772. except KeyError:
  773. return
  774. suaids = sec.properties['SUAIDs'].values
  775. muaid = sec.properties['MUAID'].values[0]
  776. noiseids = sec.properties['NoiseIDs'].values
  777. if un.annotations['unit_id'] in suaids:
  778. an_dict['sua'] = True
  779. elif un.annotations['unit_id'] in noiseids:
  780. an_dict['noise'] = True
  781. elif un.annotations['unit_id'] == muaid:
  782. an_dict['mua'] = True
  783. else:
  784. raise ValueError(
  785. "Unit %i is not registered for channel %i in odML file."
  786. % (un.annotations['unit_id'],
  787. un.annotations['channel_id']))
  788. if ('Unit_%02i' % un.annotations['unit_id']) in sec.sections:
  789. unit_sec = sec['Unit_%02i' % un.annotations['unit_id']]
  790. if an_dict['sua']:
  791. an_dict['SNR'] = unit_sec.properties['SNR'].values[0]
  792. # TODO: Add units here
  793. an_dict['spike_duration'] = unit_sec.properties['SpikeDuration'].values[0]
  794. an_dict['spike_amplitude'] = unit_sec.properties['SpikeAmplitude'].values[0]
  795. an_dict['spike_count'] = unit_sec.properties['SpikeCount'].values[0]
  796. # Annotate Unit and all children for convenience
  797. un.annotate(**an_dict)
  798. for st in un.spiketrains:
  799. st.annotate(**an_dict)
  800. def __annotate_analogsignals_with_odml(self, asig):
  801. """
  802. Annotates analogsignals with metadata from odml file.
  803. """
  804. if self.odmldoc:
  805. chids = asig.array_annotations['channel_ids']
  806. neural_chids = [chid in self.avail_electrode_ids for chid in chids]
  807. if not any(neural_chids):
  808. asig.annotate(neural_signal=False)
  809. elif all(neural_chids):
  810. asig.annotate(neural_signal=True)
  811. # Annotate filter settings from odML
  812. nchan = asig.shape[-1]
  813. filter = 'Filter_ns%i' % asig.array_annotations['nsx'][0]
  814. sec = self.odmldoc['Cerebus']['NeuralSignalProcessor']['NeuralSignals'][filter]
  815. props = sec.properties
  816. hi_pass_freq = np.full((nchan), pq.Quantity(props['HighPassFreq'].values[0],
  817. props['HighPassFreq'].unit))
  818. lo_pass_freq = np.full((nchan), pq.Quantity(props['LowPassFreq'].values[0],
  819. props['LowPassFreq'].unit))
  820. hi_pass_order = np.zeros_like(hi_pass_freq)
  821. lo_pass_order = np.zeros_like(lo_pass_freq)
  822. filter_type = np.empty((nchan), np.str)
  823. for chidx in range(nchan):
  824. filter = 'Filter_ns%i' % asig.array_annotations['nsx'][chidx]
  825. sec = self.odmldoc['Cerebus']['NeuralSignalProcessor']['NeuralSignals'][filter]
  826. hi_pass_freq[chidx] = pq.Quantity(
  827. sec.properties['HighPassFreq'].values[0],
  828. sec.properties['HighPassFreq'].unit)
  829. lo_pass_freq[chidx] = pq.Quantity(
  830. sec.properties['LowPassFreq'].values[0],
  831. sec.properties['LowPassFreq'].unit)
  832. hi_pass_order[chidx] = sec.properties['HighPassOrder'].values[0]
  833. lo_pass_order[chidx] = sec.properties['LowPassOrder'].values[0]
  834. filter_type[chidx] = sec.properties['Type'].values[0]
  835. asig.array_annotations.update(dict(
  836. hi_pass_freq=hi_pass_freq,
  837. lo_pass_freq=lo_pass_freq,
  838. hi_pass_order=hi_pass_order,
  839. lo_pass_order=lo_pass_order,
  840. filter_type=filter_type
  841. ))
  842. self.__annotate_electrode_rejections(asig)
  843. def __annotate_electrode_rejections(self, obj):
  844. # Get rejection bands
  845. sec = self.odmldoc['PreProcessing']
  846. bands = sec.properties['LFPBands'].values
  847. if hasattr(bands, '__iter__'):
  848. for band in bands:
  849. sec = self.odmldoc['PreProcessing'][band]
  850. rej_els = np.asarray(sec.properties['RejElectrodes'].values, dtype=int)
  851. if 'channel_id' in obj.annotations:
  852. rejection_value = bool(obj.annotations['channel_id'] in rej_els)
  853. obj.annotations['electrode_reject_' + band] = rejection_value
  854. elif hasattr(obj, 'array_annotations') and 'channel_ids' in obj.array_annotations:
  855. rej = np.isin(obj.array_annotations['channel_ids'], rej_els)
  856. obj.array_annotations.update({str('electrode_reject_' + band): rej})
  857. else:
  858. warnings.warn(
  859. 'Could not annotate {} with electrode rejection information.'.format(obj))
  860. def __convert_chids_and_coordinates(self, channel_ids):
  861. nchan = len(channel_ids)
  862. ca_ids = np.full(nchan, fill_value=None)
  863. # use negative infinity for invalid coordinates as None is incompatible with pq.mm
  864. coordinates_x = np.full(nchan, fill_value=-np.inf) * pq.mm
  865. coordinates_y = np.full(nchan, fill_value=-np.inf) * pq.mm
  866. for i, channel_id in enumerate(channel_ids):
  867. if channel_id not in self.connector_aligned_map:
  868. continue
  869. ca_ids[i] = self.connector_aligned_map[channel_id]
  870. coordinates_x[i] = np.mod(ca_ids[i] - 1, 10) * 0.4 * pq.mm
  871. coordinates_y[i] = int((ca_ids[i] - 1) / 10) * 0.4 * pq.mm
  872. return ca_ids, coordinates_x, coordinates_y
  873. def __annotate_channel_infos(self, block):
  874. if self.odmldoc:
  875. # updating array annotations of neuronal analogsignals
  876. for seg in block.segments:
  877. for obj in seg.analogsignals:
  878. if 'neural_signal' in obj.annotations and obj.annotations[
  879. 'neural_signal'] and 'channel_ids' in obj.array_annotations:
  880. chids = obj.array_annotations['channel_ids']
  881. ca_ids, *coordinates = self.__convert_chids_and_coordinates(chids)
  882. obj.array_annotations.update(dict(connector_aligned_ids=ca_ids,
  883. coordinates_x=coordinates[0],
  884. coordinates_y=coordinates[1]))
  885. # updating annotations of groups and spiketrains
  886. sts = []
  887. for seg in block.segments:
  888. sts.extend(seg.spiketrains)
  889. for obj in sts + block.groups:
  890. if 'channel_id' in obj.annotations:
  891. chid = obj.annotations['channel_id']
  892. ca_id, *coordinates = self.__convert_chids_and_coordinates([chid])
  893. obj.annotate(connector_aligned_id=ca_id[0],
  894. coordinate_x=coordinates[0][0],
  895. coordinate_y=coordinates[1][0])
  896. def __annotate_block_with_odml(self, bl):
  897. """
  898. Annotates block with metadata from odml file.
  899. """
  900. sec = self.odmldoc['Project']
  901. bl.annotate(
  902. project_name=sec.properties['Name'].values,
  903. project_type=sec.properties['Type'].values,
  904. project_subtype=sec.properties['Subtype'].values)
  905. sec = self.odmldoc['Project']['TaskDesigns']
  906. bl.annotate(taskdesigns=[v for v in sec.properties['UsedDesign'].values])
  907. sec = self.odmldoc['Subject']
  908. bl.annotate(
  909. subject_name=sec.properties['GivenName'].values,
  910. subject_gender=sec.properties['Gender'].values,
  911. subject_activehand=sec.properties['ActiveHand'].values,
  912. subject_birthday=str(
  913. sec.properties['Birthday'].values)) # datetime is not a valid annotation dtype
  914. sec = self.odmldoc['Setup']
  915. bl.annotate(setup_location=sec.properties['Location'].values)
  916. sec = self.odmldoc['UtahArray']
  917. bl.annotate(array_serialnum=sec.properties['SerialNo'].values)
  918. sec = self.odmldoc['UtahArray']['Connector']
  919. bl.annotate(connector_type=sec.properties['Style'].values)
  920. sec = self.odmldoc['UtahArray']['Array']
  921. bl.annotate(arraygrids_tot_num=sec.properties['GridCount'].values)
  922. sec = self.odmldoc['UtahArray']['Array']['Grid_01']
  923. bl.annotate(
  924. electrodes_tot_num=sec.properties['ElectrodeCount'].values,
  925. electrodes_pitch=pq.Quantity(
  926. sec.properties['ElectrodePitch'].values,
  927. units=sec.properties['ElectrodePitch'].unit),
  928. arraygrid_row_num=sec.properties['GridRows'].values,
  929. arraygrid_col_num=sec.properties['GridColumns'].values)
  930. secs = self.odmldoc['UtahArray']['Array'].sections
  931. bl.annotate(avail_electrode_ids=self.avail_electrode_ids)
  932. # TODO: add list of behavioral channels
  933. # bl.annotate(avail_behavsig_indexes=[])
  934. def __correct_filter_shifts(self, asig):
  935. if self.odmldoc and asig.annotations['neural_signal']:
  936. # assert all signals are originating from same nsx file
  937. if len(np.unique(asig.array_annotations['nsx'])) > 1:
  938. raise ValueError('Multiple nsx file origins (%s) in single AnalogSignal'
  939. ''.format(asig.array_annotations['nsx']))
  940. # Get and correct for shifts
  941. filter_name = 'Filter_ns%i' % asig.array_annotations['nsx'][0] # use nsx of 1st signal
  942. sec = self.odmldoc['Cerebus']['NeuralSignalProcessor']['NeuralSignals'][filter_name]
  943. shift = pq.Quantity(
  944. sec.properties['EstimatedShift'].values[0],
  945. sec.properties['EstimatedShift'].unit)
  946. asig.t_start = asig.t_start - shift
  947. # Annotate shift
  948. asig.annotate(filter_shift_correction=shift)
  949. def __merge_digital_analog_events(self, events):
  950. """
  951. Merge the two event arrays AnalogTrialEvents and DigitalTrialEvents
  952. into one common event array TrialEvents.
  953. """
  954. event_name = []
  955. event_time = None
  956. trial_id = []
  957. trial_timestamp_id = []
  958. performance_code = []
  959. performance_str = []
  960. trial_type = []
  961. for event in events:
  962. if event.name in ['AnalogTrialEvents', 'DigitalTrialEvents']:
  963. # Extract event times
  964. if event_time is None:
  965. event_time = event.times.magnitude.flatten()
  966. event_units = event.times.units
  967. else:
  968. event_time = np.concatenate((
  969. event_time,
  970. event.times.rescale(event_units).magnitude.flatten()))
  971. # Transfer annotations
  972. trial_id.extend(
  973. event.array_annotations['trial_id'])
  974. trial_timestamp_id.extend(
  975. event.array_annotations['trial_timestamp_id'])
  976. performance_code.extend(
  977. event.array_annotations['performance_in_trial'])
  978. performance_str.extend(
  979. event.array_annotations['performance_in_trial_str'])
  980. trial_type.extend(
  981. event.array_annotations['belongs_to_trialtype'])
  982. event_name.extend(
  983. event.array_annotations['trial_event_labels'])
  984. # Sort time stamps and save sort order
  985. sort_idx = np.argsort(event_time)
  986. event_time = event_time[sort_idx]
  987. # Create event object with analog events
  988. merged_event = neo.Event(
  989. times=pq.Quantity(event_time, units=event_units),
  990. labels=np.array([event_name[_] for _ in sort_idx]),
  991. name='TrialEvents',
  992. description='All trial events (digital and analog)')
  993. merged_event.array_annotate(
  994. trial_id=[trial_id[_] for _ in sort_idx],
  995. trial_timestamp_id=[trial_timestamp_id[_] for _ in sort_idx],
  996. performance_in_trial=[performance_code[_] for _ in sort_idx],
  997. performance_in_trial_str=[performance_str[_] for _ in sort_idx],
  998. belongs_to_trialtype=[trial_type[_] for _ in sort_idx],
  999. trial_event_labels=[event_name[_] for _ in sort_idx])
  1000. return merged_event
  1001. def read_block(
  1002. self, index=None, block_index=0, name=None, description=None, nsx_to_load='none',
  1003. n_starts=None, n_stops=None, channels=range(1, 97), units='none',
  1004. load_waveforms=False, load_events=False, scaling='raw',
  1005. correct_filter_shifts=True, lazy=False, cascade=True, **kwargs):
  1006. """
  1007. Reads file contents as a Neo Block.
  1008. The Block contains one Segment for each entry in zip(n_starts,
  1009. n_stops). If these parameters are not specified, the default is
  1010. to store all data in one Segment.
  1011. The Block contains one ChannelIndex per channel.
  1012. Args:
  1013. index (None, int): DEPRECATED
  1014. If not None, index of block is set to user input.
  1015. block_index (int):
  1016. Index of block to load.
  1017. name (None, str):
  1018. If None, name is set to default, otherwise it is set to user
  1019. input.
  1020. description (None, str):
  1021. If None, description is set to default, otherwise it is set to
  1022. user input.
  1023. nsx_to_load (int, list, str): DEPRECATED
  1024. ID(s) of nsx file(s) from which to load data, e.g., if set to
  1025. 5 only data from the ns5 file are loaded. If 'none' or empty
  1026. list, no nsx files and therefore no analog signals are loaded.
  1027. If 'all', data from all available nsx are loaded.
  1028. n_starts (None, Quantity, list): DEPRECATED
  1029. Start times for data in each segment. Number of entries must be
  1030. equal to length of n_stops. If None, intrinsic recording start
  1031. times of files set are used.
  1032. n_stops (None, Quantity, list): DEPRECATED
  1033. Stop times for data in each segment. Number of entries must be
  1034. equal to length of n_starts. If None, intrinsic recording stop
  1035. times of files set are used.
  1036. channels (int, list, str): DEPRECATED
  1037. Channel id(s) from which to load data. If 'none' or empty list,
  1038. no channels and therefore no analog signal or spiketrains are
  1039. loaded. If 'all', all available channels are loaded. By
  1040. default, all neural channels (1-96) are loaded.
  1041. units (int, list, str, dict): DEPRECATED
  1042. ID(s) of unit(s) to load. If 'none' or empty list, no units and
  1043. therefore no spiketrains are loaded. If 'all', all available
  1044. units are loaded. If dict, the above can be specified
  1045. individually for each channel (keys), e.g. {1: 5, 2: 'all'}
  1046. loads unit 5 from channel 1 and all units from channel 2.
  1047. load_waveforms (boolean):
  1048. Control SpikeTrains.waveforms is None or not.
  1049. Default: False
  1050. load_events (boolean): DEPRECATED
  1051. If True, all recorded events are loaded.
  1052. scaling (str): DEPRECATED
  1053. Determines whether time series of individual
  1054. electrodes/channels are returned as AnalogSignals containing
  1055. raw integer samples ('raw'), or scaled to arrays of floats
  1056. representing voltage ('voltage'). Note that for file
  1057. specification 2.1 and lower, the option 'voltage' requires a
  1058. nev file to be present.
  1059. correct_filter_shifts (bool):
  1060. If True, shifts of the online-filtered neural signals (e.g.,
  1061. ns2, channels 1-128) are corrected by time-shifting the signal
  1062. by a heuristically determined estimate stored in the metadata,
  1063. in the property EstimatedShift, under the path
  1064. /Cerebus/NeuralSignalProcessor/NeuralSignals/Filter_nsX/
  1065. lazy (bool):
  1066. If True, only the shape of the data is loaded.
  1067. cascade (bool or "lazy"): DEPRECATED
  1068. If True, only the block without children is returned.
  1069. kwargs:
  1070. Additional keyword arguments are forwarded to the BlackrockIO.
  1071. Returns:
  1072. Block (neo.segment.Block):
  1073. Block linking to all loaded Neo objects.
  1074. Block annotations:
  1075. avail_file_set (list of str):
  1076. List of file extensions of the files found to be
  1077. associated to the project, and which are used in
  1078. loading the data, e.g., ccf, odml, nev, ns2,...
  1079. avail_nsx (list of int):
  1080. List of integers specifying the .nsX files available,
  1081. e.g., [2, 5] indicates that an ns2 and and ns5 file are
  1082. available.
  1083. avail_nev (bool):
  1084. True if a .nev file is available.
  1085. avail_ccf (bool):
  1086. True if a .ccf file is available.
  1087. avail_sif (bool):
  1088. True if a .sif file is available.
  1089. nb_segments (int):
  1090. Number of segments created after merging recording
  1091. times specified by user with the intrinsic ones of the
  1092. file set.
  1093. project_name (str):
  1094. Identifier for the project/experiment.
  1095. project_type (str):
  1096. Identifier for the type of project/experiment.
  1097. project_subtype (str):
  1098. Identifier of the subtype of the project/experiment.
  1099. taskdesigns (list of str):
  1100. List of strings identifying the task designed presented
  1101. during the recording. The standard task reach-to-grasp
  1102. is denoted by the string "TwoCues".
  1103. conditions (list of int):
  1104. List of condition codes (each code describing the set
  1105. of trial types presented to the subject during a
  1106. segment of the recording) present during the recording.
  1107. For a mapping of condition codes to trial types, see
  1108. the condition_str attribute of the ReachGraspIO class.
  1109. subject_name (str):
  1110. Name of the recorded subject.
  1111. subject_gender (bool):
  1112. 'male' or 'female'.
  1113. subject_birthday (datetime):
  1114. Birthday of the recorded subject.
  1115. subject_activehand (str):
  1116. Handedness of the subject.
  1117. setup_location (str):
  1118. Physical location of the recording setup.
  1119. avail_electrode_ids (list of int):
  1120. List of length 100 of electrode channel IDs (Blackrock
  1121. IDs) ordered corresponding to the connector-aligned
  1122. linear electrode IDs. The connector-aligned IDs start
  1123. at 1 in the bottom left corner, and increase from left
  1124. to right, and from bottom to top assuming the array is
  1125. placed in front of the observer pins facing down,
  1126. connector extruding to the right:
  1127. 91 92 ... 99 100 \
  1128. 81 82 ... 89 90 \
  1129. ... ... --- Connector Wires
  1130. 11 12 ... 19 20 /
  1131. 1 2 ... 9 10 /
  1132. Thus,
  1133. avail_electrode_ids[k-1]
  1134. is the Blackrock channel ID corresponding to connector-
  1135. aligned ID k. Unconnected/unavailable channels are
  1136. marked by -1.
  1137. arraygrids_tot_num (int):
  1138. Number of Utah arrays (not necessarily all connected).
  1139. electrodes_tot_num (int):
  1140. Number of electrodes of the Utah array (not necessarily
  1141. all connected).
  1142. electrodes_pitch (float):
  1143. Distance in micrometers between neighboring electrodes
  1144. in one row/column.
  1145. array_serial_num (str):
  1146. Serial number of the recording array.
  1147. array_grid_col_num, array_grid_row_num (int):
  1148. Number of columns / rows of the array.
  1149. connector_type (str):
  1150. Type of connector used for recording.
  1151. rec_pauses (bool):
  1152. True if the session contains a recording pause (i.e.,
  1153. multiple segments).
  1154. Segment annotations:
  1155. condition (int):
  1156. Condition code (describing the set of trial types
  1157. presented to the subject) of this segment. For a
  1158. mapping of condition codes to trial types, see the
  1159. condition_str attribute of the ReachGraspIO class.
  1160. ChannelIndex annotations:
  1161. connector_aligned_id (int):
  1162. Connector-aligned channel ID from which the spikes were
  1163. loaded. This is a channel ID between 1 and 100 that is
  1164. related to the location of an electrode on the Utah
  1165. array and thus common across different arrays
  1166. (independent of the Blackrock channel ID). The ID
  1167. considers a top-view of the array with the connector
  1168. wires extruding to the right. Electrodes are then
  1169. numbered from bottom left to top right:
  1170. 91 92 ... 99 100 \
  1171. 81 82 ... 89 90 \
  1172. ... ... --- Connector Wires
  1173. 11 12 ... 19 20 /
  1174. 1 2 ... 9 10 /
  1175. Note: The Blackrock IDs are given in the 'channel_ids'
  1176. property of the ChannelIndex object.
  1177. waveform_size (Quantitiy):
  1178. Length of time used to save spike waveforms (in units
  1179. of 1/30000 s).
  1180. nev_hi_freq_corner (Quantitiy),
  1181. nev_lo_freq_corner (Quantitiy),
  1182. nev_hi_freq_order (int), nev_lo_freq_order (int),
  1183. nev_hi_freq_type (str), nev_lo_freq_type (str),
  1184. nev_hi_threshold, nev_lo_threshold,
  1185. nev_energy_threshold (Quantity):
  1186. Indicates parameters of spike detection.
  1187. nev_dig_factor (int):
  1188. Digitization factor in microvolts of the nev file, used
  1189. to convert raw samples to volt.
  1190. connector_ID, connector_pinID (int):
  1191. ID of connector and pin on the connector where the
  1192. channel was recorded from.
  1193. nb_sorted_units (int):
  1194. Number of sorted units on this channel (noise, mua and
  1195. sua).
  1196. electrode_reject_XXX (bool):
  1197. For different filter ranges XXX (as defined in the odML
  1198. file), if this variable is True it indicates whether
  1199. the spikes were recorded on an electrode that should be
  1200. rejected based on preprocessing analysis for removing
  1201. electrodes due to noise/artefacts in the respective
  1202. frequency range.
  1203. Unit annotations:
  1204. coordinates (Quantity):
  1205. Contains the x and y coordinate of the electrode in mm
  1206. (spacing: 0.4mm). The coordinates use the same
  1207. representation as the connector_aligned_id with the
  1208. origin located at the bottom left electrode. Thus,
  1209. e.g., connector aligned ID 14 is at coordinates:
  1210. (1.2 mm, 0.4 mm)
  1211. unit_id (int):
  1212. ID of the unit.
  1213. channel_id (int):
  1214. Channel ID (Blackrock ID) from which the unit was
  1215. loaded (equiv. to the single list entry in the
  1216. attribute channel_ids of ChannelIndex parent).
  1217. connector_aligned_id (int):
  1218. Connector-aligned channel ID from which the unit was
  1219. loaded. This is a channel ID between 1 and 100 that is
  1220. related to the location of an electrode on the Utah
  1221. array and thus common across different arrays
  1222. (independent of the Blackrock channel ID). The ID
  1223. considers a top-view of the array with the connector
  1224. wires extruding to the right. Electrodes are then
  1225. numbered from bottom left to top right:
  1226. 91 92 ... 99 100 \
  1227. 81 82 ... 89 90 \
  1228. ... ... --- Connector Wires
  1229. 11 12 ... 19 20 /
  1230. 1 2 ... 9 10 /
  1231. electrode_reject_XXX (bool):
  1232. For different filter ranges XXX (as defined in the odML
  1233. file), if this variable is True it indicates whether
  1234. the spikes were recorded on an electrode that should be
  1235. rejected based on preprocessing analysis for removing
  1236. electrodes due to noise/artefacts in the respective
  1237. frequency range.
  1238. noise, mua, sua (bool):
  1239. True, if the unit is classified as a noise unit, i.e.,
  1240. not considered neural activity (noise), a multi-unit
  1241. (mua), or a single unit (sua).
  1242. SNR (float):
  1243. Signal to noise ratio of SUA/MUA waveforms. A higher
  1244. value indicates that the unit could be better
  1245. distinguished in the spike detection and spike sorting
  1246. procedure.
  1247. spike_duration (float):
  1248. Approximate duration of the spikes of SUAs/MUAs in
  1249. microseconds.
  1250. spike_amplitude (float):
  1251. Maximum amplitude of the spike waveform.
  1252. spike_count (int):
  1253. Number of spikes sorted into this unit.
  1254. AnalogSignal annotations:
  1255. nsx (int):
  1256. nsX file the signal was loaded from, e.g., 5 indicates
  1257. the .ns5 file.
  1258. channel_id (int):
  1259. Channel ID (Blackrock ID) from which the signal was
  1260. loaded.
  1261. connector_aligned_id (int):
  1262. Connector-aligned channel ID from which the signal was
  1263. loaded. This is a channel ID between 1 and 100 that is
  1264. related to the location of an electrode on the Utah
  1265. array and thus common across different arrays
  1266. (independent of the Blackrock channel ID). The ID
  1267. considers a top-view of the array with the connector
  1268. wires extruding to the right. Electrodes are then
  1269. numbered from bottom left to top right:
  1270. 91 92 ... 99 100 \
  1271. 81 82 ... 89 90 \
  1272. ... ... --- Connector Wires
  1273. 11 12 ... 19 20 /
  1274. 1 2 ... 9 10 /
  1275. electrode_reject_XXX (bool):
  1276. For different filter ranges XXX (as defined in the odML
  1277. file), if this variable is True it indicates whether
  1278. the spikes were recorded on an electrode that should be
  1279. rejected based on preprocessing analysis for removing
  1280. electrodes due to noise/artefacts in the respective
  1281. frequency range.
  1282. filter_shift_correction (Quantity):
  1283. If the parameter correct_filter_shift is True, and a
  1284. shift estimate was found in the odML, this annotation
  1285. indicates the amount of time by which the signal was
  1286. shifted. I.e., adding this number to t_start will
  1287. result in the uncorrected, originally recorded time
  1288. axis.
  1289. Spiketrain annotations:
  1290. unit_id (int):
  1291. ID of the unit from which the spikes were recorded.
  1292. channel_id (int):
  1293. Channel ID (Blackrock ID) from which the spikes were
  1294. loaded.
  1295. connector_aligned_id (int):
  1296. Connector-aligned channel ID from which the spikes were
  1297. loaded. This is a channel ID between 1 and 100 that is
  1298. related to the location of an electrode on the Utah
  1299. array and thus common across different arrays
  1300. (independent of the Blackrock channel ID). The ID
  1301. considers a top-view of the array with the connector
  1302. wires extruding to the right. Electrodes are then
  1303. numbered from bottom left to top right:
  1304. 91 92 ... 99 100 \
  1305. 81 82 ... 89 90 \
  1306. ... ... --- Connector Wires
  1307. 11 12 ... 19 20 /
  1308. 1 2 ... 9 10 /
  1309. electrode_reject_XXX (bool):
  1310. For different filter ranges XXX (as defined in the odML
  1311. file), if this variable is True it indicates whether
  1312. the spikes were recorded on an electrode that should be
  1313. rejected based on preprocessing analysis for removing
  1314. electrodes due to noise/artefacts in the respective
  1315. frequency range.
  1316. noise, mua, sua (bool):
  1317. True, if the unit is classified as a noise unit, i.e.,
  1318. not considered neural activity (noise), a multi-unit
  1319. (mua), or a single unit (sua).
  1320. SNR (float):
  1321. Signal to noise ratio of SUA/MUA waveforms. A higher
  1322. value indicates that the unit could be better
  1323. distinguished in the spike detection and spike sorting
  1324. procedure.
  1325. spike_duration (float):
  1326. Approximate duration of the spikes of SUAs/MUAs in
  1327. microseconds.
  1328. spike_amplitude (float):
  1329. Maximum amplitude of the spike waveform.
  1330. spike_count (int):
  1331. Number of spikes sorted into this unit.
  1332. Event annotations:
  1333. The resulting Block contains three Event objects with the
  1334. following names:
  1335. 'DigitalTrialEvents' contains all digitally recorded events
  1336. returned by BlackrockIO, annotated with semantic labels
  1337. in accordance with the reach-to-grasp experiment (e.g.,
  1338. 'TS-ON').
  1339. 'AnalogTrialEvents' contains events extracted from the
  1340. analog behavioral signals during preprocessing and
  1341. stored in the odML (e.g., 'OT').
  1342. 'TrialEvents' contains all events of DigitalTrialEvents and
  1343. AnalogTrialEvents merged into a single Neo object.
  1344. Each annotation is a list containing one entry per time
  1345. point stored in the event.
  1346. trial_event_labels (list of str):
  1347. Name identifying the name of the event, e.g., 'TS-ON'.
  1348. trial_id (list of int):
  1349. Trial ID the event belongs to.
  1350. trial_timestamp_id (list of int):
  1351. Timestamp-based trial ID (equivalent to the time of TS-
  1352. ON of a trial) the event belongs to.
  1353. belongs_to_trialtype (str):
  1354. String identifying the trial type (e.g., SGHF) the
  1355. trial belongs to.
  1356. performance_in_trial (list of int):
  1357. Performance code of the trial that the event belongs
  1358. to. Compare to the performance_codes and
  1359. performance_str attributes of ReachGraspIO class.
  1360. trial_reject_XXX:
  1361. For different filter ranges XXX (defined in the odML
  1362. file), if True this variable indicates whether the
  1363. trial was rejected based on preprocessing analysis.
  1364. """
  1365. if not name:
  1366. name = 'Reachgrasp Recording Data Block'
  1367. if not description:
  1368. description = "Block of reach-to-grasp project data from Blackrock file set."
  1369. if index is not None:
  1370. warnings.warn('`index` is deprecated and will be replaced by `block_index`.')
  1371. if nsx_to_load != 'none':
  1372. warnings.warn('`nsx_to_load` is deprecated for `read_block`. '
  1373. 'Specify `nsx_to_load when initializing the IO or use lazy loading.')
  1374. if n_starts is not None:
  1375. warnings.warn('`n_starts` is deprecated. Use lazy loading instead.')
  1376. if n_stops is not None:
  1377. warnings.warn('`n_stops` is deprecated. Use lazy loading instead.')
  1378. if channels != range(1, 97):
  1379. warnings.warn('`channels` is deprecated. Use lazy loading instead.')
  1380. if units != 'none':
  1381. warnings.warn('`units` is deprecated. Use lazy loading instead.')
  1382. if load_events is not False:
  1383. warnings.warn('`load_events` is deprecated. Use lazy loading instead.')
  1384. if scaling != 'raw':
  1385. warnings.warn('`scaling` is deprecated.')
  1386. if cascade is not True:
  1387. warnings.warn('`cascade` is deprecated. Use lazy loading instead.')
  1388. # Load neo block
  1389. bl = BlackrockIO.read_block(
  1390. self, block_index=block_index, load_waveforms=load_waveforms, lazy=lazy, **kwargs)
  1391. if name is not None:
  1392. bl.name = name
  1393. if description is not None:
  1394. bl.description = description
  1395. bl.annotate(conditions=[])
  1396. for seg in bl.segments:
  1397. if 'condition' in list(seg.annotations):
  1398. bl.annotations['conditions'].append(seg.annotations['condition'])
  1399. ch_dict = self.__create_channel_views(bl)
  1400. self.__create_unit_groups(bl, ch_dict)
  1401. if self.odmldoc:
  1402. self.__annotate_block_with_odml(bl)
  1403. self.__annotate_channel_infos(bl)
  1404. self.__annotate_units_with_odml(bl.groups)
  1405. return bl
  1406. def read_segment(
  1407. self, block_index=0, seg_index=0, name=None, description=None, index=None,
  1408. nsx_to_load='none', channels=range(1, 97), units='none',
  1409. load_waveforms=False, load_events=False, scaling='raw',
  1410. correct_filter_shifts=True, lazy=False, cascade=True, **kwargs):
  1411. """
  1412. Reads file contents as a Neo Block.
  1413. The Block contains one Segment for each entry in zip(n_starts,
  1414. n_stops). If these parameters are not specified, the default is
  1415. to store all data in one Segment.
  1416. The Block contains one ChannelIndex per channel.
  1417. Args:
  1418. n_start (Quantity): DEPRECATED
  1419. Start time of maximum time range of signals contained in this
  1420. segment. Deprecated, use lazy loading instead.
  1421. n_stop (Quantity): DEPRECATED
  1422. Stop time of maximum time range of signals contained in this
  1423. segment. Deprecated, use lazy loading instead.
  1424. name (None, string):
  1425. If None, name is set to default, otherwise it is set to user
  1426. input.
  1427. description (None, string):
  1428. If None, description is set to default, otherwise it is set to
  1429. user input.
  1430. index (None, int): DEPRECATED
  1431. If not None, index of segment is set to user index.
  1432. Deprecated, use `seg_index` instead.
  1433. nsx_to_load (int, list, str):
  1434. ID(s) of nsx file(s) from which to load data, e.g., if set to
  1435. 5 only data from the ns5 file are loaded. If 'none' or empty
  1436. list, no nsx files and therefore no analog signals are loaded.
  1437. If 'all', data from all available nsx are loaded.
  1438. channels (int, list, str): DEPRECATED
  1439. Channel id(s) from which to load data. If 'none' or empty list,
  1440. no channels and therefore no analog signal or spiketrains are
  1441. loaded. If 'all', all available channels are loaded. By
  1442. default, all neural channels (1-96) are loaded.
  1443. units (int, list, str, dict): DEPRECATED
  1444. ID(s) of unit(s) to load. If 'none' or empty list, no units and
  1445. therefore no spiketrains are loaded. If 'all', all available
  1446. units are loaded. If dict, the above can be specified
  1447. individually for each channel (keys), e.g. {1: 5, 2: 'all'}
  1448. loads unit 5 from channel 1 and all units from channel 2.
  1449. load_waveforms (boolean):
  1450. If True, waveforms are attached to all loaded spiketrains.
  1451. load_events (boolean): DEPRECATED
  1452. If True, all recorded events are loaded.
  1453. scaling (str): DEPRECATED
  1454. Determines whether time series of individual
  1455. electrodes/channels are returned as AnalogSignals containing
  1456. raw integer samples ('raw'), or scaled to arrays of floats
  1457. representing voltage ('voltage'). Note that for file
  1458. specification 2.1 and lower, the option 'voltage' requires a
  1459. nev file to be present.
  1460. correct_filter_shifts (bool):
  1461. If True, shifts of the online-filtered neural signals (e.g.,
  1462. ns2, channels 1-128) are corrected by time-shifting the signal
  1463. by a heuristically determined estimate stored in the metadata,
  1464. in the property EstimatedShift, under the path
  1465. /Cerebus/NeuralSignalProcessor/NeuralSignals/Filter_nsX/
  1466. lazy (boolean):
  1467. If True, only the shape of the data is loaded.
  1468. cascade (boolean): DEPRECATED
  1469. If True, only the segment without children is returned.
  1470. kwargs:
  1471. Additional keyword arguments are forwarded to the BlackrockIO.
  1472. Returns:
  1473. Segment (neo.segment.Segment):
  1474. Segment linking to all loaded Neo objects. See documentation of
  1475. read_block() for a full list of annotations per Neo object.
  1476. """
  1477. if index is not None:
  1478. warnings.warn('`index` is deprecated and will be replaced by `segment_index`.')
  1479. if nsx_to_load != 'none':
  1480. warnings.warn('`nsx_to_load` is deprecated for `read_block`. '
  1481. 'Specify `nsx_to_load when initializing the IO or use lazy loading.')
  1482. if channels != range(1, 97):
  1483. warnings.warn('`channels` is deprecated. Use lazy loading instead.')
  1484. if units != 'none':
  1485. warnings.warn('`units` is deprecated. Use lazy loading instead.')
  1486. if load_events is not False:
  1487. warnings.warn('`load_events` is deprecated. Use lazy loading instead.')
  1488. if scaling != 'raw':
  1489. warnings.warn('`scaling` is deprecated.')
  1490. if cascade is not True:
  1491. warnings.warn('`cascade` is deprecated. Use lazy loading instead.')
  1492. # Load neo block
  1493. seg = BlackrockIO.read_segment(
  1494. self, block_index=block_index, seg_index=seg_index, load_waveforms=load_waveforms,
  1495. lazy=lazy, **kwargs)
  1496. if name is not None:
  1497. seg.name = name
  1498. if description is not None:
  1499. seg.description = description
  1500. # load data of all events and epochs
  1501. for ev_idx, event in enumerate(seg.events):
  1502. seg.events[ev_idx] = event.load()
  1503. seg.events[ev_idx].segment = seg
  1504. for ep_idx, epoch in enumerate(seg.epochs):
  1505. seg.epochs[ep_idx] = epoch.load()
  1506. seg.epochs[ep_idx].segment = seg
  1507. for asig in seg.analogsignals:
  1508. self.__annotate_analogsignals_with_odml(asig)
  1509. if correct_filter_shifts:
  1510. self.__correct_filter_shifts(asig)
  1511. for st in seg.spiketrains:
  1512. self.__annotate_electrode_rejections(st)
  1513. for ev in seg.events:
  1514. # Modify digital trial events to include semantic event information
  1515. if ev.name == 'digital_input_port':
  1516. self.__annotate_dig_trial_events(ev)
  1517. self.__add_rejection_to_event(ev)
  1518. cnd = self.__extract_task_condition(ev.array_annotations['belongs_to_trialtype'])
  1519. seg.annotate(condition=cnd)
  1520. # If digital trial events exist, extract analog events from odML
  1521. # and create one common event array
  1522. if len(seg.events) > 0 and self.odmldoc:
  1523. analog_event = self.__extract_analog_events_from_odml(seg.t_start, seg.t_stop)
  1524. self.__add_rejection_to_event(analog_event)
  1525. seg.events.append(analog_event)
  1526. merged_event = self.__merge_digital_analog_events(seg.events)
  1527. self.__add_rejection_to_event(merged_event)
  1528. seg.events.append(merged_event)
  1529. return seg
  1530. if __name__ == '__main__':
  1531. pass