-
Notifications
You must be signed in to change notification settings - Fork 0
/
analysis.py
15617 lines (11305 loc) · 625 KB
/
analysis.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
#Code for doing simultaneous imaging and ephys analysis
import struct, array, csv, os
import numpy as np
import matplotlib.pyplot as plt
import time
import random
import glob
import matplotlib.gridspec as gridspec
import matplotlib as mpl
from matplotlib.path import Path
import matplotlib.animation as animation
import scipy.ndimage as ndimage
from scipy.signal import butter, filtfilt, cheby1
from scipy import stats
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from libtfr import * #hermf, dpss, trf_spec <- these are some of the fucntions; for som reason last one can't be explicitly imported
from sklearn import decomposition
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
import multiprocessing
#Smooth and convolve original data to look for flow:
import cv2
import scipy
import scipy.ndimage
import sys
import load_intan_rhd_format
sys.path.append('/home/cat/code/')
import TSF.TSF as TSF
import PTCS.PTCS as PTCS
from numpy import nan
np.set_printoptions(precision=20, threshold=nan, edgeitems=None, suppress=None)
from openglclasses import * #Custom plotting functions
class Object_empty(object):
def __init__(self):
pass
class Probe(object):
def __init__(self):
print "...loading probe..."
self.name = "NeuroNexus 64Ch probe" #Hardwired, but should add options here...
self.load_layout()
def load_layout(self):
''' Load intan probe map layout
'''
self.n_electrodes = 64
#Fixed location array for NeurNexus probe layotus
self.Siteloc = np.zeros((self.n_electrodes*2), dtype=np.int16) #Read as 1D array
for i in range (self.n_electrodes):
self.Siteloc[i*2]=30*(i%2)
self.Siteloc[i*2+1]=i*23
#A64 Omnetics adaptor
adaptor_map = []
adaptor_map.append([34,35,62,33,60,54,57,55,10,8,11,5,32,3,30,31])
adaptor_map.append([64,58,63,56,61,59,52,50,15,13,6,4,9,2,7,1])
adaptor_map.append([53,51,49,47,45,36,37,38,27,28,29,20,18,16,14,12])
adaptor_map.append([48,46,44,42,40,39,43,41,24,22,26,25,23,21,19,17])
adaptor_layout1=[] #Concatenated rows
for maps in adaptor_map:
adaptor_layout1.extend(maps)
#Intan adapter - if inserted right-side up
intan_map = []
intan_map.append(list(reversed([46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16]))) #NB: need to reverse these arrays: list(reversed(...))
intan_map.append(list(reversed([47,45,43,41,39,37,35,33,31,29,27,25,23,21,19,17])))
intan_map.append(list(reversed([49,51,53,55,57,59,61,63,1,3,5,7,9,11,13,15])))
intan_map.append(list(reversed([48,50,52,54,56,58,60,62,0,2,4,6,8,10,12,14])))
intan_layout1=[]
for maps in intan_map:
intan_layout1.extend(maps)
#Intan adapter - if inserted upside-down; no need to reverse
intan_map = []
intan_map.append([48,50,52,54,56,58,60,62,0,2,4,6,8,10,12,14])
intan_map.append([49,51,53,55,57,59,61,63,1,3,5,7,9,11,13,15])
intan_map.append([47,45,43,41,39,37,35,33,31,29,27,25,23,21,19,17])
intan_map.append([46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16])
intan_layout2=[]
for maps in intan_map:
intan_layout2.extend(maps)
#A1x64 probe layout
a = [27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,28,29,30,31,32]
b = [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,36,35,34,33]
probe_map = a+b
probe_map[::2] = a
probe_map[1::2] = b
self.layout = []
for i in range(len(probe_map)):
self.layout.append(intan_layout1[adaptor_layout1.index(probe_map[i])])
#DUPLICATE FUNCTION WITH TSF CLASS FUNCTION; May still need it for stand alone functions; but LIKELY OBSOLETE... ERASE!!!!!!!!!!!!
def save_tsf_single(tsf, file_name):
print "... SAVING single .tsf: ", file_name
fout = open(file_name, 'wb')
fout.write(tsf.header)
fout.write(struct.pack('i', tsf.iformat))
fout.write(struct.pack('i', tsf.SampleFrequency))
fout.write(struct.pack('i', tsf.n_electrodes))
fout.write(struct.pack('i', tsf.n_vd_samples))
fout.write(struct.pack('f', tsf.vscale_HP))
for i in range(tsf.n_electrodes):
fout.write(struct.pack('h', tsf.Siteloc[i*2]))
fout.write(struct.pack('h', tsf.Siteloc[i*2+1]))
#fout.write(struct.pack('i', i+1))
fout.write(struct.pack('i', tsf.Readloc[i]))
for i in range(tsf.n_electrodes):
np.int16(tsf.ec_traces[tsf.layout[i]]).tofile(fout) #Save ec_traces for each channel while converting to int16; the channel order comes from probe
#tsf.ec_traces[i].tofile(fout) #Save ec_traces for each channel while converting to int16; the channel order comes from probe
fout.write(struct.pack('i', tsf.n_cell_spikes))
#Save additional spike information if value non-zero
if tsf.n_cell_spikes!=0:
np.int32(tsf.fake_spike_times).tofile(fout)
np.int32(tsf.fake_spike_assignment).tofile(fout)
np.int32(tsf.fake_spike_channels).tofile(fout)
#Footer information
#number of files saved in tsf;
n_files = len(tsf.file_names) #Save # of files first
np.int32(n_files).tofile(fout)
#Save: name of each file; number of digital channels; digital channels in boolean format
for fname, n_samples, n_dig_chs, dig_chs in zip(tsf.file_names, tsf.n_samples, tsf.n_digital_chs, tsf.digital_chs):
fname = fname+" "*(256-len(fname)) #pack extra spaces
print "...saving file_name: ", fname
fout.write(fname)
fout.write(struct.pack('i', n_samples))
#Save digital channels
print "... # of digital chs: ", n_dig_chs
np.int32(n_dig_chs).tofile(fout) #Save # of digital channels
print "... number of actual saved data streams: ", len(dig_chs)
for ch in range(len(dig_chs)):
print "...xaving ch: ", ch
dig_chs[ch].tofile(fout)
fout.close()
def convert_bin_to_npy(self):
filename = self.parent.root_dir+self.selected_animal+"/tif_files/"+self.selected_recording
print filename
if os.path.exists(filename+'.bin')==False:
print "...loading .bin file..."
data = np.fromfile(file_out+'.bin', dtype=np.int16)
print "...reshaping array..."
data = data.reshape((-1, 128, 128))
print "...saving .npy array..."
np.save(file_out, data)
else:
print "... .npy file already exists..."
def convert_video(self):
print "Loading file: ", self.selected_session
import cv2
print self.parent.animal.home_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.m4v'
vid = cv2.VideoCapture(self.parent.animal.home_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.m4v')
#length = vid.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)
#width = vid.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
#height = vid.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
#fps = vid.get(cv2.cv.CV_CAP_PROP_FPS)
#NB: CAN ALSO INDEX DIRECTLY INTO .WMV FILES:
#time_length = 30.0
#fps=25
#frame_seq = 749
#frame_no = (frame_seq /(time_length*fps))
##The first argument of cap.set(), number 2 defines that parameter for setting the frame selection.
##Number 2 defines flag CV_CAP_PROP_POS_FRAMES which is a 0-based index of the frame to be decoded/captured next.
##The second argument defines the frame number in range 0.0-1.0
#cap.set(2,frame_no);
#print length, width, height, fps
#if length==0: print "... no movie file... returning..."; return
time.sleep(.5)
#Show video
if True:
data = []
ctr=0
now = time.time()
while True:
vid.grab()
retval, image = vid.retrieve()
if not retval: break
#cv2.imshow("Test", image)
#cv2.waitKey(1)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
data.append(image)
ctr+=1; print ctr
np.save(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session, data)
def find_start_end(self):
self.blue_light_filename = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+self.selected_session+'_blue_light_frames.npy'
#if os.path.exists(self.blue_light_filename)==True:
# print "...Blue Light Boundaries already found... returning..."
# return
global coords, images_temp, ax, fig, cid
#Re-Compute frames per second relative session.reclength; ensure makes sense ~15Hz
#First, load movie data
movie_data = np.load(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.npy')
print movie_data.shape
#Second, load imaging data
temp_file = self.parent.root_dir + self.parent.animal.name + '/tif_files/'+self.selected_session+'/'+self.selected_session
print "...loading .npy img file..."
data = np.load(temp_file+'_aligned.npy')
print data.shape
#********Check to see if img_rate was ~30.00Hz; otherwise skip
self.img_rate = np.load(temp_file+'_img_rate.npy') #LOAD IMG_RATE
self.abstimes = np.load(temp_file+'_abstimes.npy')
print "...movie fps: ", float(movie_data.shape[0])/self.abstimes[-1]
#Select pixels from 2 pics: 30th frame and 300th frame; should be able to see light differences
images_temp = movie_data[300]
coords=[]
self.coords = coords
fig = plt.figure()
ax=plt.subplot(1,2,1)
plt.imshow(movie_data[30],cmap=plt.get_cmap('gray') )
ax = plt.subplot(1,2,2)
ax.imshow(images_temp, cmap=plt.get_cmap('gray') )
ax.set_title("Click blue light")
cid = fig.canvas.mpl_connect('button_press_event', on_click_single_frame)
plt.show()
def plot_blue_light_roi(self):
plotting = True
movie_filename = self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.npy'
movie_data = np.load(movie_filename)
print movie_data.shape
t = np.arange(0,movie_data.shape[0],1)/15.
blue_light_roi = []
for k in range(len(movie_data)):
blue_light_roi.append(np.sum(movie_data[k, int(self.coords[0][0])-1:int(self.coords[0][0])+1,
int(self.coords[0][1])-1:int(self.coords[0][1])+1]))
blight_ave = np.average(blue_light_roi)
print "std...", self.blue_light_std.text()
blight_std = np.std(blue_light_roi)*float(self.blue_light_std.text())
print blight_std
if plotting:
ax = plt.subplot(2,1,1)
plt.plot(t, blue_light_roi)
plt.plot([t[0],t[-1]], [blight_ave,blight_ave], color='red')
plt.plot([t[0],t[-1]], [blight_ave-blight_std,blight_ave-blight_std], color='green')
blue_light_roi = np.int32(blue_light_roi)
indexes = np.where(blue_light_roi>(blight_ave-blight_std))[0]
blue_light_roi= blue_light_roi[indexes[0]:indexes[-1]] #SOME OF THE FRAMES DIP BELOW SO JUST ASSUME OK
print indexes[0], indexes[-1]
print "...no of frames w. blue light: ", len(indexes)
movie_rate = float(len(blue_light_roi))/self.abstimes[-1]
print "...movie fps: ", movie_rate
if abs(15-movie_rate)>0.02:
print "************* movie frame rate incorrect *************"
else:
#Save frames for blue light
np.save(self.blue_light_filename, np.arange(indexes[0],indexes[-1],1))
vid_rate_filename = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+self.selected_session+'_vid_rate.npy'
np.savetxt(vid_rate_filename, [movie_rate])
if plotting:
ax = plt.subplot(2,1,2)
plt.plot(blue_light_roi)
plt.ylim(bottom=0)
plt.show()
def event_triggered_movies_multitrial(self):
""" Make multiple mouse lever pull trials video"""
#Load imaging data
temp_file = self.parent.root_dir + self.parent.animal.name + '/tif_files/'+self.selected_session+'/'+self.selected_session
self.img_rate = np.load(temp_file+'_img_rate.npy') #LOAD IMG_RATE
self.abstimes = np.load(temp_file+'_abstimes.npy')
self.abstimes = np.load(temp_file+'_abstimes.npy')
self.abspositions = np.load(temp_file+'_abspositions.npy')
self.abscodes = np.load(temp_file+'_abscodes.npy')
self.locs_44threshold = np.load(temp_file+'_locs44threshold.npy')
self.code_44threshold = np.load(temp_file+'_code44threshold.npy')
print self.abspositions
print self.abscodes
print self.locs_44threshold
print self.code_44threshold
#Load original .npy movie data and index only during blue_light_frames
movie_data = np.load(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.npy')
self.blue_light_filename = self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'_blue_light_frames.npy'
self.movie_data = movie_data[np.load(self.blue_light_filename)]
print "... movie_data.shape: ", self.movie_data.shape
movie_times = np.linspace(0, self.abstimes[-1], self.movie_data.shape[0])
print movie_times
#NB: indexes are not just for '04' codes but for value in selected_code
indexes_04 = np.where(self.code_44threshold==self.selected_code)
times_04 = self.locs_44threshold[indexes_04]
print times_04
#Find movie frame centred on time_index
movie_04frame_locations = []
for time_index in times_04:
movie_04frame_locations.append(find_nearest(movie_times, time_index))
self.movie_04frame_locations = movie_04frame_locations
print "... frame event triggers: ", self.movie_04frame_locations
#Load original .npy movie data and index only during blue_light_frames
print "... movie_data.shape: ", self.movie_data.shape
temp_img_rate = 15
self.movie_stack = []
for frame in self.movie_04frame_locations:
self.movie_stack.append(self.movie_data[frame-3*temp_img_rate: frame+3*temp_img_rate])
make_movies_from_triggers(self)
def make_movies_from_triggers(self):
#***********GENERATE ANIMATIONS
Writer = animation.writers['ffmpeg']
writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=1800)
self.movie_stack = self.movie_stack[:int(self.n_trials_movies.text())]
n_cols = int(np.sqrt(len(self.movie_stack))+0.999999); n_rows = n_cols-1 #Assume on less row needed (always the case unless perfect square
if (n_rows*n_cols)<(len(self.movie_stack)): n_rows = n_cols #If not enough rows, add 1
fig = plt.figure()
im=[]
for k in range(len(self.movie_stack)):
im.append([])
ax = plt.subplot(n_rows,n_cols,k+1)
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im[k] = plt.imshow(self.movie_stack[k][0], cmap=plt.get_cmap('gray'), interpolation='none')
def updatefig(j):
print j
plt.suptitle("Frame: "+str(j)+" " +str(format(float(j)/15-3.,'.2f'))+"sec", fontsize = 20)
# set the data in the axesimage object
for k in range(len(self.movie_stack)):
im[k].set_array(self.movie_stack[k][j])
# return the artists set
return im
# kick off the animation
ani = animation.FuncAnimation(fig, updatefig, frames=range(len(self.movie_stack[0])), interval=100, blit=False, repeat=True)
if True:
ani.save(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'_'+str(len(self.movie_stack))+'.mp4', writer=writer)
plt.show()
def behavioural_stack(self):
#Load behaviour camera and annotations data - if avialable
if os.path.exists(self.vid_rate_filename):
#********** Load Annotations ********
print "... making stacks of annotation arrays ...",
areas = ['_lick', '_lever'] #, '_pawlever', '_lick', '_snout', '_rightpaw', '_leftpaw', '_grooming']
annotation_arrays = []
for ctr, area in enumerate(areas):
annotation_arrays.append([])
for k in range(len(self.movie_data)): annotation_arrays[ctr].append([])
#data = np.load(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+area+'_clusters.npz')
data = np.load(self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+self.selected_session+area+'_clusters.npz')
cluster_indexes=data['cluster_indexes']
cluster_names=data['cluster_names']
for k in range(len(cluster_indexes)):
for p in range(len(cluster_indexes[k])):
annotation_arrays[ctr][cluster_indexes[k][p]] = cluster_names[k]
annotation_arrays[ctr] = np.array(annotation_arrays[ctr])[self.movie_indexes]
self.annotation_arrays=[]
for k in range(len(annotation_arrays)): #***************************** SAME DUPLICATION AS ABOVE; Video is 15Hz, imaging is 30Hz
self.annotation_arrays.append([])
for p in range(len(annotation_arrays[k])):
self.annotation_arrays[k].append(annotation_arrays[k][p])
self.annotation_arrays[k].append(annotation_arrays[k][p])
self.annotation_stacks = []
print "...making annotation_stacks..."
areas = ['_Tongue', '_Lever'] #, '_pawlever', '_lick', '_snout', '_rightpaw', '_leftpaw', '_grooming']
for k in range(len(self.annotation_arrays[0])):
#print k
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
#ax.tick_params(axis='both', which='both', labelsize=30)
#plt.title(self.annotation_arrays[0][k]+'_'+self.annotation_arrays[1][k], fontsize=40)
for p in range(len(self.annotation_arrays)):
ax.text(-10, p*20+30, areas[p][1:]+': '+self.annotation_arrays[p][k], fontsize=40, fontweight='bold')
#print areas[p][1:]+': '+self.annotation_arrays[p][k]
ax.set_ylim(0,len(self.annotation_arrays)*20+20)
ax.set_xlim(0,120)
ax.axis('off')
#ax.plot(x_val[:k],y_val[:k], linewidth=3)
#ax.set_ylim(0,120)
#ax.set_xlim(0,len(self.movie_stack))
canvas.draw() # draw the canvas, cache the renderer
data = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
self.annotation_stacks.append(data)
print "...behavioural stack done..."
plt.close()
else:
print "... behavioural video data doesn't exist ... "
self.annotation_stacks = []
self.movie_stack = np.zeros((len(self.ca_stack[0]), 30, 40), dtype=np.int8)
filesave = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+ \
self.selected_session+'_'+self.selected_code+'_'+self.selected_trial+'_annotation_stack'
np.save(filesave, self.annotation_stacks)
#conn.send(self.annotation_stacks)
#conn.close()
def calcium_stack(self):
if self.selected_dff_filter == 'nofilter':
self.traces_filename = self.parent.animal.home_dir+self.parent.animal.name+'/tif_files/'+self.selected_session+'/'+self.selected_session+"_"+ \
str(self.parent.n_sec)+"sec_"+ self.selected_dff_filter+'_' +self.dff_method+'_'+str(self.selected_code)+"code_stm.npy"
else:
self.traces_filename = self.parent.animal.home_dir+self.parent.animal.name+'/tif_files/'+self.selected_session+'/'+self.selected_session+"_"+ \
str(self.parent.n_sec)+"sec_" + self.selected_dff_filter + "_"+self.dff_method+'_'+self.parent.filter_low.text()+"hz_"+self.parent.filter_high.text()+"hz_"+str(self.selected_code)+"code_stm.npy"
print "...stm_name: ", self.traces_filename
data = np.load(self.traces_filename, mmap_mode='c')[int(self.selected_trial)] #Load only selected trial
print data.shape
self.data_norm = []
self.ca_stack = []
n_stacks = 2
for k in range(n_stacks):
self.ca_stack.append([])
self.ca_stack[0] = data
#Normalize data; opencv functions largely work on unit8 data types
#img_rate = 30.0
#start_time = float(self.stm_start_time.text()); end_time = float(self.stm_end_time.text())
#for k in range(int(img_rate*(3+start_time)),int(img_rate*(3+end_time)), 1):
for k in range(len(data)):
data_norm = ((data[k]-np.min(data[k]))/(np.max(data[k])-np.min(data[k]))*255).astype(np.uint8) #Normalize data to gray scale 0..255
#data_norm = (data[k]-np.min(data[k]))/(np.max(data[k])-np.min(data[k]))*2. - 1. #Normalize to: -1.. 0 .. +1 scale
self.data_norm.append(data_norm)
self.data_norm = np.array(self.data_norm)
self.data_norm_ave = np.average(self.data_norm, axis = 0)
filter_power = float(self.mask_power.text())
for k in range(len(self.data_norm)):
stack_ctr = 1
sigma=2
img_arctan = np.ma.arctanh((self.data_norm[k]-128.)/128.)
data_neg = -1. * np.ma.clip(img_arctan, -100., 0)
data_neg = -np.ma.power(data_neg, filter_power)
data_pos = np.ma.clip(img_arctan, 0, 100.)
data_pos = np.ma.power(data_pos, filter_power)
data_total = np.float32(data_neg + data_pos)
#img_uint8 = ((data_total-np.min(data_total))/(np.max(data_total)-np.min(data_total))*255.).astype(np.uint8)
img_gaussian = ndimage.gaussian_filter(data_total, sigma=sigma) #Recentre image around zero
#negatives = np.clip(img_gaussian, -1E-6, 1E-6)/1E-6
#data_out = np.power(np.ma.abs(img_gaussian), filter_power)*negatives
self.ca_stack[stack_ctr].append(img_gaussian); stack_ctr+=1
#kernel_5pix = np.ones((5,5),np.float32)/5.
#data_out = cv2.filter2D(self.data_norm[k],-1,kernel_5pix)
#self.ca_stack[stack_ctr].append(data_out); stack_ctr+=1
#sigma = 10
#data_out = ndimage.gaussian_filter(self.data_norm[k], sigma=sigma)
#self.ca_stack[stack_ctr].append(data_out); stack_ctr+=1
#sx = scipy.ndimage.sobel(data_out.astype(np.uint8), axis=0, mode='nearest')
#sy = scipy.ndimage.sobel(data_out.astype(np.uint8), axis=1, mode='nearest')
#data_out = np.hypot(sx, sy)
#self.ca_stack[stack_ctr].append(data_out); stack_ctr+=1
#Remove averages from the smoothed stacks;
#self.ca_stack[2] = self.ca_stack[2] - np.average(self.ca_stack[2], axis=0)
#self.ca_stack[2] = self.ca_stack[2] - np.average(self.ca_stack[2], axis=0)
#np.save(self.traces_filename[:-4] + "_Ca_stacks" , self.ca_stack) #SAVE ARRAYS BEFORE MASKING
temp_stack = self.ca_stack #Save for loading below
#Apply Generic Mask
print "...selected trial for stm: ", self.selected_trial
for k in range(len(self.ca_stack)):
self.ca_stack[k] = quick_mask(self, self.ca_stack[k])
#Last and apply Motion Mask
filename_motion_mask = self.traces_filename.replace('_traces.npy','')[:-4]+'_motion_mask.npy'
print filename_motion_mask
if os.path.exists(filename_motion_mask)==False:
print "...motion mask missing..."
return
else:
motion_mask = np.load(filename_motion_mask)
for k in range(len(self.ca_stack)):
self.ca_stack[k] = self.ca_stack[k] * motion_mask
self.ca_stack = np.ma.array(self.ca_stack)
print "...self.ca_stack.shape: ", self.ca_stack.shape
#************************************************************************************************************
#**************************************** PCA SPACE CALCIUM IMAGING PANEL ***********************************
#************************************************************************************************************
data = temp_stack[0]
subsampled_array = []
for k in range(len(data)):
subsampled_array.append(scipy.misc.imresize(data[k], .9, interp='bilinear', mode=None))
methods = ['MDS', 'tSNE', 'PCA', 'Sammon']
method = methods[2]
print "... computing original dim reduction ..."
X = []
for k in range(len(subsampled_array)):
X.append(np.ravel(subsampled_array[k]))
X = PCA_reduction(X, n_components=3)
cm = plt.cm.get_cmap('jet')
colors = range(len(X))
self.pca_stack = []
print "... making pca_stack..."
for k in range(len(data)):
#print k
fig = Figure()
canvas = FigureCanvas(fig)
#ax = fig.gca()
fig.set_size_inches(10, 10)
#fig = plt.figure(1, figsize=(4, 3))
plt.clf()
#ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
ax = Axes3D(fig, rect=[0, 0, 1, 1], elev=48, azim=134)
#ax.scatter(X[:, 0], X[:, 1], X[:, 2], c = colors, cmap=plt.cm.spectral)
ax.scatter(X[:k+1, 0], X[:k+1, 1], X[:k+1, 2], s =200, c = colors[:k+1], cmap=cm)
if k>1: ax.plot3D (X[:k, 0], X[:k, 1], X[:k,2])
ax.w_xaxis.set_ticklabels([])
ax.w_yaxis.set_ticklabels([])
ax.w_zaxis.set_ticklabels([])
ax.set_xlim(np.min(X[:, 0])-1, np.max(X[:, 0])+1)
ax.set_ylim(np.min(X[:, 1])-1, np.max(X[:, 1])+1)
ax.set_zlim(np.min(X[:, 2])-1, np.max(X[:, 2])+1)
canvas.draw() # draw the canvas, cache the renderer
data = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
self.pca_stack.append(data)
print "...done pca_stack..."
plt.close()
filesave = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+ \
self.selected_session+'_'+self.selected_code+'_'+self.selected_trial
np.save(filesave+'_ca_stack', np.ma.filled(self.ca_stack, np.nan))
#self.ca_stack.dump(filesave+'_ca_stack')
np.save(filesave+'_pca_stack', self.pca_stack)
#self.ca_stack.dump(filesave+'_ca_stack')
def lever_position_stack(self):
lever_file = self.temp_file+'_abspositions.npy'
times_file = self.temp_file+'_abstimes.npy'
lever_data = np.load(lever_file)
times_data = np.load(times_file)
start_index = find_nearest(times_data, self.selected_locs_44threshold)
#print start_index, times_data[start_index]
#Initialize lever_stack and find indexes in lever_data @~120Hz that match 30Hz sampling rate; both img_rates should be saved to disk so can use exact vals
#self.lever_stack = np.zeros((self.movie_stack.shape[0], 120, self.movie_stack.shape[0]), dtype=np.float32)+255
self.lever_stack = []
#Make plots and convert to img stack
x_val = []
y_val = []
for k in range(len(self.movie_stack)):
x_val.append(k)
#y_val.append(lever_data[int(start_index+k*4-self.movie_stack.shape[0]/2*4)])
y_val.append(abs(lever_data[int(start_index+k*(120./self.img_rate)-self.movie_stack.shape[0]/2*(120./self.img_rate))]))
print y_val
print "... making stacks of lever pull panels..."
for k in range(len(self.movie_stack)):
#print k
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
ax.tick_params(axis='both', which='both', labelsize=45)
old_xlabel = np.linspace(0,len(self.movie_stack), 2*int(self.n_sec_window.text()))
new_xlabel = np.around(np.linspace(-int(self.n_sec_window.text()), int(self.n_sec_window.text()), 2*int(self.n_sec_window.text())), decimals=2)
ax.set_xticks(old_xlabel)
ax.set_xticklabels(new_xlabel)
ax.plot([0,len(self.movie_stack)], [10, 10], color = 'black', linewidth=2, alpha = 0.8)
ax.plot([0,len(self.movie_stack)], [34, 34], 'r--', color = 'blue', linewidth=3, alpha = 0.8)
ax.plot([0,len(self.movie_stack)], [60, 60], color = 'blue', linewidth=2, alpha = 0.8)
ax.plot(x_val[:k],y_val[:k], linewidth=6)
ax.set_ylim(0,120)
ax.set_xlim(0,len(self.movie_stack))
canvas.draw() # draw the canvas, cache the renderer
data = np.fromstring(canvas.tostring_rgb(), dtype='uint8')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
self.lever_stack.append(data)
print "...done lever stack..."
plt.close()
filesave = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+ \
self.selected_session+'_'+self.selected_code+'_'+self.selected_trial+'_lever_stack'
np.save(filesave, self.lever_stack)
def event_triggered_movies_single_Ca(self):
""" Load [Ca] imaging and behavioural camera data and align to selected trial"""
self.parent.n_sec = float(self.n_sec_window.text())
self.start_time = -self.parent.n_sec; self.end_time = self.parent.n_sec
self.temp_file = self.parent.root_dir + self.parent.animal.name + '/tif_files/'+self.selected_session+'/'+self.selected_session
self.abstimes = np.load(self.temp_file+'_abstimes.npy')
self.img_rate = np.load(self.temp_file+'_img_rate.npy') #imaging rate
#Process reward triggered data
if (self.selected_code =='02') or (self.selected_code =='04') or (self.selected_code =='07'):
self.locs_44threshold = np.load(self.temp_file+'_locs44threshold.npy')
self.code_44threshold = np.load(self.temp_file+'_code44threshold.npy')
indexes = np.where(self.code_44threshold==self.selected_code)[0]
print "...indexes: "; print indexes
self.code_44threshold = self.code_44threshold[indexes] #Select only indexes that match the code selected
self.locs_44threshold = self.locs_44threshold[indexes]
#Process behaviour triggered data;
else:
load_behavioural_annotation_data(self)
print len(self.code_44threshold)
print len(self.locs_44threshold)
print "...self.selected_code: ", self.selected_code
print "...self.selected_trial: ", self.selected_trial
self.selected_locs_44threshold = self.locs_44threshold[int(self.selected_trial)] #selected_locs should already have been selected above
self.selected_code_44threshold = self.code_44threshold[int(self.selected_trial)]
print self.selected_locs_44threshold
print self.selected_code_44threshold
#****************************** Load behaviour video ******************************
#Load behaviour camera and annotations data - if avialable
self.vid_rate_filename = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+self.selected_session+'_vid_rate.npy'
print "...loading behavioural camera data..."
if os.path.exists(self.vid_rate_filename):
self.vid_rate = np.loadtxt(self.vid_rate_filename)
#Load original movie data and index only during blue_light_frames
movie_data = np.load(self.parent.root_dir+self.parent.animal.name+"/video_files/"+self.selected_session+'.npy', mmap_mode='c')
self.blue_light_filename = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+self.selected_session+'_blue_light_frames.npy'
self.movie_data = movie_data[np.load(self.blue_light_filename)]
#Find movie frame corresponding to lever pull trigger
movie_times = np.linspace(0, self.abstimes[-1], self.movie_data.shape[0])
self.movie_04frame_locations = find_nearest(movie_times, self.selected_locs_44threshold)
print "... frame event triggers: ", self.movie_04frame_locations
#Make movie stack
self.movie_indexes = np.arange(self.movie_04frame_locations+int(-self.parent.n_sec*self.vid_rate-1), self.movie_04frame_locations+int(self.parent.n_sec*self.vid_rate+1), 1)
self.movie_stack = self.movie_data[self.movie_indexes]
#self.movie_stack = self.movie_data[self.movie_04frame_locations+int(-self.parent.n_sec*self.vid_rate-1): self.movie_04frame_locations+int(self.parent.n_sec*self.vid_rate+1)]
#print len(self.movie_stack)
#quit()
#Duplicate movie stack to match [Ca] imaging rate #******************NB INTERPOLATION IS KIND OF HARDWIRED TO 30HZ & 15HZ.... PERHAPS THIS CAN SKIP FRAME SOMETIMES !?!
new_stack = []
for frame in range(len(self.movie_stack)):
new_stack.append(self.movie_stack[frame])
#new_stack.append((np.int16(self.movie_stack[frame])+np.int16(self.movie_stack[frame+1]))/2.) #Interpolation, maybe not use it.
new_stack.append(self.movie_stack[frame])
#new_stack.append(self.movie_stack[-1]); new_stack.append(self.movie_stack[-1])
self.movie_stack = np.uint8(new_stack)
print self.movie_stack.shape
else:
print "... behavioural video data doesn't exist ... "
self.movie_stack = np.zeros((len(self.ca_stack[0]), 30, 40), dtype=np.int8)
#*************************************************************************************************************
#Process stacks in parallel - save data to disk
procs=[]
procs.append(multiprocessing.Process(target=behavioural_stack, args=(self,)))
procs.append(multiprocessing.Process(target=calcium_stack, args=(self,)))
procs.append(multiprocessing.Process(target=lever_position_stack, args=(self,)))
map(lambda x: x.start(), procs)
map(lambda x: x.join(), procs)
#*******************************************************************************************************
#Load processed data from disk
filesave = self.parent.root_dir+self.parent.animal.name+"/tif_files/"+self.selected_session+'/'+ \
self.selected_session+'_'+self.selected_code+'_'+self.selected_trial
self.annotation_stacks = np.load(filesave+'_annotation_stack.npy')
self.ca_stack = np.load(filesave+'_ca_stack.npy', allow_pickle=True)
self.pca_stack = np.load(filesave+'_pca_stack.npy')
self.lever_stack = np.load(filesave+'_lever_stack.npy')
print "... len pca_stack: ", len(self.pca_stack)
print "... len ca_stack: ", len(self.ca_stack)
#Make movies
make_movies_ca(self)
def make_movies_ca(self):
#***********GENERATE ANIMATIONS
Writer = animation.writers['ffmpeg']
writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=15000)
fig = plt.figure()
im = []
#gs = gridspec.GridSpec(2,len(self.ca_stack)*2)
gs = gridspec.GridSpec(4,6)
#[Ca] stacks
titles = ["GCamp6s Activity", "GCamp6s (z-Tranformed)"]
for k in range(len(self.ca_stack)):
ax = plt.subplot(gs[0:2,k*2:k*2+2])
plt.title(titles[k], fontsize = 12)
v_max = np.nanmax(np.ma.abs(self.ca_stack[k])); v_min = -v_max
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im.append(plt.imshow(self.ca_stack[k][0], vmin=v_min, vmax = v_max, cmap=plt.get_cmap('jet'), interpolation='none'))
#PCA stack
ax = plt.subplot(gs[0:2,4:])
plt.title("PCA State Space", fontsize = 12)
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im.append(plt.imshow(self.pca_stack[0], cmap=plt.get_cmap('gray'), interpolation='none'))
#Camera stack
ax = plt.subplot(gs[2:4,0:4])
plt.title("Behavioural Camera", fontsize = 12)
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im.append(plt.imshow(self.movie_stack[0], cmap=plt.get_cmap('gray'), interpolation='none'))
#Lever position trace
ax = plt.subplot(gs[2:3,4:])
plt.title("Lever Position", y = .95 , fontsize = 10)
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im.append(plt.imshow(self.lever_stack[0], cmap=plt.get_cmap('gray'), interpolation='none'))
#Annotation Stck
ax = plt.subplot(gs[3:4,4:])
plt.title("Annotations", y = .95 , fontsize = 10)
ax.get_xaxis().set_visible(False); ax.yaxis.set_ticks([]); ax.yaxis.labelpad = 0
im.append(plt.imshow(self.annotation_stacks[0], cmap=plt.get_cmap('gray'), interpolation='none'))
#Loop to combine all video insets into 1
print "...making final video..."
def updatefig(j):
print "...frame: ", j
#plt.suptitle(self.selected_dff_filter+' ' +self.dff_method + "\nFrame: "+str(j)+" " +str(format(float(j)/self.img_rate-self.parent.n_sec,'.2f'))+"sec ", fontsize = 15)
plt.suptitle("Time: " +str(format(float(j)/self.img_rate-self.parent.n_sec,'.2f'))+"sec Frame: "+str(j), fontsize = 15)
# set the data in the axesimage object
ctr=0
for k in range(len(self.ca_stack)):
im[ctr].set_array(self.ca_stack[k][j]); ctr+=1
im[ctr].set_array(self.pca_stack[j]); ctr+=1
im[ctr].set_array(self.movie_stack[j]); ctr+=1
im[ctr].set_array(self.lever_stack[j]); ctr+=1
im[ctr].set_array(self.annotation_stacks[j]); ctr+=1
# return the artists set
return im
# kick off the animation
ani = animation.FuncAnimation(fig, updatefig, frames=range(len(self.movie_stack)), interval=100, blit=False, repeat=True)
#ani = animation.FuncAnimation(fig, updatefig, frames=range(len(self.ca_stack[1])), interval=100, blit=False, repeat=True)
if True:
#ani.save(self.parent.root_dir+self.parent.animal.name+"/movie_files/"+self.selected_session+'_'+str(len(self.movie_stack))+'_'+str(self.selected_trial)+'trial.mp4', writer=writer, dpi=300)
ani.save(self.parent.root_dir+self.parent.animal.name+"/movie_files/"+self.selected_session+'_'+str(self.selected_code)+"_"+str(self.selected_trial)+'trial.mp4', writer=writer, dpi=600)
plt.show()
def annotate_movies(self):
''' Make annotated movies
'''
#Constants for processing
n_frames = 21000 #Number of frames of video to process
video_rate = 15. #Video rate in Hz.
self.parent.n_sec = float(self.n_sec_window.text())
self.start_time = -self.parent.n_sec; self.end_time = self.parent.n_sec
self.temp_file = self.parent.root_dir + self.parent.animal.name + '/tif_files/'+self.selected_session+'/'+self.selected_session
self.abstimes = np.load(self.temp_file+'_abstimes.npy')
self.img_rate = np.load(self.temp_file+'_img_rate.npy') #imaging rate
#****************** LOAD RAW VIDEO ***********************
#movie_raw = np.load(self.temp_file+'.m4v')
#movie_raw = np.load(self.parent.root_dir + self.parent.animal.name + '/tif_files/'+self.selected_session+'/movie.npy', mmap_mode='r')
#print movie_raw.shape
movie_stack = []
n_movie_frames = 20000
if True:
camera = cv2.VideoCapture(self.temp_file+'.m4v')
#Find 200th frame in video: #Save cropped raw image into .npy array
ctr = 0
while ctr<n_movie_frames:
(grabbed, frame) = camera.read()
ctr+=1
movie_stack.append(cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY))
print ctr
#image_original = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
#image_original_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
#************************ PROCESS ANNOTATIONS *********************
#Process reward triggered data
self.locs_44threshold = np.load(self.temp_file+'_locs44threshold.npy')
self.code_44threshold = np.load(self.temp_file+'_code44threshold.npy')
indexes = np.where(self.code_44threshold=="02")[0]
self.locs_02 = self.locs_44threshold[indexes]
indexes = np.where(self.code_44threshold=="04")[0]
self.locs_04 = self.locs_44threshold[indexes]
indexes = np.where(self.code_44threshold=="07")[0]
self.locs_07 = self.locs_44threshold[indexes]
print self.locs_02[:10],"...", self.locs_02[-10:]
#print self.locs_04
#print self.locs_07
self.locs_annotated = []
for annotated_cluster in self.annotated_clusters:
self.locs_annotated.append(load_behavioural_annotation_data_all(self, annotated_cluster))
print self.locs_annotated[0][:10],"...", self.locs_annotated[0][-10:]
print self.locs_annotated[1][:10],"...", self.locs_annotated[1][-10:]
print self.locs_annotated[2][:10],"...", self.locs_annotated[2][-10:]
#Make matrix for plotting
annotated_matrix = np.zeros((6,n_frames), dtype=np.float32)
#Shift time of behaviours based on blue_light data
blue_light_index = np.load(self.temp_file+'_blue_light_frames.npy')[0] #load number of video frames at which excitation light starts
#Extend reward codes over 1second; mostly onwards from time of code; save for about 8 behavioural imaging frames ~=500ms
for k in range(0,8,1):
annotated_matrix[0][np.int32(self.locs_02*video_rate)+k+blue_light_index] = 1