-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1662 lines (1274 loc) · 61.3 KB
/
utils.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
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.sparse import issparse, spdiags, coo_matrix, csc_matrix
from past.utils import old_div
from scipy.ndimage.measurements import center_of_mass
import tifffile as tiff
import os, sys
import matplotlib.gridspec as gridspec
import scipy.io as sio
import matplotlib.patches as mpatches
try:
import bokeh
import bokeh.plotting as bpl
from bokeh.models import CustomJS, ColumnDataSource, Range1d
except:
print("Bokeh could not be loaded. Either it is not installed or you are not running within a notebook")
def run_foopsi(root):
file_name= root.data.file_name
data = np.load(file_name)
traces = data['traces'].T
centres = data['cm']
print (centres[0])
print (len(traces))
lengths_filename = os.path.split(root.data.file_name)[0]+'/all_lengths.txt'
lengths = np.loadtxt(lengths_filename,dtype=np.int32)
#lengths = [3000,3500,3500,3000,3000,3000]
#import imp
#cm = imp.load_source('caiman', '/home/cat/code/CaImAn/')
caiman_path = np.loadtxt('caiman_folder_location.txt', dtype=str)
sys.path.append(str(caiman_path)+'/')
import caiman as cm
from caiman.source_extraction.cnmf.deconvolution import constrained_foopsi
c_array = []
foopsi_traces = []
if False: #Run deconvolution on entire trace for each neuron
for n, trace in enumerate(traces):
print (" ... cell: ", n)
temp_c = []
temp_raster = []
#c, bl, c1, g, sn, sp, lam = constrained_foopsi(trace,method = 'cvxpy', p=1)
c, bl, c1, g, sn, sp, lam = constrained_foopsi(trace, p=1)
temp_c.extend(c)
temp_raster.extend(sp)
c_array.append(temp_c)
foopsi_traces.append(temp_raster)
else: #This runs deconvolution chunkwise and setsbaseline based on mean of the input traces - to account for differences in light intensity across frames...
for n, trace in enumerate(traces):
print (" ... cell (chunks): ", n)
temp_c = []
temp_raster = []
for l in range(len(lengths)): #loop over all lengths of recording
#print (np.sum(lengths[0:l]), np.sum(lengths[0:l+1]))
trace_chunk = trace[np.sum(lengths[0:l]):np.sum(lengths[0:l+1])]
#plt.plot(trace_chunk)
trace_chunk = trace_chunk + abs(np.mean(trace_chunk))
#plt.plot(trace_chunk)
#plt.show(block=True)
c, bl, c1, g, sn, sp, lam = constrained_foopsi(trace_chunk,p=1)
temp_c.extend(c)
temp_raster.extend(sp)
c_array.append(temp_c)
foopsi_traces.append(temp_raster)
foopsi_traces = np.array(foopsi_traces)
c_array=np.array(c_array)
#Compute
print ("...extracting binary rasters...")
rasters = []
threshold = float(root.data.foopsi_threshold)
for k in range(len(foopsi_traces)):
indexes = np.where(foopsi_traces[k]>threshold)[0]
rasters.append(indexes)
np.savez(file_name[:-4]+"_deconvolved_data_thr"+str(root.data.foopsi_threshold), original_traces=traces, deconvolved_traces=c_array, foopsi_probabilities=foopsi_traces, rasters=rasters, centres=centres)
sio.savemat(file_name[:-4]+'_deconvolved_data_thr'+str(root.data.foopsi_threshold)+'.mat', {'original_traces':traces, 'deconvolved_traces':c_array, 'foopsi_probabilities':foopsi_traces,'rasters':rasters,'centres':centres})
def view_rasters(root):
print ("...View rasters ...")
colors=['blue','red', 'green', 'violet','lightseagreen','lightsalmon','dodgerblue','mediumvioletred','indianred','lightsalmon','pink','darkolivegreen']
root.deconvolved_filename = root.data.file_name[:-4]+"_deconvolved_data_thr"+str(root.data.foopsi_threshold)+".npz"
data = np.load(root.deconvolved_filename)
rasters = data['rasters']
traces = data['original_traces']
print (rasters.shape)
#Load filenames and lengths
all_names = np.loadtxt(os.path.split(root.data.file_name)[0]+'/all_names.txt', dtype='str')
all_lengths = np.loadtxt(os.path.split(root.data.file_name)[0]+'/all_lengths.txt')
ax=plt.subplot(1,1,1)
ofset=0
for k in range(len(rasters)):
ymin=np.zeros(len(rasters[k]))+k
ymax=np.zeros(len(rasters[k]))+k+0.8
plt.vlines(rasters[k], ymin, ymax, linewidth=1, colors=colors[k%12], alpha=1) #colors[mod(counter,7)])
#plt.vlines(rasters[k], ymin, ymax, linewidth=1, colors='blue', alpha=1) #colors[mod(counter,7)])
ctr=0
ctr_sum = []
#Shade each recording block
for k in range(0,len(all_lengths),2):
print (all_lengths[k])
#ax.axvspan(ctr, ctr+all_lengths[k+1], ymin=0, ymax=200, alpha=0.03, color='black')
ax.axvspan(ctr, ctr+10, ymin=0, ymax=200, alpha=1, color='black')
ctr+=all_lengths[k]
ax.axvspan(ctr, ctr+10, ymin=0, ymax=200, alpha=1, color='black')
ctr_sum.append(ctr)
ctr+=all_lengths[k+1]
ctr_sum.append(ctr)
plt.xlim(-1,len(traces[0])+1)
plt.ylim(-1,len(rasters)+1)
plt.xlabel("Frames", fontsize=25)
plt.ylabel("Neuron ID", fontsize=25)
ax.tick_params(axis='both', which='both', labelsize=25)
#ax.set_xticklabels(np.array(ctr_sum)-ctr_sum[0], all_names, rotation=17, fontsize=6)
plt.xticks(np.array(ctr_sum)-ctr_sum[0], all_names, rotation=17, fontsize=6)
#ax2 = ax.twiny()
#plt.xticks(all_names,rotation=17, fontsize=6)
print (ctr_sum)
print (all_names)
#plt.yticks(np.int16(range(0,21*output.scale,output.scale))+output.scale/2, all_names)
plt.suptitle(root.deconvolved_filename+" (Foopsi threshold: "+str(root.data.foopsi_threshold)+")", fontsize=15)
plt.show()
def view_neuron(root):
print ("...viewing neuron: ", root.data.neuron_id)
data = np.load(root.data.file_name[:-4]+"_deconvolved_data_thr"+str(root.data.foopsi_threshold)+".npz")
original_traces=data['original_traces']
deconvolved_traces=data['deconvolved_traces']
foopsi_probabilities=data['foopsi_probabilities']
centres=data['centres']
fig = plt.figure()
ax=plt.subplot(1,1,1)
#mng = plt.get_current_fig_manager()
#mng.resize(*mng.window.maxsize())
print (foopsi_probabilities[root.data.neuron_id])
print (root.data.foopsi_threshold)
spikes = np.where(foopsi_probabilities[root.data.neuron_id]>float(root.data.foopsi_threshold))[0]
print (spikes)
#spikes = np.where(derivative>(der_std*3))[0]
ax.vlines(spikes,[-25],[-50])
plt.plot([0,len(original_traces[root.data.neuron_id])], [float(root.data.foopsi_threshold),float(root.data.foopsi_threshold)], 'r--', linewidth=2, color='red', alpha=0.7)
plt.plot(original_traces[root.data.neuron_id])
plt.plot(deconvolved_traces[root.data.neuron_id])
plt.plot(foopsi_probabilities[root.data.neuron_id])
plt.xlim(0,len(original_traces[root.data.neuron_id]))
plt.title("Cell: "+str(root.data.neuron_id), fontsize=20)
plt.xlabel("Frames", fontsize=20)
plt.ylabel("DF/F", fontsize=20)
ax.tick_params(axis='both', which='both', labelsize=20)
#Legend
blue_patch = mpatches.Patch(color='blue')
orange_patch = mpatches.Patch(color='orange')
green_patch = mpatches.Patch(color='green')
labels = ['Raw', 'Deconvolved', 'Foopsi']
ax.legend([blue_patch, orange_patch, green_patch], labels, fontsize=12, loc=0,
title="")
plt.show()
def convert_tif_npy(file_name):
images = tiff.imread(file_name)
np.save(file_name[:-4], images)
tiff.imsave(file_name[:-4]+"_500frames.tif", images[:500])
np.save(file_name[:-4]+"_500frames.npy", images[:500])
def merge_tifs(file_name):
''' Merge tifs;
Important to also save names of files for later loading and size of each chunk in frames
'''
print ("...merging tifs ...")
filenames = np.loadtxt(file_name, dtype='str')
img_array = []
names = []
lengths = []
for filename in filenames:
data_temp = tiff.imread(filename)
print ("...loading: ", filename, " size: ", data_temp.shape)
lengths.append(len(data_temp))
names.append(os.path.split(filename)[1])
img_array.append(data_temp)
img_array = np.vstack(img_array)
print (img_array.shape)
print ("...saving tif...")
tiff.imsave(file_name[:-4]+'_all.tif', img_array)
print ("...saving npy version...")
np.save(file_name[:-4]+'_all.npy', img_array)
np.save(file_name[:-4]+'_all_names.npy', names)
np.save(file_name[:-4]+'_all_lengths.npy', lengths)
print ("...done saving tiffs/npy...")
def load_tif_sequence(file_name):
import glob
filenames = sorted(glob.glob(file_name))
print ("... # files: ", len(filenames))
print ("... loading tiffs...")
image_array = []
for filename in filenames:
image_array.append(tiff.imread(filename))
image_array = np.array(image_array)
np.save(file_name[:-1]+"_all.npy", image_array)
tiff.imsave(file_name[:-1]+"_all.tif", image_array)
#np.save(file_name[:-4]+"_500frames.npy", images[:500])
def crop_image(file_name):
global coords, ax, fig1, cid, fname,image_stack, single_frame #IS THIS Global declaration unsafe for other functions?
print ("... reading tif...")
image_stack = tiff.imread(file_name)
single_frame = image_stack[0].copy()
fname = file_name
#image_temp = image_stack[0].copy()
fig1, ax = plt.subplots()
coords=[]
ax.imshow(image_stack[0])#, vmin=0.0, vmax=0.02)
ax.set_title("Click on top left and bottom right of area to crop")
cid = fig1.canvas.mpl_connect('button_press_event', on_click)
plt.show()
def on_click(event):
global coords, image_temp, ax, fig1, cids, image_stack, single_frame #IS THIS Global declaration unsafe for other functions?
if event.inaxes is not None:
coords.append((event.ydata, event.xdata))
print (coords)
for j in range(len(coords)):
for k in range(3):
for l in range(3):
single_frame[int(coords[j][0]-1+k)][int(coords[j][1])-1+l]=np.max(single_frame)
ax.imshow(single_frame)
fig1.canvas.draw()
else:
plt.close()
fig1.canvas.mpl_disconnect(cid)
print ("...saving cropped .tif...")
x_coords = np.int32(np.sort([coords[0][0], coords[1][0]]))
y_coords = np.int32(np.sort([coords[0][1], coords[1][1]]))
print (x_coords, y_coords)
tiff.imsave(fname[:-4]+"_cropped.tif", image_stack[:, x_coords[0]:x_coords[1], y_coords[0]: y_coords[1]])
np.save(fname[:-4]+"_cropped.npy", image_stack[:, x_coords[0]:x_coords[1], y_coords[0]: y_coords[1]])
print ("...done...")
#Must do operations here... tkinter doesn't play nice with other parts
ax = plt.subplot(1,1,1)
ax.imshow(single_frame[x_coords[0]:x_coords[1], y_coords[0]: y_coords[1]])
plt.show()
print ("...exiting...")
def motion_correct_caiman(root):
fname = root.data.file_name
# motion correction parameters
niter_rig = 1 # number of iterations for rigid motion correction
max_shifts = (6, 6) # maximum allow rigid shift
splits_rig = 56 # for parallelization split the movies in num_splits chuncks across time
strides = (48, 48) # start a new patch for pw-rigid motion correction every x pixels
overlaps = (24, 24) # overlap between pathes (size of patch strides+overlaps)
splits_els = 30 # for parallelization split the movies in num_splits chuncks across time
upsample_factor_grid = 4 # upsample factor to avoid smearing when merging patches
max_deviation_rigid = 3 # maximum deviation allowed for patch with respect to rigid shifts
#%% start a cluster for parallel processing
caiman_path = np.loadtxt('caiman_folder_location.txt', dtype=str) #<------------ is this necessary still?
sys.path.append(str(caiman_path)+'/')
print (caiman_path)
import caiman as cm
c, dview, n_processes = cm.cluster.setup_cluster(backend='local', n_processes=None, single_thread=False)
#min_mov = cm.load(fname, subindices=range(200)).min()
if 'tif' in fname:
all_mov = tiff.imread(fname)
else:
all_mov = np.load(fname)
print (all_mov.shape)
#return
min_mov = all_mov.min()
# this will be subtracted from the movie to make it non-negative
from caiman.motion_correction import MotionCorrect
mc = MotionCorrect(fname, min_mov,
dview=dview, max_shifts=max_shifts, niter_rig=niter_rig,
splits_rig=splits_rig,
strides= strides, overlaps= overlaps, splits_els=splits_els,
upsample_factor_grid=upsample_factor_grid,
max_deviation_rigid=max_deviation_rigid,
shifts_opencv = True, nonneg_movie = True)
mc.motion_correct_rigid(save_movie=False,template = None)
new_templ = mc.total_template_rig
dview.terminate()
#print np.array(mc.fname_tot_rig).shape
#print np.array(mc.total_template_rig).shape
#print np.array(mc.templates_rig).shape
#print np.array(mc.shifts_rig).shape
np.savetxt(fname[:-4]+"_shifts_rig.txt",mc.shifts_rig)
print ("... shifting image stack based on motion correction...")
reg_mov = np.zeros(all_mov.shape, dtype=np.uint16)
for k in range(len(all_mov)):
print (int(mc.shifts_rig[k][0]), int(mc.shifts_rig[k][1]))
reg_mov[k] = np.roll(np.roll(all_mov[k], int(mc.shifts_rig[k][0]), axis=0), int(mc.shifts_rig[k][1]), axis=1)
np.save(fname[:-4]+"_registered.npy", reg_mov)
try:
from libtiff import TIFF
tiff_out = TIFF.open(fname[:-4]+"_registered.tif", mode='w')
tiff_out.write_image(reg_mov)
tiff_out.close()
except:
print ("Tiff too large, need to install libtiff to save to disk (only saving .npy version.")
#import imageio
#imageio.mimwrite(fname[:-4]+"_registered_fps10.mp4", reg_mov, fps = 10)
fig1 = plt.figure()
ax=plt.subplot()
plt.title("New_template", fontsize=20)
ax.imshow(new_templ, cmap='gray')
plt.savefig(fname[:-4]+"_registered.png")
plt.title("new_template", fontsize=20)
plt.imshow(new_templ, cmap='gray')
plt.show()
def louvain_compute(root):
print ("...Louvain modularity computation")
import community
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import os
def corr2_coeff(A,B):
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean(1)[:,None]
# Sum of squares across rows
ssA = (A_mA**2).sum(1);
ssB = (B_mB**2).sum(1);
# Finally get corr coeff
return np.dot(A_mA,B_mB.T)/np.sqrt(np.dot(ssA[:,None],ssB[None]))
#Load original data
file_name = root.data.file_name
data = np.load(file_name)
rasters = data['rasters']
traces = data['original_traces']
print (rasters.shape)
print (rasters[0])
#Load filenames and lengths
all_names = np.loadtxt(os.path.split(file_name)[0]+'/all_names.txt', dtype='str')
all_lengths = np.loadtxt(os.path.split(file_name)[0]+'/all_lengths.txt')
print (all_lengths)
cumulative_lengths = []
ctr=0
cumulative_lengths.append(ctr)
for length in all_lengths:
ctr+=length; cumulative_lengths.append(ctr)
print (rasters[0])
cumulative_lengths = np.int32(cumulative_lengths)
print (cumulative_lengths)
#Convert rasters into milisecond precise time serios
rasters_binarized = np.zeros((len(rasters),int(np.sum(all_lengths))),dtype=np.int8)
for k in range(len(rasters)):
rasters_binarized[k][np.int32(rasters[k])]=1
print (rasters_binarized)
#Compute session wise correlation matrices
from scipy import stats
corr_arrays = []
for s in range(len(cumulative_lengths)-1):
ind1 = cumulative_lengths[s]
ind2 = cumulative_lengths[s+1]
print (ind1, ind2)
#for k in range(len(rasters_binarized)):
# corr_array.append([])
# for p in range(k,len(rasters_binarized),1):
# corr_array[k].append(stats.pearsonr(rasters_binarized[k][ind1:ind2], rasters_binarized[p][ind1:ind2]))
#print rasters_binarized[:,ind1:ind2].shape
#img = np.corrcoef(rasters_binarized[:,ind1:ind2], rasters_binarized[:,ind1:ind2])
corr_arrays.append(corr2_coeff(rasters_binarized[:,ind1:ind2], rasters_binarized[:,ind1:ind2]))
#print len(corr_array)
#Load matrix into a networkx graph
network_array = []
for corr_array in corr_arrays:
#G = np.random.rand(100,100)
G = corr_array-np.min(corr_array)
#G = G/np.max(G)/100
G = nx.Graph(G)
print ("...# edges: ", G.number_of_edges())
print ("...# nodes: ", G.number_of_nodes())
#first compute the best partition
partition = community.best_partition(G)
print (len(partition.values()))
#print partition.values()
#print partition.keys()
#drawing
size = float(len(set(partition.values())))
#print size
pos = nx.spring_layout(G)
count = 0.
colors=np.array(['red','orange','yellow','green','cyan','blue','indigo','violet'])[::-1]
plotting = False
list_nodes_array = []
for com in set(partition.values()) :
#for com in [6,7,8]:
#count = count + 1.
count = com
list_nodes = [nodes for nodes in partition.keys()
if partition[nodes] == com]
print (com, len(list_nodes))
list_nodes_array.append(list_nodes)
if plotting:
nx.draw_networkx_nodes(G, pos, list_nodes, node_size = 25+ np.exp(com), #com/float(size)*1000,
node_color = 'blue',alpha=.5)
print (list_nodes_array)
if plotting:
nx.draw_networkx_edges(G, pos, alpha=0.25)
plt.show()
network_array.append(list_nodes_array)
np.save(file_name[:-4]+"_networks", network_array)
def visualize_louvain(root):
print ("...loading processed file: ", root.data.file_name)
#Load ROI countour data first
index = root.data.file_name.find("processed_ROIs")
ROI_fname = root.data.file_name[:index+14]+".npz"
data_in = np.load(ROI_fname, encoding= 'latin1', mmap_mode='c')
Bmat_array = data_in['Bmat_array']
cm = data_in['cm'] #Centre of mass
thr_array = data_in['thr_array'] #Threshold array original data, usually 0.2
traces = data_in['traces'] #
x_array = data_in['x_array']
y_array = data_in['y_array']
colors='b'
#Second, load louvain network info:
network_array = np.load(root.data.file_name)
for n in range(0,len(network_array),2):
print ("... epoch: ", n)
#Plot first recording
index_array=[]
for k in range(len(network_array[n])-3,len(network_array[n]),1):
index_array.extend(network_array[n][k])
unique_indexes=np.unique(index_array)
print ("...# neurons: ", len(unique_indexes))
thr_fixed=.5
ax=plt.subplot(1,2,1)
for i, (y,x,Bmat,thr) in enumerate(zip(y_array,x_array,Bmat_array,thr_array)):
if i in unique_indexes:
cs = plt.contour(y, x, Bmat, [thr_fixed], colors=colors)
#Plot second recording same day
index_array=[]
for k in range(len(network_array[n+1])-3,len(network_array[n+1]),1):
index_array.extend(network_array[n+1][k])
unique_indexes=np.unique(index_array)
print ("...# neurons: ", len(unique_indexes))
thr_fixed=.5
ax=plt.subplot(1,2,2)
for i, (y,x,Bmat,thr) in enumerate(zip(y_array,x_array,Bmat_array,thr_array)):
if i in unique_indexes:
cs = plt.contour(y, x, Bmat, [thr_fixed], colors=colors)
plt.show()
def About():
tkMessageBox.showinfo("About", "CaImAn Ver 1.0 ...")
def com(A, d1, d2):
"""Calculation of the center of mass for spatial components
Inputs:
------
A: np.ndarray
matrix of spatial components (d x K)
d1: int
number of pixels in x-direction
d2: int
number of pixels in y-direction
Output:
-------
cm: np.ndarray
center of mass for spatial components (K x 2)
"""
from past.utils import old_div
nr = np.shape(A)[-1]
Coor = dict()
Coor['x'] = np.kron(np.ones((d2, 1)), np.expand_dims(list(range(d1)), axis=1))
Coor['y'] = np.kron(np.expand_dims(list(range(d2)), axis=1), np.ones((d1, 1)))
cm = np.zeros((nr, 2)) # vector for center of mass
cm[:, 0] = old_div(np.dot(Coor['x'].T, A), A.sum(axis=0))
cm[:, 1] = old_div(np.dot(Coor['y'].T, A), A.sum(axis=0))
return cm
def plot_contours(A, Cn, thr=None, thr_method='max', maxthr=0.2, nrgthr=0.9, display_numbers=True, max_number=None,
cmap=None, swap_dim=False, colors='w', vmin=None, vmax=None, **kwargs):
"""Plots contour of spatial components against a background image and returns their coordinates
Parameters:
-----------
A: np.ndarray or sparse matrix
Matrix of Spatial components (d x K)
Cn: np.ndarray (2D)
Background image (e.g. mean, correlation)
thr_method: [optional] string
Method of thresholding:
'max' sets to zero pixels that have value less than a fraction of the max value
'nrg' keeps the pixels that contribute up to a specified fraction of the energy
maxthr: [optional] scalar
Threshold of max value
nrgthr: [optional] scalar
Threshold of energy
thr: scalar between 0 and 1
Energy threshold for computing contours (default 0.9)
Kept for backwards compatibility. If not None then thr_method = 'nrg', and nrgthr = thr
display_number: Boolean
Display number of ROIs if checked (default True)
max_number: int
Display the number for only the first max_number components (default None, display all numbers)
cmap: string
User specifies the colormap (default None, default colormap)
Returns:
--------
Coor: list of coordinates with center of mass, contour plot coordinates and bounding box for each component
"""
if issparse(A):
A = np.array(A.todense())
else:
A = np.array(A)
if swap_dim:
Cn = Cn.T
print('Swapping dim')
d1, d2 = np.shape(Cn)
d, nr = np.shape(A)
print ("# neurons: ", nr)
if max_number is None:
max_number = nr
#if thr is not None:
# thr_method = 'nrg'
# nrgthr = thr
# warn("The way to call utilities.plot_contours has changed. Look at the definition for more details.")
x, y = np.mgrid[0:d1:1, 0:d2:1]
ax = plt.gca()
if vmax is None and vmin is None:
plt.imshow(Cn, interpolation=None, cmap=cmap,
vmin=np.percentile(Cn[~np.isnan(Cn)], 1), vmax=np.percentile(Cn[~np.isnan(Cn)], 99))
else:
plt.imshow(Cn, interpolation=None, cmap=cmap,
vmin=vmin, vmax=vmax)
coordinates = []
cm = com(A, d1, d2)
for i in range(np.minimum(nr, max_number)):
print (i)
pars = dict(kwargs)
if thr_method == 'nrg':
indx = np.argsort(A[:, i], axis=None)[::-1]
cumEn = np.cumsum(A[:, i].flatten()[indx]**2)
cumEn /= cumEn[-1]
Bvec = np.zeros(d)
Bvec[indx] = cumEn
thr = nrgthr
else: # thr_method = 'max'
if thr_method != 'max':
warn("Unknown threshold method. Choosing max")
Bvec = A[:, i].flatten()
Bvec /= np.max(Bvec)
thr = maxthr
if swap_dim:
Bmat = np.reshape(Bvec, np.shape(Cn), order='C')
else:
Bmat = np.reshape(Bvec, np.shape(Cn), order='F')
cs = plt.contour(y, x, Bmat, [thr], colors=colors)
# this fix is necessary for having disjoint figures and borders plotted correctly
p = cs.collections[0].get_paths()
v = np.atleast_2d([np.nan, np.nan])
for pths in p:
vtx = pths.vertices
num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :]))
if num_close_coords < 2:
if num_close_coords == 0:
# case angle
newpt = np.round(old_div(vtx[-1, :], [d2, d1])) * [d2, d1]
#import ipdb; ipdb.set_trace()
vtx = np.concatenate((vtx, newpt[np.newaxis, :]), axis=0)
else:
# case one is border
vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0)
#import ipdb; ipdb.set_trace()
v = np.concatenate((v, vtx, np.atleast_2d([np.nan, np.nan])), axis=0)
pars['CoM'] = np.squeeze(cm[i, :])
pars['coordinates'] = v
pars['bbox'] = [np.floor(np.min(v[:, 1])), np.ceil(np.max(v[:, 1])),
np.floor(np.min(v[:, 0])), np.ceil(np.max(v[:, 0]))]
pars['neuron_id'] = i + 1
coordinates.append(pars)
if display_numbers:
for i in range(np.minimum(nr, max_number)):
if swap_dim:
ax.text(cm[i, 0], cm[i, 1], str(i + 1), color=colors)
else:
ax.text(cm[i, 1], cm[i, 0], str(i + 1), color=colors)
plt.show()
return coordinates
def PointsInCircum(r,n=100):
import math
from math import pi
return [(math.cos(2*pi/n*x)*r,math.sin(2*pi/n*x)*r) for x in xrange(0,n+1)]
#************************* GUI TO CORRECT ROIS; USING EXISTING CAIMAN CODE *******************
def correct_ROIs(file_name, A, Cn, thr=None, thr_method='max', maxthr=0.2, nrgthr=0.9, display_numbers=True, max_number=None,
cmap=None, swap_dim=False, colors='grey', vmin=None, vmax=None, **kwargs):
"""Plots contour of spatial components against a background image and returns their coordinates
Parameters:
-----------
A: np.ndarray or sparse matrix
Matrix of Spatial components (d x K)
Cn: np.ndarray (2D)
Background image (e.g. mean, correlation)
thr_method: [optional] string
Method of thresholding:
'max' sets to zero pixels that have value less than a fraction of the max value
'nrg' keeps the pixels that contribute up to a specified fraction of the energy
maxthr: [optional] scalar
Threshold of max value
nrgthr: [optional] scalar
Threshold of energy
thr: scalar between 0 and 1
Energy threshold for computing contours (default 0.9)
Kept for backwards compatibility. If not None then thr_method = 'nrg', and nrgthr = thr
display_number: Boolean
Display number of ROIs if checked (default True)
max_number: int
Display the number for only the first max_number components (default None, display all numbers)
cmap: string
User specifies the colormap (default None, default colormap)
Returns:
--------
Coor: list of coordinates with center of mass, contour plot coordinates and bounding box for each component
"""
global nearest_cell, previous_cell, l_width, ylim_max, ylim_min, y_array, x_array, Bmat_array, thr_array, traces, cm, img1, images_kalman, color_selected, img_data, ax, ax2, ax3, add_cell_flag
if issparse(A):
A = np.array(A.todense())
else:
A = np.array(A)
if swap_dim:
Cn = Cn.T
print('Swapping dim')
d1, d2 = np.shape(Cn)
d, nr = np.shape(A)
print ("# neurons: ", nr)
if max_number is None:
max_number = nr
#if thr is not None:
# thr_method = 'nrg'
# nrgthr = thr
# warn("The way to call utilities.plot_contours has changed. Look at the definition for more details.")
x, y = np.mgrid[0:d1:1, 0:d2:1]
def reload_data():
global cm, traces, images_kalman
cm = com(A, d1, d2)
#print Cn.shape
#print file_name
print (file_name.replace("_processed.npz",'.npy'))
images_kalman = np.load(file_name.replace("_processed.npz",'.npy'))
print (images_kalman.shape)
traces = np.load(file_name[:-4]+"_traces.npy")
print (traces.shape)
reload_data()
#************* PLOT AVERAGE DATA MOVIES ************
from matplotlib.widgets import Slider, Button, RadioButtons
#fig, ax = plt.subplots()
fig = plt.figure()
#mng = plt.get_current_fig_manager()
#mng.resize(*mng.window.maxsize())
gs = gridspec.GridSpec(2,4)
#ax1 = plt.subplot(self.gs[0:2,0:2])
#Setup neuron rasters plot
f0 = 0
l_width=1
ylim_max=500
ylim_min=-200
previous_cell=0
add_cell_flag=False
nearest_cell=(previous_cell+1)
img_data = images_kalman
print (img_data.shape)
#ax=plt.subplot(1,2,1)
ax = plt.subplot(gs[0:2,0:2])
img1 = ax.imshow(img_data[0], cmap='viridis')
#BOTTOM TRACES
ax2 = plt.subplot(gs[1:2,2:4])
img2, = ax2.plot(traces[:,0])
plt.ylim(-50,400)
plt.xlim(0,len(images_kalman))
#TOP TRACES
ax3 = plt.subplot(gs[0:1,2:4])
img3, = ax3.plot(traces[:,0])
plt.ylim(-50,400)
plt.xlim(0,len(images_kalman))
#SLIDER WINDOW
axcolor = 'lightgoldenrodyellow'
axframe = plt.axes([0.12, 0.02, 0.35, 0.03])#, facecolor=axcolor)
frame = Slider(axframe, 'frame', 0, len(img_data), valinit=f0)
#********* PRELOAD CONTOUR VALS **************
y_array=[]
x_array=[]
Bmat_array=[]
thr_array=[]
thr_method == 'nrg'
colors_white='w'
#cm = cm[:nr]
#for i in range(np.minimum(nr, max_number)):
for k in range(nr):
#for k in range(10): #this index matches Bokeh plot numbering
i=k
print ("cell: ", k, " coords: ", cm[i,1],cm[i,0])
pars = dict(kwargs)
if thr_method == 'nrg':
indx = np.argsort(A[:, i], axis=None)[::-1]
cumEn = np.cumsum(A[:, i].flatten()[indx]**2)
cumEn /= cumEn[-1]
Bvec = np.zeros(d)
Bvec[indx] = cumEn
thr = nrgthr
else: # thr_method = 'max'
if thr_method != 'max':
warn("Unknown threshold method. Choosing max")
Bvec = A[:, i].flatten()
Bvec /= np.max(Bvec)
thr = maxthr
#if swap_dim:
# Bmat = np.reshape(Bvec, np.shape(Cn), order='C')
#else:
Bmat = np.reshape(Bvec, np.shape(Cn), order='F')
y_array.append(y)
x_array.append(x)
thr_array.append(thr)
Bmat_array.append(Bmat)
cs = ax.contour(y, x, Bmat, [thr], linewidth=l_width, colors=colors)
#ax.text(cm[i, 1], cm[i, 0], str(i + 1), color=colors)
ax.text(cm[i, 1], cm[i, 0], str(i), color=colors_white)
Bmat_array = np.array(Bmat_array)
thr_array = np.array(thr_array)
y_array = np.array(y_array)
x_array = np.array(x_array)
#***********************************************************************************
#**************************** REDRAW TRACES FUNCTION ******************************
#***********************************************************************************
def redraw_traces():
''' Function to redraw traces on right panels; called by various tools
'''
global nearest_cell, previous_cell, l_width, ylim_max, ylim_min, y_array, x_array, Bmat_array, thr_array, traces, cm, img1, img_data, ax, ax2, ax3
#********** PREVIOUS NEURON ************
ax3.cla()
ax3.plot([int(frame.val),int(frame.val)],[ylim_min,ylim_max])
ax3.set_ylim(ylim_min, ylim_max)
ax3.set_title("Cell: "+str(previous_cell), fontsize=15)
ax3.set_xlim(0,len(traces))
#Plot original traces
ax3.plot(traces[:,previous_cell]+50, color='red', alpha=0.8)
#Plot spikes
derivative = traces[:,previous_cell][1:]-traces[:,previous_cell][:-1]
der_std = np.std(derivative)
spikes = np.where(derivative>(der_std*3))[0]
ax3.vlines(spikes,[0],[-100])
#************** CURRENT NEURON *********
ax2.cla()
ax2.set_ylim(ylim_min, ylim_max)
ax2.plot([int(frame.val),int(frame.val)],[ylim_min,ylim_max])
ax2.set_title("Cell: "+str(nearest_cell), fontsize=15)
ax2.set_xlim(0,len(traces))
#Plot original traces
ax2.plot(traces[:,nearest_cell]+50, color='blue', alpha=0.8)
#Plot spikes
#temp_trace = traces[:,nearest_cell]
#derivative = temp_trace[1:]-temp_trace[:-1]
#derivative = np.gradient(traces[:,nearest_cell])
#der_std = np.std(derivative)
#ax2.plot(derivative)
#spikes = np.where(derivative>(der_std*3))[0]
#ax2.plot([0,len(traces)], [der_std*3,der_std*3], 'r--', color='red')
#ax2.vlines(spikes,[0],[-100])
fig.canvas.draw()
#***********************************************************************************
#**************************** RESET FUNCTION **************************************
#***********************************************************************************
def reset_function():
''' Reset function called by various buttons to redraw everything
'''
global nearest_cell, previous_cell, l_width, ylim_max, ylim_min, y_array, x_array, Bmat_array, thr_array, traces, cm, img1, img_data, ax, ax2, ax3
print ("...reset function called ...")
print ("...nearest_cell: ", nearest_cell)
print ("...previous_cell: ", previous_cell)
#******* Redraw movie panel
ax.cla()
img1 = ax.imshow(img_data[0], cmap=color_selected)#, interpolation='sinc')
for c in range(len(x_array)):
ax.contour(y_array[c], x_array[c], Bmat_array[c], [thr_array[c]], colors=colors)
ax.text(cm[c, 1], cm[c, 0], str(c), color=colors_white)
ax.set_title("# Cells: "+str(len(x_array)), fontsize=15)
#*************** DRAW NEW CONTROUS **************
ax.contour(y_array[previous_cell], x_array[previous_cell], Bmat_array[previous_cell], [thr_array[previous_cell]], linewidths=l_width, colors='red',alpha=0.9)
ax.contour(y_array[nearest_cell], x_array[nearest_cell], Bmat_array[nearest_cell], [thr_array[nearest_cell]], linewidths=l_width, colors='blue',alpha=0.9)
redraw_traces()
#***********************************************************************************
#**************************** SELECT NEURON BUTTON *********************************
#***********************************************************************************
def callback(event):
''' This function finds the nearest neuron to the mouse click location
'''
global nearest_cell, previous_cell, l_width, ylim_max, ylim_min, y_array, x_array, Bmat_array, thr_array, traces, cm, img1, img_data, ax, ax2, ax3, add_cell_flag
if event.inaxes is not None:
print ("...button press: ", event.ydata, event.xdata)
if ax !=event.inaxes:
print (" click outside image box ")
return
print (" click inside image box ")