reachgraspio.py 73 KB

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