-
Notifications
You must be signed in to change notification settings - Fork 6
/
make_nwb.py
executable file
·2692 lines (2421 loc) · 128 KB
/
make_nwb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/local/python-2.7.11/bin/python
#
# make_nwb.py
#
# Created by Claudia Friedsam on 2015-02-08.
# Redesigned by Gennady Denisov on 2016-03-28.
import sys
import os
import nwb
from nwb import nwb_file
from nwb import nwb_utils
import h5py
import datetime
import unicodedata
import getpass
import numpy as np
from sets import Set
import re
import optparse
import libh5
# ------------------------------------------------------------------------------
def make_nwb_command_line_parser(parser):
parser.add_option("-D", "--debug", action="store_true", dest="debug", help="output debugging info", default=False)
parser.add_option("-e", "--no_error_handling", action="store_false", dest="handle_errors", help="handle_errors", default=True)
parser.add_option("-o", "--outfolder", dest="output_folder", help="output folder (default=same as input folder)",metavar="output_folder",default="")
parser.add_option("-r", "--replace", action="store_true", dest="replace", help="if the output file already exists, replace it", default=False)
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="increase the verbosity level of output", default=False)
return parser
# ------------------------------------------------------------------------------
def check_entry(file_name,obj):
try:
return file_name[obj]
except KeyError:
print(str(obj) +" does not exist")
return []
# ------------------------------------------------------------------------------
# function used for natural sort ke
# from: http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-a-list-using-a-natural-order-algorithm
def sortkey_natural(s):
return tuple(int(part) if re.match(r'[0-9]+$', part) else part
for part in re.split(r'([0-9]+)', s))
# ------------------------------------------------------------------------------
# these (natural_sort and sortkey_natural) added to sort object names in parse_h5_obj
# so that numerical object names, like "1" "2" "10", "11", "22" are sorted according
# to their numeric value (int) instead of their string sort order
def natural_sort(vals):
"""return sorted numerically if all integers, otherwise, sorted alphabetically"""
all_str = all(isinstance(x, (str, unicode)) for x in vals)
sv = sorted(vals, key=sortkey_natural) if all_str else sorted(vals)
return sv
# ------------------------------------------------------------------------------
def parse_h5_obj(obj, level = 0, output = [], verbose = 0):
if level == 0:
output = []
try:
if isinstance(obj, h5py.highlevel.Dataset):
level = level+1
if obj.value.any():
output.append(obj.value)
else:
full_name = obj.name.split("/")
output.append(full_name[-1])
elif isinstance(obj, h5py.highlevel.Group):
level = level+1
if not obj.keys():
output.append([])
else:
for key in natural_sort(list(obj.keys())):
parse_h5_obj(obj[key], level, output, verbose)
else:
output.append([])
except KeyError:
print("Can't find" + str(obj))
output.append([])
return output
# ------------------------------------------------------------------------------
# each of nwb_object's hdf5 files have imaging planes and subareas
# labels consistent within the file, but inconsistent between
# files. create a map between the h5 plane name and the
# identifier used between files
# plane_map = {}
def add_plane_map_entry(plane_map, h5_plane_name, filename, options):
toks = filename.split("fov_")
if len(toks) != 2:
print("Error parsing %s for imaging plane name" % filename)
sys.exit(1)
univ_name = "fov_" + toks[1][:5]
if univ_name not in plane_map:
#print filename + " -> " + univ_name
plane_map[h5_plane_name] = univ_name
return univ_name
# ------------------------------------------------------------------------------
def create_plane_map(orig_h5, plane_map, options):
if options.handle_errors:
num_subareas = 1
if '1' in orig_h5['timeSeriesArrayHash/descrHash'].keys():
num_subareas = len(orig_h5['timeSeriesArrayHash/descrHash'].keys()) - 1
else:
num_subareas = len(orig_h5['timeSeriesArrayHash/descrHash'].keys()) - 1
for subarea in range(num_subareas):
# fetch time array
if options.handle_errors:
try:
grp = orig_h5['timeSeriesArrayHash/value/%d/imagingPlane' %(subarea + 2)]
grp2 = orig_h5['timeSeriesArrayHash/descrHash/%d/value/1' %(subarea + 2)]
except:
try:
grp = orig_h5['timeSeriesArrayHash/value/imagingPlane']
grp2 = orig_h5['timeSeriesArrayHash/descrHash/value']
except:
print("Cannot create plane map")
break
else:
grp = orig_h5['timeSeriesArrayHash/value/%d/imagingPlane' %(subarea + 2)]
grp2 = orig_h5['timeSeriesArrayHash/descrHash/%d/value/1' %(subarea + 2)]
if grp2.keys()[0] == 'masterImage':
num_planes = 1
else:
num_planes = len(grp2.keys())
for plane in range(num_planes):
# if num_planes == 1:
# pgrp = grp
# else:
# pgrp = grp["%d"%(plane+1)]
# print("\nsubarea=", subarea, " plane=", plane
if options.handle_errors:
try:
pgrp = grp["%d"%(plane+1)]
except:
# Warning: only one imaging plane available (instead of 3)
pgrp = grp
else:
pgrp = grp["%d"%(plane+1)]
old_name = "area%d_plane%d" % (subarea+1, plane+1)
frame_idx = pgrp["sourceFileFrameIdx"]["sourceFileFrameIdx"].value
lst = parse_h5_obj(pgrp["sourceFileList"])[0]
for k in lst:
# srcfile = str(lst[k][k].value)
srcfile = str(k)
add_plane_map_entry(plane_map, old_name, srcfile, options)
break
# ------------------------------------------------------------------------------
# fetch start time/date of experiment
def find_exp_time(input_h5, options):
child_groups = libh5.get_child_group_names(input_h5)
# print("child_groups=", child_groups
if options.data_origin == "SP":
# SP data
d = libh5.get_value_by_key(input_h5['/metaDataHash'], \
"dateOfExperiment")
t = libh5.get_value_by_key(input_h5['/metaDataHash'], \
"timeOfExperiment")
# print("d=", d
# print("t=", t
dt=datetime.datetime.strptime(d+t, "%Y%m%d%H%M%S")
elif options.data_origin in ["NL", "DG"]:
d = np.array(libh5.get_value_pointer_by_path_items(input_h5, \
["dateOfExperiment", "dateOfExperiment"])).tolist()[0]
t = np.array(libh5.get_value_pointer_by_path_items(input_h5, \
["timeOfExperiment", "timeOfExperiment"])).tolist()[0]
try:
if re.search("not recorded", t):
dt = datetime.datetime.strptime(d, "%Y%m%d")
else:
dt = datetime.datetime.strptime(d+t, "%Y%m%d%H%M%S")
except:
d = re.sub('\x00','', d)
t = re.sub('\x00','', t)
dt = datetime.datetime.strptime(d+t, "%Y%m%d")
elif options.data_origin == "JY":
d = np.array(libh5.get_value_pointer_by_path_items(input_h5, \
["dateOfExperiment", "dateOfExperiment"])).tolist()[0]
print "d=", d
print("date=", "20"+str(d))
dt = datetime.datetime.strptime("20"+d, "%Y%m%d")
else:
sys.exit("Data origin is unknown")
return dt.strftime("%a %b %d %Y %H:%M:%S")
# ------------------------------------------------------------------------------
# create 2-photon time series, pointing to specified filename
# use junk values for 2-photon metadata, for now at least
def create_2p_tsa(nwb_object, img_plane, ext_file, starting_frame, \
timestamps, name):
twop = nwb_object.make_group("<TwoPhotonSeries>", img_plane, \
path='/acquisition/timeseries', attrs={ \
"source": "Device 'two-photon microscope'",\
"description": \
"2P image stack, one of many sequential stacks for this field of view"})
twop.set_dataset("format", "external")
# need to convert name to utf8, otherwise error generated:
# TypeError: No conversion path for dtype: dtype('<U91'). Added by jt.
# fname_utf = fname.encode('utf8')
twop.set_dataset("external_file", ext_file, attrs={"starting_frame": starting_frame})
twop.set_dataset("dimension", [512,512])
#twop.set_value("pmt_gain", 1.0)
twop.set_dataset("scan_line_rate", 16000.0)
twop.set_dataset("field_of_view", [ 600e-6, 600e-6 ])
twop.set_dataset("imaging_plane", img_plane)
twop.set_dataset("timestamps", timestamps)
# ------------------------------------------------------------------------------
# save frames for 2-photon series. These are used in routine create_2p_tsa
def save_2p_frames(external_file, starting_frame, timestamps, fname, stack_t):
starting_frame.append(len(timestamps))
timestamps.extend(stack_t)
external_file.append(fname.encode('utf8'))
# ------------------------------------------------------------------------------
# pull out masterImage arrays and create entries for each in
# /acquisition/images
# masterImages are store in:
# tsah::descrHash::[2-7]::value::1::[1-3]::masterImage
# each image has 2 color channels, green and red
def update_reference_images(orig_h5, nwb_object, master_shape, \
ref_image_red, ref_image_green, plane_map, area, \
plane, options, num_plane = 3):
area_grp = orig_h5["timeSeriesArrayHash/descrHash"]["%d"%(1+area)]
if num_plane == 1:
plane_grp = area_grp["value/1"]
else:
plane_grp = area_grp["value/1"]["%d"%(plane)]
master = plane_grp["masterImage"]["masterImage"].value
master1_shape = np.array(master).shape
green = np.zeros([master1_shape[0],master1_shape[1]])
red = np.zeros([master1_shape[0],master1_shape[1]])
if len(master1_shape) == 3 or not options.handle_errors:
green = master[:,:,0]
red = master[:,:,1]
else:
green = master
red = master
# convert from file-specific area/plane mapping to
# inter-session naming convention
oname = "area%d_plane%d" % (area, plane)
master_shape[oname] = master1_shape
image_plane = plane_map[oname]
ref_image_green[image_plane] = green
ref_image_red[image_plane] = red
# Store green and red referebce images
fmt = "raw"
name = image_plane + "_green"
desc = "Master image (green channel), in " + str(master1_shape[0]) + \
"x" + str(master1_shape[1]) + ", 8bit"
nwb_object.set_dataset("<image_X>", green.astype('uint8'), name=name,\
dtype='uint8', attrs={"description":desc, \
"format": fmt, "source" : " "})
name = image_plane + "_red"
desc = "Master image (red channel), in " + str(master1_shape[0]) + \
"x" + str(master1_shape[1]) + ", 8bit"
nwb_object.set_dataset("<image_X>", red.astype('uint8'), name=name, \
dtype='uint8', attrs={"description":desc, \
"format": fmt, "source" : " "})
# Use the green ref image as reference frame in /general/optophysiology/fov_xx
general_group = nwb_object.make_group("general", abort=False)
optophys_group = general_group.make_group("optophysiology", abort=False)
fov_xx_group = optophys_group.make_group("<imaging_plane_X>", name=image_plane, abort=False)
fov_xx_group.set_dataset("reference_frame", "3.6 mm lateral (left), 1.6 mm posterior Bregma, 0 mm depth")
return (master_shape, ref_image_red, ref_image_green)
# ------------------------------------------------------------------------------
# pull out all ROI pixel maps for a particular subarea and imaging plane
# and store these in the segmentation module
def fetch_rois(orig_h5, master_shape, plane_map, seg_iface, area, plane, \
options, num_planes=3):
tsah = orig_h5["timeSeriesArrayHash"]
# convert from file-specific area/plane mapping to
# inter-session naming convention
#image_plane = "area%d_plane%d" % (area, plane)
oname = "area%d_plane%d" % (area, plane)
master1_shape = master_shape[oname]
image_plane = plane_map[oname]
sip = seg_iface.make_group("<image_plane>", image_plane, \
attrs={"source" : "Simon's data file"})
sip.set_dataset("imaging_plane_name", image_plane)
sip.set_dataset("description", image_plane)
# first get the list of ROIs for this subarea and plane
if options.handle_errors:
try:
ids = tsah["value"]["%d"%(area+1)]["imagingPlane"]["%d"%plane]["ids"]
except:
# Warning: only one imaging plane is available (instead of 3)
ids = tsah["value"]["%d"%(area+1)]["imagingPlane"]["ids"]
else:
ids = tsah["value"]["%d"%(area+1)]["imagingPlane"]["%d"%plane]["ids"]
roi_ids = ids["ids"].value
lookup = tsah["value"]["%d"%(area+1)]["ids"]["ids"].value
for i in range(len(roi_ids)):
rid = roi_ids[i]
if num_planes == 1:
rois = tsah["descrHash"]["%d"%(area+1)]["value"]["1"]
else:
rois = tsah["descrHash"]["%d"%(area+1)]["value"]["1"]["%d"%plane]
# make sure the ROI id is correct
try:
record = rois["rois"]["%s"%(1+i)]
x = int(parse_h5_obj(record["id"])[0])
assert x == int(rid)
except:
print("Missing ROI for area=" +str(area)+ " plane="+ str(plane) + " id=" +str(i))
continue
pix = parse_h5_obj(record["indicesWithinImage"])[0]
# pix = record["indicesWithinImage/indicesWithinImage"].value
pixmap = []
for j in range(len(pix)):
v = pix[j]
px = int(v / master1_shape[1])
py = int(v) % master1_shape[0]
pixmap.append([py,px])
weight = np.zeros(len(pixmap)) + 1.0
# print("image_plane=", image_plane, " oname=", oname
nwb_utils.add_roi_mask_pixels(seg_iface, image_plane, "%d"%x, "ROI %d"%x, np.array(pixmap).astype('uint16'), \
weight, master1_shape[1], master1_shape[0])
# ------------------------------------------------------------------------------
def fetch_dff(orig_h5, dff_iface, seg_iface, plane_map, area, plane, \
options, num_planes=3):
area_grp = orig_h5["timeSeriesArrayHash/value"]["%d"%(area+1)]
if options.handle_errors:
try:
plane_ids = area_grp["imagingPlane"]["%d"%plane]["ids/ids"].value
except:
# Warning: only one imaging plane is available (instead of 3)
plane_ids = area_grp["imagingPlane"]["ids/ids"].value
else:
plane_ids = area_grp["imagingPlane"]["%d"%plane]["ids/ids"].value
area_ids = area_grp["ids/ids"].value
# store dff in matrix and supply that to time series
dff_data = area_grp["valueMatrix/valueMatrix"].value
# convert from file-specific area/plane mapping to
# inter-session naming convention
oname = "area%d_plane%d" % (area, plane)
image_plane = plane_map[oname]
t = area_grp["time/time"].value * 0.001
# create array of ROI names for each matrix row
roi_names = []
trial_ids = area_grp["trial/trial"].value
# for each plane ID, find group idx. df/f is idx'd row in values
for i in range(len(plane_ids)):
roi_names.append("ROI%d"%plane_ids[i])
dff_ts = dff_iface.make_group("<RoiResponseSeries>", image_plane,
attrs = {"source" : "Simon's data file"})
dff_ts.set_dataset("data", dff_data, attrs={"unit":"dF/F",
"conversion": 1.0, "resolution":0.0})
dff_ts.set_dataset("timestamps", t)
dff_ts.set_dataset("roi_names", roi_names)
#- dff_ts.set_value_as_link("segmentation_interface", seg_iface)
dff_ts.make_group("segmentation_interface", seg_iface)
trial_ids = area_grp["trial/trial"].value
dff_ts.set_custom_dataset("trial_ids", trial_ids)
# ------------------------------------------------------------------------------
# Function: create_time_series
# Returns: pointer to the created group
# Arguments: series_name, series_type, series_path, nwb_object,
# var, t, description, source, comments,
# hash_group , keyName, options
# Action:
# - creates a group <series_name>
# of type <series_type>
# at the path <spath>
# relative to <nwb_group>
# - creates datasets "data", "num_samples" and "timestamps"
# inside of the series group
# - populates the datasets from the arrays var and t
# - populates dataset "timestamps" with the data from input array t
# using <keyName>
# - sets the attributes "description", "source" and "comments"
# to the time series group using the input strings
# <description>, <source> and <comments>
# - perform additional data handling using <h5_hash_group> and <keyName>
# NOTE: argument t has different meaning depending on the keyName
def create_time_series(series_name, series_type, series_path, \
orig_h5, nwb_group, group_attrs, var, t, data_attrs, \
hash_group_pointer, keyName, options):
# initialize timeseries
if options.verbose:
print(" Creating group " + str(series_name) + " type=" + str(series_type)+ " path=" + str(series_path))
if len(series_path) > 0:
print "Creating ts ", series_name, " at series_path=", series_path
ts = nwb_group.make_group(series_type, series_name, path = series_path, \
attrs = group_attrs)
else:
print "Creating ts ", series_name
ts = nwb_group.make_group(series_type, series_name, attrs = group_attrs)
# 1) Data = on_off
if series_name in ["water_left", "water_right", \
"pole_touch_protract","pole_touch_retract", \
"auditory_cue"] \
or (series_name == "pole_accessible" and series_path == "/stimulus/presentation"):
timestamps = t
on_off = np.int_(np.zeros(len(t)))
on_off += -1
on_off[::2] *= -1
data = on_off
# SP data only
if series_name == "pole_touch_protract":
kappa_ma_path = "eventSeriesArrayHash/value/2/eventPropertiesHash/1/value/2/2"
kappa_ma = orig_h5[kappa_ma_path].value
# ts.set_custom_dataset("kappa_max_abs_over_touch", kappa_ma)
elif series_name == "pole_touch_retract":
kappa_ma_path = "eventSeriesArrayHash/value/2/eventPropertiesHash/2/value/2/2"
kappa_ma = orig_h5[kappa_ma_path].value
# ts.set_custom_dataset("kappa_max_abs_over_touch", kappa_ma)
# 2) Data = [1]*len(timestamps)
elif series_name in ["lick_left", "lick_right",\
"water_left_reward", "water_right_reward",\
"pole_in", "pole_out", "reward_cue", \
"lick_time", "pole_accessible"]: \
data = [1] * len(t)
timestamps = t
# 3) Data = value
elif series_name in ["whisker_angle", "whisker_curve", "pole_position", \
"lick_trace", "photostim_control"] \
or re.search("photostimulus_", series_name) \
or keyName in ["whiskerVars", "Ephys"]:
data = var
timestamps = t
else:
sys.exit("Unknown key " + keyName + \
" or series_name " + series_name + \
" in create_time_series")
data_attrs['keyName'] = keyName
ts.set_dataset("data", data, attrs=data_attrs)
ts.set_dataset("timestamps", timestamps)
ts.set_dataset("num_samples", len(timestamps))
return ts
# ------------------------------------------------------------------------------
# pole position
# store accessible intervals as BehavioralInterval (pole_accessible)
# store touch times as BehavioralInterval (pole_touch
def process_pole_position(orig_h5, nwb_object, options):
if options.data_origin == "SP":
# create time series for stimulus/presentation group
keyName = "poleInReach"
hash_group_pointer = orig_h5['eventSeriesArrayHash']
grp = libh5.get_value_pointer_by_key(hash_group_pointer , keyName, \
options.debug)
t = grp["eventTimes/eventTimes"].value * 0.001
description = libh5.get_description_by_key(hash_group_pointer , keyName)
group_attrs = {"source" : "Intervals are as reported in Simon's data file", \
"description" : description}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution":0.0}
# create time series for stimulus/presentation group
series_path = "/stimulus/presentation"
pole_acc = create_time_series("pole_accessible", "<IntervalSeries>", series_path,\
orig_h5, nwb_object, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName, options)
# create time series for processing/Pole/BehavioralEvents group
mod = nwb_object.make_group("<Module>", "Pole", attrs = \
{"description" : "Pole accessibility times"})
pole_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Pole accessibility times"})
group_attrs = {"source" : "Intervals are as reported in Simon's data file", \
"description" : description}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution":0.0}
pole_acc = create_time_series("pole_accessible", "<IntervalSeries>", '',\
orig_h5, pole_iface, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName, options)
elif options.data_origin in ["NL", "JY", "DG"]:
hash_group_pointer = orig_h5["trialPropertiesHash"]
source = "Times as reported in motor cortex data file, but relative to session start"
trial_start_times = orig_h5["trialStartTimes/trialStartTimes"].value
grp = orig_h5["trialPropertiesHash/value/"]
series_path = "/stimulus/presentation"
if options.data_origin == "DG":
# handle pole_pos data
keyName = "PolePos"
data = grp["1/1"].value
time = grp["2/2"].value
t = time + trial_start_times
description = libh5.get_description_by_key(hash_group_pointer, keyName)
group_attrs = {"source": source, "description" : description}
data_attrs = {"resolution":0.1,"conversion":1.0}
pole_position = create_time_series("pole_position", "<TimeSeries>", series_path,\
orig_h5, nwb_object, group_attrs, data, t, data_attrs, \
hash_group_pointer, keyName, options)
# get relevant pole_in data
keyName1 = "PoleInTime"
if options.data_origin in ["NL", "JY"]:
time = grp["1/1"].value
else:
time = grp["2/2"].value
t = time + trial_start_times
description = libh5.get_description_by_key(hash_group_pointer, keyName1)
group_attrs = {"source": source, "description" : description}
data_attrs = {"resolution":0.1,"unit":"unknown", "conversion":1.0}
pole_in = create_time_series("pole_in", "<TimeSeries>", series_path,\
orig_h5, nwb_object, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName1, options)
# same procedure for pole_out
keyName2 = "PoleOutTime"
if options.data_origin in ["NL", "JY"]:
time = grp["2/2"].value
else:
time = grp["3/3"].value
t = time + trial_start_times
description = libh5.get_description_by_key(hash_group_pointer, keyName2)
group_attrs = {"source": source, "description" : description}
data_attrs = {"resolution":float('nan'),"unit":"unknown","conversion":1.0}
pole_out = create_time_series("pole_out", "<TimeSeries>", series_path,\
orig_h5, nwb_object, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName2, options)
else:
sys.exit("Unable to read pole position")
# ------------------------------------------------------------------------------
# licks
def process_licks(orig_h5, nwb_object, options):
if options.data_origin in ["SP", "JY"]:
mod = nwb_object.make_group("<Module>", "Licks", attrs = \
{"description" : "Lick port contact times"})
if options.data_origin == "SP":
# SP data
lick_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Lick Times as reported in Simon's data file"})
mod.set_custom_dataset("description", "Lickport contacts, right and left")
lick_iface.set_attr("source", "Data as reported in somatosensory cortex data file")
hash_group_pointer = orig_h5['eventSeriesArrayHash']
source = "Intervals are as reported in somatosensory cortex data file"
group_attrs = {"description": "Left lickport contact times (beam breaks left)",
"source": "Times as reported in Simon's data file",
"comments": "Timestamp array stores lick times"}
# Handle left licks
keyName1 = 'leftLicks'
description = libh5.get_description_by_key(hash_group_pointer, keyName1)
grp = libh5.get_value_by_key(hash_group_pointer, keyName1)
t = grp["eventTimes/eventTimes"].value * 0.001
data_attrs = {"description": description, \
"source": "Times as reported in Simon's data file",
"unit":"licks", "conversion": 1.0, "resolution": 1.0}
ts_left = create_time_series("lick_left", "<TimeSeries>", "",\
orig_h5, lick_iface, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName1, options)
# Handle right licks
keyName2 = 'rightLicks'
description = libh5.get_description_by_key(hash_group_pointer, keyName2)
grp = libh5.get_value_by_key(hash_group_pointer, keyName2)
t = grp["eventTimes/eventTimes"].value * 0.001
data_attrs = {"description": description, \
"source": "Times as reported in Simon's data file",
"unit":"licks", "conversion": 1.0, "resolution": 1.0}
ts_right = create_time_series("lick_right", "<TimeSeries>", "",\
orig_h5, lick_iface, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName2, options)
elif options.data_origin in ["NL", "DG"]:
hash_group_pointer = orig_h5["timeSeriesArrayHash"]
if options.data_origin == "NL":
keyName = "EphusVars"
lick_trace = hash_group_pointer["value/valueMatrix/valueMatrix"][:,0]
grp_name = "timeSeriesArrayHash/value/time/time"
timestamps = orig_h5[grp_name].value
description = parse_h5_obj(hash_group_pointer["value/idStrDetailed/idStrDetailed"])[0][0]
else:
keyName = "lickVars"
lick_trace = hash_group_pointer["value/2/valueMatrix/valueMatrix"]
timestamps = hash_group_pointer["value/2/time/time"]
description = parse_h5_obj(hash_group_pointer["value/2/idStrDetailed/idStrDetailed"])[0][0]
series_path = "/acquisition/timeseries"
comment1 = keyName
comment2 = libh5.get_description_by_key(hash_group_pointer, keyName)
comments = comment1 + ": " + comment2
data_attrs={"conversion":1.0, "unit":"unknown", "resolution":float('nan')}
group_attrs={"description" : description, "comments" : comments, \
"source": "Times as reported in Nuo's data file"}
lick_ts = create_time_series("lick_trace", "<TimeSeries>", series_path,\
orig_h5, nwb_object, group_attrs, lick_trace, timestamps, data_attrs, \
hash_group_pointer, keyName, options)
elif options.data_origin == "JY":
# JY data
lick_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Lick Times as reported in Jianing's data file"})
hash_group_pointer = orig_h5["trialPropertiesHash"]
# Handle lick times
keyName = "LickTime"
description = libh5.get_description_by_key(hash_group_pointer , keyName)
data_attrs = {"resolution":0.1,"conversion":1.0,\
"description" : description, \
"source" : "Lick times as reported in Jianing's data file"}
trial_start_times = orig_h5["trialStartTimes/trialStartTimes"].value
grp = libh5.get_value_by_key(hash_group_pointer, keyName)
start_t = []
num_trials = len(grp.keys())
for k in sorted([int(k) for k in grp.keys()]):
dt = grp[str(k) + "/" + str(k)].value * 0.001
for i in range(0, len(dt)):
start_t.append(trial_start_times[int(k-1)])
ts_time = create_time_series("lick_time", "<TimeSeries>", "",\
orig_h5, lick_iface, {}, '', start_t, data_attrs, \
hash_group_pointer, keyName, options)
# ------------------------------------------------------------------------------
# water
def process_water(orig_h5, nwb_object):
hash_group_pointer = orig_h5['eventSeriesArrayHash']
source = "Intervals are as reported in somatosensory cortex data file"
series_path="/stimulus/presentation"
# handling data for stimulus/presentation
# left water
keyName1 = "leftReward"
description1 = libh5.get_description_by_key(hash_group_pointer, keyName1)
grp = libh5.get_value_by_key(hash_group_pointer , keyName1)
t1 = grp["eventTimes/eventTimes"].value * 0.001
group_attrs = {"source" : source, "description" : description1}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution":0.0}
water_left = create_time_series("water_left", "<IntervalSeries>", \
series_path, orig_h5, nwb_object, group_attrs, '', t1, \
data_attrs, hash_group_pointer, keyName1, options)
# right water
keyName2 = "rightReward"
description2 = libh5.get_description_by_key(hash_group_pointer , keyName2)
grp = libh5.get_value_by_key(hash_group_pointer , keyName2)
t2 = grp["eventTimes/eventTimes"].value * 0.001
group_attrs = {"source" : source, "description" : description2}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution":0.0}
water_right = create_time_series("water_right", "<IntervalSeries>", \
series_path, orig_h5, nwb_object, group_attrs, '', t2, \
data_attrs, hash_group_pointer, keyName2, options)
# handling data for processing
# create time series for processing/Pole/BehavioralEvents group
mod = nwb_object.make_group("<Module>", "Reward", attrs = \
{"description" : "Water reward times"})
water_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Water reward times"})
group_attrs = {"source" : "Intervals are as reported in Simon's data file", \
"description" : description1}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution":0.0}
water_left = create_time_series("water_left_reward", "<IntervalSeries>", '',\
orig_h5, water_iface, group_attrs, '', t1, data_attrs, \
hash_group_pointer, keyName1, options)
group_attrs = {"source" : "Intervals are as reported in Simon's data file", \
"description" : description2}
water_left = create_time_series("water_right_reward", "<IntervalSeries>", '',\
orig_h5, water_iface, group_attrs, '', t2, data_attrs, \
hash_group_pointer, keyName2, options)
# ------------------------------------------------------------------------------
# auditory_cue
def process_cue(orig_h5, nwb_object, options):
series_path = "/stimulus/presentation"
if options.data_origin == "NL":
# NL data
keyName = "CueTime"
trial_start_times = orig_h5["trialStartTimes/trialStartTimes"].value
grp = orig_h5["trialPropertiesHash/value/"]
time = grp["3/3"].value
description = grp = orig_h5["trialPropertiesHash/descr/descr"][2]
print "CueTime_description=", description
cue_timestamps = time + trial_start_times
hash_group_pointer = orig_h5['trialPropertiesHash']
description = libh5.get_description_by_key(hash_group_pointer, keyName)
group_attrs = {"comments" : description,\
"description" : keyName, \
"source" : "Times are as reported in Nuo's data file, but relative to session time"}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution": 0.0, "duration" : 0.1}
cue_ts = create_time_series("auditory_cue", "<TimeSeries>", series_path,\
orig_h5, nwb_object, group_attrs, '', cue_timestamps, data_attrs, \
hash_group_pointer, keyName, options)
elif options.data_origin == "SP":
# SP data
# handling data for /stimulus/presentation
# auditory cue
hash_group_pointer = orig_h5['eventSeriesArrayHash']
keyName = "rewardCue"
description = libh5.get_description_by_key(hash_group_pointer, keyName)
grp = libh5.get_value_by_key(hash_group_pointer, keyName)
t = grp["eventTimes/eventTimes"].value * 0.001
group_attrs = {"description" : "Intervals when auditory cue presented",\
"source": "Intervals are as reported in Simon's data file"}
data_attrs = {"unit": "None", "conversion": 1.0, "resolution": 0.0}
cue_ts = create_time_series("auditory_cue", "<IntervalSeries>", series_path,
orig_h5, nwb_object, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName, options)
# handling data for /processing
mod = nwb_object.make_group("<Module>", "Auditory", attrs = \
{"description" : "Auditory reward times"})
auditory_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Auditory reward times"})
data_attrs = {"unit": "None", "conversion": 1.0, "resolution": 0.0}
cue_ts = create_time_series("reward_cue", "<IntervalSeries>", '',
orig_h5, auditory_iface, group_attrs, '', t, data_attrs, \
hash_group_pointer, keyName, options)
# ------------------------------------------------------------------------------
def process_whisker(orig_h5, nwb_object, options):
# create module
mod = nwb_object.make_group("<Module>", "Whisker")
# Create interface
whisker_iface = mod.make_group("BehavioralTimeSeries", attrs={
"source": "Whisker data"})
# Create time series
keyName = 'whiskerVars'
hash_group_pointer = orig_h5['timeSeriesArrayHash']
grp = libh5.get_value_by_key(hash_group_pointer , keyName)
# GD scaling must be read in from input file
t = grp["time/time"].value * 0.001
if options.data_origin == "SP":
mod.set_custom_dataset("description", \
"Whisker angle and curvature (relative) of the whiskers and times when the pole was touched by whiskers")
var = grp["valueMatrix/valueMatrix"].value
if options.handle_errors:
try:
grp = orig_h5["timeSeriesArrayHash/value/1"]
except:
grp = orig_h5["timeSeriesArrayHash/value"]
else:
grp = orig_h5["timeSeriesArrayHash/value/1"]
descr = parse_h5_obj(grp["idStrs"])[0]
# whisker angle time series
# embedded nans screw things up -- remove them
# count how many non-nan values, and prepare output array
angle = var[0]
group_attrs={"description": descr[0],
"source": "Whisker angle as reported in Simon's data file"}
data_attrs ={"unit": "degrees", "conversion":1.0, "resolution":0.001}
ts_angle = create_time_series("whisker_angle", "<TimeSeries>", "",\
orig_h5, whisker_iface, group_attrs, angle, t, data_attrs, \
hash_group_pointer, keyName, options)
ts_angle.set_attr("description", "Angle of whiskers")
ts_angle.set_attr("source", "Whisker angle as reported in Simon's data file")
# whisker curvature
curv = var[1]
group_attrs={"description": descr[1],
"source": "Curvature (relative) of whiskers as reported in Simon's data file"}
data_attrs={"unit":"Unknown", "conversion": 1.0, "resolution": 1.0}
ts_curve = create_time_series("whisker_curve", "<TimeSeries>", "",\
orig_h5, whisker_iface, group_attrs, curv, t, data_attrs, \
hash_group_pointer , keyName, options)
# pole touches
pole_iface = mod.make_group("BehavioralEvents", attrs={
"source": "Pole intervals as reported in Simon's data file"})
keyName = "touches"
hash_group_pointer = orig_h5["eventSeriesArrayHash"]
grp = libh5.get_value_by_key(hash_group_pointer , keyName)
# protraction touches
t = grp["eventTimes/1/1"].value * 0.001
group_attrs = {"description" : "Intervals that whisker touches pole (protract)",\
"source" : "Intervals are as reported in Simon's data file"}
if len(t) > 0 or not options.handle_errors:
pole_touch_pr = create_time_series("pole_touch_protract", "<IntervalSeries>",\
"", orig_h5, pole_iface, group_attrs, '', t, {},\
hash_group_pointer, keyName, options)
# retraction touches
t = grp["eventTimes/2/2"].value * 0.001
group_attrs = {"description" : "Intervals that whisker touches pole (retract)",\
"source" : "Intervals are as reported in Simon's data file"}
if len(t) > 0 or not options.handle_errors:
pole_touch_re = create_time_series("pole_touch_retract", "<IntervalSeries>",\
"", orig_h5, pole_iface, group_attrs, '', t, {},\
hash_group_pointer, keyName, options)
elif options.data_origin == "JY":
# JY data
group_attrs = {"source" : "Times as reported in Jianing's data file",
"description" : "Time moment that whisker touches pole"}
num_vars = len(np.array(grp["id/id"]).tolist())
if len(t) > 0:
valueMatrix = np.array(grp["valueMatrix/valueMatrix"])
idStr = np.array(grp["idStr/idStr"])
try:
idStrDetailed = np.array(grp["idStrDetailed/idStrDetailed"])
except:
idStrDetailed = idStr
for i in range(0, num_vars):
var = valueMatrix[i]
series_name = idStr[i]
description = idStrDetailed[i]
whisker_var = create_time_series(series_name, "<TimeSeries>", "", \
orig_h5, whisker_iface, group_attrs, var, t, {},\
hash_group_pointer, keyName, options)
elif options.data_origin == "DG":
keyName = "whiskerVars"
mod.set_custom_dataset("description", \
"Whisker variables: 'Whisker Angle at Base', 'Change in whisker curvature', 'Time of touch onset', 'Time of touch offset' and 'Time points in which a twitch occured'")
grp1 = hash_group_pointer["value/1"]
timestamps = grp1["time/time"]
comment1 = keyName
comment2 = libh5.get_description_by_key(hash_group_pointer, keyName)
comments = comment1 + ": " + comment2
# print("comment1=", comment1, " comment2=", comment2, " comments=", comments
data_attrs={"conversion":1.0, "unit":"unknown", "resolution":float('nan')}
num_vars = len(np.array(grp1["id/id"]).tolist())
key_map = {"thetaAtBase_1_whisker" : "whisker_angle_1", \
"deltaKappa_1_whisker" : "whisker_curvature_1", \
"touch_onset_1_whisker" : "touch_onset_1", \
"touch_offset_1_whisker" : "touch_offset_1", \
"blockMask_1_whisker" : "block_mask_1"}
for i in range(0, num_vars):
var = grp1["valueMatrix/valueMatrix"][:,i]
series_name = grp1["idStr/idStr"][i]
if series_name in key_map.keys():
series_name = key_map[series_name]
description = grp1["idStrDetailed/idStrDetailed"][i]
group_attrs={"description" : description, "comments" : comments, \
"source": "Times as reported in Diego's data file"}
whisker_var = create_time_series(series_name, "<TimeSeries>", "",\
orig_h5, whisker_iface, group_attrs, var, timestamps, data_attrs, \
hash_group_pointer, keyName, options)
# ------------------------------------------------------------------------------
def process_pole_touches(orig_h5, nwb_object, options):
keyName1 = "touches"
keyName2 = "kappaMaxAbsOverTouch"
kappa_ma_pr = libh5.get_value2_by_key2(orig_h5["eventSeriesArrayHash"], keyName1, \
"eventPropertiesHash/1", keyName2)
pole_tp_path = "processing/Whisker/BehavioralEpochs/pole_touch_protract"
if options.handle_errors:
try:
pole_tp_grp = nwb_object.file_pointer[pole_tp_path]
pole_tp_grp.create_dataset("kappa_max_abs_over_touch", data=kappa_ma_pr)
except:
print("Cannot create dataset processing/Whisker/BehavioralTimeSeries/pole_touch_protract/kappa_max_abs_over_touch")
else:
pole_tp_grp = nwb_object.file_pointer[pole_tp_path]
pole_tp_grp.create_dataset("kappa_max_abs_over_touch", data=kappa_ma_pr)
# add kappaMaxAbsOverTouch to pole_touch_retract
kappa_ma_re = libh5.get_value2_by_key2(orig_h5["eventSeriesArrayHash"], keyName1, \
"eventPropertiesHash/2", keyName2)
pole_tr_path = "processing/Whisker/BehavioralEpochs/pole_touch_retract"
try:
pole_tr_grp = nwb_object.file_pointer[pole_tr_path]
pole_tr_grp.create_dataset("kappa_max_abs_over_touch", data=kappa_ma_re)
except:
print("Cannot create dataset processing/Whisker/BehavioralTimeSeries/pole_touch_retract/kappa_max_abs_over_touch")
# ------------------------------------------------------------------------------
def process_stimulus(orig_h5, nwb_object):
keyName = "StimulusPosition"
stim_pos = libh5.get_value_by_key(orig_h5['trialPropertiesHash'], keyName)
trial_t = orig_h5["trialStartTimes/trialStartTimes"].value * 0.001
rate = (trial_t[-1] - trial_t[0])/(len(trial_t)-1)
description = libh5.get_description_by_key(orig_h5["trialPropertiesHash"], keyName)
zts = nwb_object.make_group("<TimeSeries>", "zaber_motor_pos", path="/stimulus/presentation",\
attrs={"description": description})
zts.set_attr("source", "Simon's somatosensory cortex data file")
zts.set_dataset("timestamps", trial_t)
zts.set_dataset("data", stim_pos, attrs={"unit":"unknown",\
"conversion": 1.0, "resolution":1.0})
# ------------------------------------------------------------------------------
def process_intracellular_ephys_data(orig_h5, meta_h5, nwb_object, options):
gg = nwb_object.make_group("general", abort=False)
cellType = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"cellType", "cellType"])[0]
groundCoordinates = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"groundCoordinates", "groundCoordinates"])[0]
identificationMethod = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"identificationMethod", "identificationMethod"])[0]
probeType = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"probeType", "probeType"])[0]
recordingCoordinates = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"recordingCoordinates", "recordingCoordinates"])[0]
recordingLocation = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"recordingLocation", "recordingLocation"])[0][0]
recordingMarker = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"recordingMarker", "recordingMarker" ])[0][0]
recordingType = libh5.get_value_pointer_by_path_items(meta_h5, ["intracellular",\
"recordingType", "recordingType" ])[0][0]
print "recordingType=", recordingType, " recordingMarker=", recordingMarker, " identificationMethod=", identificationMethod
description = "identificationMethod: "+ str(identificationMethod) +\
"\nrecordingMarker: " + str(recordingMarker) +\
"\nrecordingType: " + str(recordingType)
location = "groundCoordinates: " + str(groundCoordinates) + \
"\nrecordingCoordinates: " + str(recordingCoordinates) + \
"\nrecordingLocation: " + str(recordingLocation)
device = "cellType: " + str(cellType) + "\nprobeType: " + str(probeType)
ie = gg.make_group("intracellular_ephys", abort=False, attrs={"description": description})
iex= ie.make_group("<electrode_X>", "electrode")
iex.set_dataset('location', location)
iex.set_dataset('device', device)
ie.set_dataset('filtering', "Bandpass filtered 300-6K Hz")
mod = nwb_object.make_group("<Module>", "IntracellularEphys")
keyName = 'Ephys'
hash_group_pointer = orig_h5['timeSeriesArrayHash']
mod_descr = libh5.get_description_by_key(hash_group_pointer, keyName)
mod.set_attr("description", mod_descr)
# Create interface
ephys_iface = mod.make_group("FilteredEphys", attrs = \
{"source" : "Intracellular ephys data as reported in Jianing's data file"})
# Create time series
grp = libh5.get_value_by_key(hash_group_pointer , keyName)
time = np.transpose(np.array(grp["time/time"]))
t = []
for i in range(time.shape[0]):
t = t + time[i,:].tolist()
source = "Times as reported in Jianing's data file"
num_ts = 0
if len(t) > 0:
valueMatrix = np.array(grp["valueMatrix/valueMatrix"])
idStr = np.array(grp["idStr/idStr"])
try:
idStrDetailed = np.array(grp["idStrDetailed/idStrDetailed"])
except:
idStrDetailed = idStr
num_var = len(idStr)
# print("num_var=", num_var
for i in range(num_var):
var = valueMatrix[i]
series_name = idStr[i]
if options.handle_errors:
try:
electrode_idx = meta_h5["intracellular/recording_coord_location/recording_coord_location"]
except: