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