reachgraspio.py 81 KB

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