-
Notifications
You must be signed in to change notification settings - Fork 3
/
oevent.py
2491 lines (2393 loc) · 107 KB
/
oevent.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
"""
OEvent: Oscillation event detection and feature analysis.
oevent.py - main entry point
Written by Sam Neymotin ([email protected]) & Idan Tal ([email protected])
References: Taxonomy of neural oscillation events in primate auditory cortex
https://doi.org/10.1101/2020.04.16.045021
"""
from pylab import *
from scipy import ndimage
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
from scipy.interpolate import interp1d
import sys,os,numpy,scipy,subprocess
from math import ceil
from scipy.stats.stats import pearsonr
from filter import lowpass,bandpass,bandstop
from multiprocessing import Pool
from scipy.signal import decimate, find_peaks
import pickle
import h5py
from morlet import MorletSpec
import matplotlib.patches as mpatches
from nhpdat import *
from hecogdat import rdecog, rerefavg
from csd import *
from lc import lagged_coherence # for quantifying rhythmicity
from collections import OrderedDict
import scipy.signal as sps
from evstats import *
import gc # garbage collector
from cyc import getcyclefeatures, getcyclekeys
from bbox import bbox, p2d
import pandas as pd
from scipy.stats import chi2
tl = tight_layout
rcParams['lines.markersize'] = 15
rcParams['lines.linewidth'] = 4
# rcParams['font.size'] = 25
chan = 12 # pick a granular layer
noiseampLFP = 200.0 # 125.0 # amplitude cutoff for LFP noise -- not really used
noiseampCSD = 200.0 / 10.0 # amplitude cutoff for CSD noise; was 200 before units fix
noiseampBIP = 200.0 / 100.0 # amplitude cutoff for BIP noise (BIP ~10X smaller than CSD)
# get frequencies of interest + bandwidths for filtering
def getlfreqwidths (minf=0.5,maxf=125.0,step=0.5):
lfreq=arange(minf,maxf,step); lfwidth=[]
off=0.0
if minf < 1.0: off = 0.5 - log2(minf) # min freq get
lfwidth = [log2(f) + off for f in lfreq] # logarithmic + shift
return lfreq,lfwidth
#
def getlfreq (freqmin,freqmax,getinc=False):
dinc = {'delta':0.25,'theta':0.5,'alpha':1.0,'beta':1.0,'lgamma':1.0,'gamma':1.0,'hgamma':1.0}
freqcur = freqmin
lfreq = [freqcur]
inc = dinc[getband(freqcur)]
linc = [inc]
while freqcur < freqmax:
b = getband(freqcur)
if b in dinc: inc = dinc[b]
linc.append(inc)
freqcur += inc
lfreq.append(freqcur)
if getinc:
return lfreq,linc
else:
return lfreq
# get logarithmically spaced frequencies
def getloglfreq (freqmin,freqmax,minstep,getstep=False):
off = 0.0
freqcur = freqmin
lfreq = [freqcur]
l2fc = log2(freqcur)
if l2fc < 0.:
freqstep = minstep
else:
freqstep = l2fc
lfreqstep = [freqstep]
while freqcur < freqmax:
l2fc = log2(freqcur)
if l2fc < 0.:
freqstep = minstep
else:
freqstep = l2fc
freqcur += freqstep
lfreq.append(freqcur)
lfreqstep.append(freqstep)
if getstep:
return lfreq,lfreqstep
else:
return lfreq
def index2ms (idx, sampr): return 1e3*idx/sampr
def ms2index (ms, sampr): return int(sampr*ms/1e3)
ion() # interactive mode for pylab
#
def plotspec (T,F,S,vc=[],newFig=False,cbar=False,ax=None):
if len(vc) == 0: vc = [amin(S), amax(S)]
if newFig: figure();
if ax is None: ax=gca()
print(amin(T),amax(T),amin(F),amax(F))
ax.imshow(S,extent=[amin(T),amax(T),amin(F),amax(F)],origin='lower',aspect='auto',vmin=vc[0],vmax=vc[1],cmap=plt.get_cmap('jet'));
if cbar: ax.colorbar();
ax.set_xlabel('Time (s)'); ax.set_ylabel('Frequency (Hz)');
#
def slicenoise (arr,F,minF=58,maxF=62):
sidx,eidx = -1,-1
for i in range(len(arr)):
if F[i] >= minF and sidx == -1:
sidx = i
if F[i] >= maxF and eidx == -1:
eidx = i
return numpy.append(arr[0:sidx+1], arr[eidx+1:len(arr)])
#
def plotsigwavecut (sig,sampr,freqmax=100,thresh=1.0):
dt = 1.0 / sampr
ms = MorletSpec(sig,sampr,freqmin=1.0,freqmax=freqmax,freqstep=1.0)
ll,nl = blobcut(ms.TFR,np.mean(ms.TFR)+thresh*np.std(ms.TFR));
subplot(3,1,1)
ttt = linspace(0,len(sig)*dt,len(sig))
plot(ttt,sig-mean(sig))
xlim((ttt[0],ttt[-1]))
subplot(3,1,2)
imshow(ms.TFR,extent=[ttt[0], ttt[-1], ms.f[0], ms.f[-1]], aspect='auto', origin='lower',cmap=plt.get_cmap('jet'))
xlabel('Time (s)'); ylabel('Frequency (Hz)');
subplot(3,1,3)
plotspec(ttt,ms.f,ll)
return ms,ll,nl
#
def slicenoisebycol (arr2D,F,minF=58,maxF=62):
aout = []
for i in range(arr2D.shape[1]):
aout.append(slicenoise(arr2D[:,i],F,minF,maxF))
tmp = numpy.zeros( (len(aout[0]), len(aout) ) )
for i in range(len(aout)):
tmp[:,i] = aout[i]
return tmp
#
def keepF (arr,F,minF=25,maxF=55):
sidx,eidx = -1,-1
for i in range(len(arr)):
if F[i] >= minF and sidx == -1:
sidx = i
if F[i] >= maxF and eidx == -1:
eidx = i
return numpy.array(arr[sidx:eidx+1])
#
def keepFbycol (arr2D,F,minF=25,maxF=55):
aout = []
for i in range(arr2D.shape[1]):
aout.append(keepF(arr2D[:,i],F,minF,maxF))
tmp = numpy.zeros( (len(aout[0]), len(aout) ) )
for i in range(len(aout)):
tmp[:,i] = aout[i]
return tmp
#
def checknoise (dat,winsz,sampr,noiseamp=noiseampCSD):
lnoise = [];
n,sz = len(dat),len(dat)
for sidx in range(0,sz,winsz):
eidx = sidx + winsz
if eidx >= sz: eidx = sz - 1
print(sidx,eidx)
sig = dat[sidx:eidx]
lnoise.append(max(abs(sig)) > noiseamp)
return lnoise
# get morlet specgrams on windows of dat time series (window size in samples = winsz)
def getmorletwin (dat,winsz,sampr,freqmin=1.0,freqmax=100.0,freqstep=1.0,\
noiseamp=noiseampCSD,getphase=False,useloglfreq=False,mspecwidth=7.0):
lms = []
n,sz = len(dat),len(dat)
lnoise = []; lsidx = []; leidx = []
if useloglfreq:
minstep=0.1
loglfreq = getloglfreq(freqmin,freqmax,minstep)
for sidx in range(0,sz,winsz):
lsidx.append(sidx)
eidx = sidx + winsz
if eidx >= sz: eidx = sz - 1
leidx.append(eidx)
print(sidx,eidx)
sig = dat[sidx:eidx]
lnoise.append(max(abs(sig)) > noiseamp)
if useloglfreq:
ms = MorletSpec(sig,sampr,freqmin=freqmin,freqmax=freqmax,freqstep=freqstep,getphase=getphase,lfreq=loglfreq,width=mspecwidth)
else:
ms = MorletSpec(sig,sampr,freqmin=freqmin,freqmax=freqmax,freqstep=freqstep,getphase=getphase,width=mspecwidth)
lms.append(ms)
return lms,lnoise,lsidx,leidx
def hstacklmsTFR (lms):
# concatenates the windowed spectrogram horizontally
return np.hstack([ms.TFR for ms in lms])
# median normalization
def mednorm (dat,byRow=True):
nrow,ncol = dat.shape[0],dat.shape[1]
out = zeros((nrow,ncol))
if byRow:
for row in range(nrow):
med = median(dat[row,:])
if med != 0.0:
out[row,:] = dat[row,:] / med
else:
out[row,:] = dat[row,:]
else:
for col in range(ncol):
med = median(dat[:,col])
if med != 0.0:
out[:,col] = dat[:,col] / med
else:
out[:,col] = dat[:,col]
return out
# sub average div std normalization
def unitnorm (dat,byRow=True):
nrow,ncol = dat.shape[0],dat.shape[1]
out = zeros((nrow,ncol))
if byRow:
for row in range(nrow):
avg = np.mean(dat[row,:])
std = np.std(dat[row,:])
out[row,:] = dat[row,:] - avg
if std != 0.0:
out[row,:] /= std
else:
for col in range(ncol):
avg = np.mean(dat[:,col])
std = np.std(dat[:,col])
out[:,col] = dat[:,col] - avg
if std != 0.0:
out[:,col] /= std
return out
# sub min div by max
def unitnorm1D (dat):
mn = np.amin(dat)
out = (dat - mn)
mx = np.amax(out)
if mx != 0.0: out = out / mx
return out
# maximum filter on an image
# from https://stackoverflow.com/questions/27598103/what-is-the-difference-between-imregionalmax-of-matlab-and-scipy-ndimage-filte
def maxfilt (dat,sz=3):
lm = scipy.ndimage.filters.maximum_filter(dat,size=sz)
msk = (dat == lm) # convert local max values to binary mask
return msk
# simple 2D peak finding
def simple2Dpeak (dat,sz=1):
pkx,pky=[],[]
nrow,ncol = dat.shape[0],dat.shape[1]
for y in range(sz,nrow-sz,1):
if y % 100 == 0: print('.')
for x in range(sz,ncol-sz,1):
ispk = True
for y0 in range(y-sz,y+sz+1,1):
for x0 in range(x-sz,x+sz+1,1):
if dat[y][x] < dat[y0][x0]:
ispk = False
break
if ispk:
pkx.append(x)
pky.append(y)
return pkx,pky
# cut out the individual blobs via thresholding and component labeling
def blobcut (im,thresh):
mask = im > thresh
labelim, nlabels = ndimage.label(mask)
return labelim, nlabels
# binarize image (im) using a different threshold (lthresh) for each row
def blobcutlines (im,lthresh):
lmask = []
for row,th in enumerate(lthresh):
mask = im[row] >= thresh
lmask.append(mask)
mask = np.array(lmask)
labelim, nlabels = ndimage.label(mask)
return labelim, nlabels
# draw a line
def drline (x0,x1,y0,y1,clr,w,ax=None):
if ax is None: ax=gca()
ax.plot([x0,x1],[y0,y1],clr,linewidth=w)
#
def drbox (x0,x1,y0,y1,clr,w,ax=None):
# draw a box
drline(x0,x0,y0,y1,clr,w,ax)
drline(x1,x1,y0,y1,clr,w,ax)
drline(x0,x1,y0,y0,clr,w,ax)
drline(x0,x1,y1,y1,clr,w,ax)
# get threshold that minimizes bimodal variance
def getminbimodalvarthresh (arr,minprct=0.1,maxprct=0.9,nlevel=10,draw=False):
minval = amin(arr)
maxval = amax(arr)
rng = maxval - minval
lthresh = linspace(minprct*rng+minval,maxprct*rng+minval,nlevel)
lstd0,lstd1,lstdA=[],[],[]
lthreshused = []
for thresh in lthresh:
x0 = [x for x in arr if x < thresh]
x1 = [x for x in arr if x >= thresh]
if len(x0) <= 0 or len(x1) <= 0: continue
lstd0.append(np.std(x0))
lstd1.append(np.std(x1))
lstdA.append((lstd0[-1]+lstd1[-1])/2.0)
lthreshused.append(thresh)
if draw:
plot(lthresh,lstd0,'r');plot(lthresh,lstd0,'ro')
plot(lthresh,lstd1,'b');plot(lthresh,lstd1,'bo')
plot(lthresh,lstdA,'k');plot(lthresh,lstdA,'ko')
#print(lstdA)
return lthreshused[np.argmin(np.array(lstdA))],lthreshused,lstd0,lstd1,lstdA
# container for convenience - wavelet info from a single sample
class WaveletInfo:
def __init__ (self,phs=0.0,idx=0,T=0.0,val=0.0):
self.phs=phs
self.idx=idx
self.T=T
self.val=val
#
class evblob(bbox):
""" event blob class, inherits from bbox
"""
NoneVal = -1e9
def __init__ (self):
self.avgpowevent=0 # avg val during event but only including suprathreshold pixels
self.avgpow=self.avgpoworig=0 # avg val during event bounds
self.cmass=evblob.NoneVal
self.maxval=self.maxpos=self.maxvalorig=evblob.NoneVal # max spectral amplitude value during event
self.minval=evblob.NoneVal # min val during event
self.minvalbefore=self.maxvalbefore=self.avgpowbefore=evblob.NoneVal
self.minvalafter=self.maxvalafter=self.avgpowafter=evblob.NoneVal
self.MUAbefore=self.MUA=self.MUAafter=evblob.NoneVal
self.arrMUAbefore=self.arrMUA=self.arrMUAafter=evblob.NoneVal # arrays (across channels) of avg MUA values before,during,after event
self.slicex=self.slicey=evblob.NoneVal
self.minF=self.maxF=self.peakF=0 # min,max,peak frequencies
self.minT=self.maxT=self.peakT=0 # min,max,peak times
self.dur = self.Fspan = self.ncycle = self.dom = self.dombefore = self.domafter = self.Foct = 0
self.domevent = 0 # dom during event but only including suprathreshold pixels
# Foct is logarithmic frequency span
self.hasbefore = self.hasafter = False # whether has before,after period
self.ID = -1
self.bbox = bbox()
self.windowidx = 0 # window index (from which spectrogram obtained)
self.offidx = 0 # offset into time-series (since taking windows)
self.duringnoise = 0 # during a noise window?
# indicates whether other events of given frequency co-occur (on same channel)
self.codelta = self.cotheta = self.coalpha = self.cobeta = self.colgamma = self.cogamma = self.cohgamma = self.coother = 0
self.band = evblob.NoneVal
# correlation between CSD and MUA before,during,after event
self.CSDMUACorrbefore = self.CSDMUACorr = self.CSDMUACorrafter = 0.0
# a few waveform features:
# peak and trough values close to the spectral amplitude peak, used to align signals
self.WavePeakVal = self.WavePeakIDX = self.WaveTroughVal = self.WaveTroughIDX = 0
self.WaveH = self.WaveW = 0 # wave height and width
self.WavePeakT = self.WaveTroughT = 0
self.WaveletPeak = WaveletInfo() # for alignment by wavelet peak phase (0)
self.WaveletLeftTrough = WaveletInfo() # for alignment by wavelet trough phase (-pi)
self.WaveletRightTrough = WaveletInfo() # for alignment by wavelet trough phase (pi)
self.WaveletLeftH = self.WaveletLeftW = self.WaveletLeftSlope = 0 # wavelet-based height and width
self.WaveletRightH = self.WaveletRightW = self.WaveletRightSlope = 0 # wavelet-based height and width
self.WaveletFullW = 0 # full width right minus left trough times
self.WaveletFullH = 0 # height offset of the right minus left trough values
self.WaveletFullSlope = 0 # slope at full length of troughs (baseline) WaveletFullH/WaveletFullW
# lagged coherence - for looking at rhythmicity of signal before,during,after oscillatory event
#self.laggedCOH = self.laggedCOHbefore = self.laggedCOHafter = 0
self.filtsig = [] # filtered signal
self.lfiltpeak = []
self.lfilttrough = []
self.filtsigcor = 0.0 # correlation between filtered and raw signal
# self.oscqual = 0.0
def __str__ (self):
return str(self.left)+' '+str(self.right)+' '+str(self.top)+' '+str(self.bottom)+' '+str(self.avgpow)+' '+str(self.cmass)+' '+str(self.maxval)+' '+str(self.maxpos)
def draw (self,scalex,scaley,offidx=0,offidy=0,bbclr='white',mclr='r',linewidth=3):
x0,x1=scalex*(self.left+offidx),scalex*(self.right+offidx)
y0,y1=scaley*(self.top+offidy),scaley*(self.bottom+offidy)
drline(x0,x0,y0,y1,bbclr,linewidth)
drline(x1,x1,y0,y1,bbclr,linewidth)
drline(x0,x1,y0,y0,bbclr,linewidth)
drline(x0,x1,y1,y1,bbclr,linewidth)
plot([scalex*(self.maxpos[1]+offidx)],[scaley*(self.maxpos[0]+offidy)],mclr+'o',markersize=12)
#
def getmergesets (lblob,prct,areaop=min):
""" get the merged blobs (bounding boxes)
lblob is a list of blos (input)
prct is the threshold for fraction of overlap required to merge two blobs (boxes)
returns a list of sets of merged blobs and a bool list of whether each original blob was merged
"""
sz = len(lblob)
bmerged = [False for i in range(sz)]
for i,blob in enumerate(lblob): blob.ID = i # make sure ID assigned
lmergeset = [] # set of merged blobs (boxes)
for i in range(sz):
blob0 = lblob[i]
for j in range(sz):
if i == j: continue
blob1 = lblob[j]
# if blob0.band != blob1.band: continue # NB: this was only used when preventing frequency band crossing!! (2/18/21)
# enough overlap between bboxes?
if blob0.getintersection(blob1).area() >= prct * areaop(blob0.area(),blob1.area()):
# merge them
bmerged[i]=bmerged[j]=True
found = False
for k,mergeset in enumerate(lmergeset): # determine if either of these bboxes are in existing mergesets
if i in mergeset or j in mergeset: # one of the bboxes in an existing mergeset?
found = True
if i not in mergeset: mergeset.add(i) # i not already there? add it in
if j not in mergeset: mergeset.add(j) # j not already there? add it in
if not found: # did not find either bbox in an existing mergeset? then create a new mergeset
mergeset = set()
mergeset.add(i)
mergeset.add(j)
lmergeset.append(mergeset)
return lmergeset, bmerged
#
def getmergedblobs (lblob,lmergeset,bmerged):
""" create a new list of blobs (boxes) based on lmergeset, and update the new blobs' properties
"""
lblobnew = [] # list of new blobs
for i,blob in enumerate(lblob):
if not bmerged[i]: lblobnew.append(blob) # non-merged blobs are copied as is
for mergeset in lmergeset: # now go through the list of mergesets and create the new blobs
lblobtmp = [lblob[ID] for ID in mergeset]
for i,blob in enumerate(lblobtmp):
if i == 0:
box = bbox(blob.left,blob.right,blob.bottom,blob.top)
peakF = blob.peakF
minF = blob.minF
maxF = blob.maxF
minT = blob.minT
maxT = blob.maxT
peakT = blob.peakT
maxpos = blob.maxpos
maxval = blob.maxval
minval = blob.minval
else:
box = box.getunion(blob)
minF = min(minF, blob.minF)
maxF = max(maxF, blob.maxF)
minT = min(minT, blob.minT)
maxT = max(maxT, blob.maxT)
if blob.maxval > maxval:
peakF = blob.peakF
peakT = blob.peakT
maxpos = blob.maxpos
maxval = blob.maxval
if blob.minval < minval:
minval = blob.minval
blob.left,blob.right,blob.bottom,blob.top = box.left,box.right,box.bottom,box.top
blob.minF,blob.maxF,blob.peakF,blob.minT,blob.maxT,blob.peakT=minF,maxF,peakF,minT,maxT,peakT
blob.maxpos,blob.maxval = maxpos,maxval
blob.minval = minval
lblobnew.append(blob)
return lblobnew
# gets blob features in original image coordinates
def getblobfeatures (imnorm,lbl,imorig=None,T=None,F=None):
# imnorm is normalized image, lbl is label image obtained from imnorm, imorig is original un-normalized image
# getblobfeatures returns features of blobs in lbl using imnorm
nlabel = amax(lbl)
lblob = [] # blob output (need better name than blob! how about object?)
lblobidx = linspace(1,nlabel,nlabel)
lavg = ndimage.mean(imnorm,lbl,lblobidx)
lcmass = ndimage.center_of_mass(imnorm,lbl,lblobidx)
lmaxval = ndimage.maximum(imnorm,lbl,lblobidx)
lmaxpos = ndimage.maximum_position(imnorm,lbl,lblobidx)
lavgorig = lmaxvalorig = None
if imorig is not None:
lavgorig = ndimage.mean(imorig,lbl,lblobidx)
lmaxvalorig = ndimage.maximum(imorig,lbl,lblobidx)
for blobidx in range(1,nlabel+1,1):
msk = lbl==blobidx
b = evblob()
slicey, slicex = ndimage.find_objects(msk)[0]
b.slicey = slicey
b.slicex = slicex
b.left = slicex.start
b.right = slicex.stop
b.top = slicey.stop
b.bottom = slicey.start
b.avgpow = lavg[blobidx-1]
if lavgorig is not None: b.avgpoworig = lavgorig[blobidx-1]
if lmaxvalorig is not None: b.maxvalorig = lmaxvalorig[blobidx-1]
b.cmass = lcmass[blobidx-1]
b.maxval = lmaxval[blobidx-1]
b.maxpos = lmaxpos[blobidx-1]
if F is not None:
b.minF = F[b.bottom] # get the frequencies
b.maxF = F[min(b.top,len(F)-1)]
b.peakF = F[b.maxpos[0]]
if T is not None:
b.minT = T[b.left]
b.maxT = T[min(b.right,len(T)-1)]
b.peakT = T[b.maxpos[1]]
lblob.append(b)
return lblob
#
def getampinrange (ms, F, minF, maxF):
sidx = 0
while F[sidx] < minF and sidx + 1 < len(F): sidx += 1
eidx = len(F) - 1
while F[eidx] > maxF and sidx - 1 > 0: eidx -= 1
print(minF,maxF,sidx,eidx,F[sidx],F[eidx])
return sum(ms[sidx:eidx+1,:],axis=0)/(eidx-sidx+1.0)
# get event blobs in (inclusive for lower bound, strictly less than for upper bound) range of minf,maxf
def getblobinrange (lblobf, minF,maxF): return [blob for blob in lblobf if blob.peakF >= minF and blob.peakF < maxF]
# get interevent interval distribution
def getblobIEI (lblob,scalex=1.0):
liei = []
newlist = sorted(lblob, key=lambda x: x.left)
for i in range(1,len(newlist),1):
liei.append((newlist[i].left-newlist[i-1].right)*scalex)
return liei
# get peak-to-peak time interevent interval distribution
def getpeakTIEI (dframe, levidx):
pt = dframe['absPeakT']
lpt = [pt[idx] for idx in levidx]
lpt.sort()
return [lpt[i]-lpt[i-1] for i in range(1,len(lpt),1)]
# get inter-event interval distribution based on end to start time intervals
def getinterTIEI (dframe, levidx):
liei = []
ptmin = dframe['absminT']
ptmax = dframe['absmaxT']
lpt2d = [p2d(ptmin[idx],ptmax[idx]) for idx in levidx]
newlist = sorted(lpt2d, key=lambda x: x.x)
for i in range(1,len(newlist),1):
dt = newlist[i].x-newlist[i-1].y
if dt < 0: continue # sometimes previous event finishes after next event if they're at different peak frequencies
liei.append(dt)
return liei
# get CV2 using variable duration windows specified in lwinsz (in seconds, entries correspond to lband)
def getvarwindCV2 (dframe, chan, \
lband = ['delta','theta','alpha','beta','lgamma','gamma','hgamma'],\
lwinsz=[44.0, 30.0, 24.0, 10.7, 12, 3.6, 1.3],FoctTH=1.5,ERPscoreTH=0.8,ERPDurTH=(75,300)):
maxt = max(dframe['absPeakT']) / 1e3 # convert to s, lwinsz is in s
dcv = {}
for b,winsz in zip(lband,lwinsz):
print(chan,b,winsz)
dcv[b] = {'startt':[],'peaktieiCV2':[],'intertieiCV2':[],'peaktiei':[],'intertiei':[],'N':[],'Rate':[],\
'peaktieiLV':[],'intertieiLV':[]}
for startt in arange(0,maxt-winsz,winsz):
endt = startt + winsz
if 'ERPscore' in dframe.columns:
dfs = dframe[(dframe.band==b) & (dframe.Foct<FoctTH) & (dframe.absPeakT>=startt*1e3) & (dframe.absPeakT<=endt*1e3) & (dframe.chan==chan) & ((dframe.ERPscore<ERPscoreTH)|(dframe.dur<ERPDurTH[0])|(dframe.dur>ERPDurTH[1]))]
else:
dfs = dframe[(dframe.band==b) & (dframe.Foct<FoctTH) & (dframe.absPeakT>=startt*1e3) & (dframe.absPeakT<=endt*1e3) & (dframe.chan==chan)]
N = len(dfs)
dcv[b]['startt'].append(startt)
dcv[b]['N'].append(N)
dcv[b]['Rate'].append(float(N)/winsz)
if N > 1:
dcv[b]['peaktiei'].append(getpeakTIEI(dframe,dfs.index))
dcv[b]['intertiei'].append(getinterTIEI(dframe,dfs.index))
if N > 2:
dcv[b]['peaktieiCV2'].append(getCV2(dcv[b]['peaktiei'][-1]))
dcv[b]['intertieiCV2'].append(getCV2(dcv[b]['intertiei'][-1]))
if N > 3:
dcv[b]['peaktieiLV'].append(getLV(dcv[b]['peaktiei'][-1]))
dcv[b]['intertieiLV'].append(getLV(dcv[b]['intertiei'][-1]))
else:
dcv[b]['peaktieiLV'].append(nan)
dcv[b]['intertieiLV'].append(nan)
else:
dcv[b]['peaktieiCV2'].append(nan)
dcv[b]['intertieiCV2'].append(nan)
dcv[b]['peaktieiLV'].append(nan)
dcv[b]['intertieiLV'].append(nan)
else:
dcv[b]['peaktiei'].append([])
dcv[b]['intertiei'].append([])
dcv[b]['peaktieiCV2'].append(nan)
dcv[b]['intertieiCV2'].append(nan)
dcv[b]['peaktieiLV'].append(nan)
dcv[b]['intertieiLV'].append(nan)
dcv[b]['FF'] = getFF(dcv[b]['N'])
return dcv
#
def getdCV2 (dframe, chan, \
lband = ['delta','theta','alpha','beta','lgamma','gamma','hgamma'], \
lwinsz=[1,2,5,10,15,20,25,50,100,200], \
FoctTH=1.5,ERPscoreTH=0.8,ERPDurTH=(75,300)):
maxt = max(dframe['absPeakT']) / 1e3 # convert to s, lwinsz is in s
dcv = {}
for b in lband:
dcv[b]={}
for winsz in lwinsz:
print(b,winsz)
dcv[b][winsz] = {'startt':[],'peaktieiCV2':[],'intertieiCV2':[],'peaktiei':[],'intertiei':[],'N':[],'Rate':[]}
for startt in arange(0,maxt-winsz,winsz):
endt = startt + winsz
if 'ERPscore' in dframe.columns:
dfs = dframe[(dframe.band==b) & (dframe.Foct<FoctTH) & (dframe.absPeakT>=startt*1e3) & (dframe.absPeakT<=endt*1e3) & (dframe.chan==chan) & ((dframe.ERPscore<ERPscoreTH)|(dframe.dur<ERPDurTH[0])|(dframe.dur>ERPDurTH[1]))]
else:
dfs = dframe[(dframe.band==b) & (dframe.Foct<FoctTH) & (dframe.absPeakT>=startt*1e3) & (dframe.absPeakT<=endt*1e3) & (dframe.chan==chan)]
N = len(dfs)
if N > 2:
dcv[b][winsz]['peaktiei'].append(getpeakTIEI(dframe,dfs.index))
dcv[b][winsz]['peaktieiCV2'].append(getCV2(dcv[b][winsz]['peaktiei'][-1]))
dcv[b][winsz]['intertiei'].append(getinterTIEI(dframe,dfs.index))
dcv[b][winsz]['intertieiCV2'].append(getCV2(dcv[b][winsz]['intertiei'][-1]))
dcv[b][winsz]['startt'].append(startt)
dcv[b][winsz]['N'].append(N)
dcv[b][winsz]['Rate'].append(float(N)/winsz)
return dcv
#
def drawdCV2 (ddcv2,lchan,lwinsz,k='intertieiCV2',xl=None,yl=None,ylab=r'Average $CV^2$',lclr = ['r','g','b','c','m'], lsty='solid',marker='o'):
for clr,chan in zip(lclr,lchan):
dcv2 = ddcv2[chan]
for bdx,b in enumerate(lband):
subplot(3,2,bdx+1); title(b)
lWinter = []; lMinter = [];
for winsz in lwinsz:
m = mean(dcv2[b][winsz][k])
if not isnan(m):
lWinter.append(winsz)
lMinter.append(m)
plot(lWinter,lMinter,clr,linestyle=lsty);
plot(lWinter,lMinter,clr+marker,markersize=25)
title(b)
if ylab is not None: ylabel(ylab)
xlabel('Window size (s)')
if yl is not None: ylim(yl)
if xl is not None: xlim(xl)
# finds boundaries where the image dips below the threshold, starting from x,y and moving left,right,up,down
def findbounds (img,x,y,thresh):
ysz, xsz = img.shape
y0 = y
x0 = x - 1
# look left
while True:
if x0 < 0:
x0 = 0
break
if img[y0][x0] < thresh: break
x0 -= 1
left = x0
# look right
x0 = x + 1
while True:
if x0 >= xsz:
x0 = xsz - 1
break
if img[y0][x0] < thresh: break
x0 += 1
right = x0
# look down
x0 = x
y0 = y - 1
while True:
if y0 < 0:
y0 = 0
break
if img[y0][x0] < thresh: break
y0 -= 1
bottom = y0
# look up
x0 = x
y0 = y + 1
while True:
if y0 >= ysz:
y0 = ysz - 1
break
if img[y0][x0] < thresh: break
y0 += 1
top = y0
#print('left,right,top,bottom:',left,right,top,bottom)
return left,right,top,bottom
# extract the event blobs from local maxima image (impk)
def getblobsfrompeaks (imnorm,impk,imorig,medthresh,endfctr,T,F):
# imnorm is normalized image, lbl is label image obtained from imnorm, imorig is original un-normalized image
# medthresh is median threshold for significant peaks
# getblobfeatures returns features of blobs in lbl using imnorm
lpky,lpkx = np.where(impk) # get the peak coordinates
lblob = []
for y,x in zip(lpky,lpkx):
pkval = imnorm[y][x]
#thresh = max(medthresh, min(medthresh, endfctr * pkval)) # lower value threshold used to find end of event
thresh = min(medthresh, endfctr * pkval) # lower value threshold used to find end of event -- original rule!!
#thresh = max(medthresh, endfctr * pkval) # lower value threshold used to find end of event
#thresh = max(medthresh, (medthresh + endfctr*pkval)/2.0) # threshold used to find end of event
left,right,top,bottom = findbounds(imnorm,x,y,thresh)
#subimg = imnorm[bottom:top+1,left:right+1]
#thsubimg = subimg > thresh
#print('L,R,T,B:',left,right,top,bottom,subimg.shape,thsubimg.shape,sum(thsubimg))
#print('sum(thsubimg)',sum(thsubimg),'amax(subimg)',amax(subimg))
b = evblob()
#b.avgpoworig = ndimage.mean(imorig[bottom:top+1,left:right+1],thsubimg,[1])
b.maxvalorig = imorig[y][x]
#b.avgpow = ndimage.mean(subimg,thsubimg,[1])
b.maxval = pkval
b.minval = amin(imnorm[bottom:top+1,left:right+1])
b.left = left
b.right = right
b.top = top
b.bottom = bottom
b.maxpos = (y,x)
b.minF = F[b.bottom] # get the frequencies
b.maxF = F[min(b.top,len(F)-1)]
b.peakF = F[b.maxpos[0]]
b.band = getband(b.peakF)
b.minT = T[b.left]
b.maxT = T[min(b.right,len(T)-1)]
b.peakT = T[b.maxpos[1]]
lblob.append(b)
return lblob
#
def getbandrange (lblob):
drange = {'delta':[],'theta':[],'alpha':[],'beta':[],'lgamma':[],'gamma':[],'hgamma':[],'unknown':[]}
for blob in lblob:
drange[blob.band].append((blob.minT,blob.maxT))
return drange
#
def checkcorange (drange,band,ev):
for rng in drange[band]:
if ev.maxT < rng[0] or ev.minT > rng[1]:
pass
else:
return True
return False
#
def getcoband (levblob):
drange = getbandrange(levblob)
for ev in levblob:
if ev.band == 'delta': ev.codelta = 1
else: ev.codelta = int(checkcorange(drange,'delta',ev))
if ev.band == 'theta': ev.cotheta = 1
else: ev.cotheta = int(checkcorange(drange,'theta',ev))
if ev.band == 'alpha': ev.coalpha = 1
else: ev.coalpha = int(checkcorange(drange,'alpha',ev))
if ev.band == 'beta': ev.cobeta = 1
else: ev.cobeta = int(checkcorange(drange,'beta',ev))
if ev.band == 'lgamma': ev.colgamma = 1
else: ev.colgamma = int(checkcorange(drange,'lgamma',ev))
if ev.band == 'gamma': ev.cogamma = 1
else: ev.cogamma = int(checkcorange(drange,'gamma',ev))
if ev.band == 'hgamma': ev.cohgamma = 1
else: ev.cohgamma = int(checkcorange(drange,'hgamma',ev))
if ev.band == 'delta':
ev.coother = int(ev.cotheta or ev.coalpha or ev.cobeta or ev.colgamma or ev.cogamma or ev.cohgamma)
if ev.band == 'theta':
ev.coother = int(ev.codelta or ev.coalpha or ev.cobeta or ev.colgamma or ev.cogamma or ev.cohgamma)
if ev.band == 'alpha':
ev.coother = int(ev.codelta or ev.cotheta or ev.cobeta or ev.colgamma or ev.cogamma or ev.cohgamma)
if ev.band == 'beta':
ev.coother = int(ev.codelta or ev.cotheta or ev.coalpha or ev.colgamma or ev.cogamma or ev.cohgamma)
if ev.band == 'lgamma':
ev.coother = int(ev.codelta or ev.cotheta or ev.coalpha or ev.cobeta or ev.cogamma or ev.cohgamma)
if ev.band == 'gamma':
ev.coother = int(ev.codelta or ev.cotheta or ev.coalpha or ev.cobeta or ev.colgamma or ev.cohgamma)
if ev.band == 'hgamma':
ev.coother = int(ev.codelta or ev.cotheta or ev.coalpha or ev.cobeta or ev.colgamma or ev.cogamma)
#
def getFoct (minF, maxF):
if maxF - minF > 0.0 and minF > 0.0: return log(maxF/minF)
return 0.0
#
def getextrafeatures (lblob, ms, img, medthresh, csd, MUA, chan, offidx, sampr, endfctr = 0.5, getphase = True, getfilt = True):
# get extra features for the event blobs, including:
# MUA before/after, min/max/avg power before/after
# ms is the MorletSpec object (contains non-normalized TFR and PHS when getphase==True
# img is the median normalized spectrogram image; MUA is the multiunit activity (should have same sampling rate)
# chan is CSD channel (where events detected), note that csd is 1D while MUA is 2D (for now)
#vec=h.Vector() # for getting the sample entropy
mua = None
if MUA is not None: mua = MUA[chan+1,:] # mua on same channel
for bdx,blob in enumerate(lblob):
# duration/frequency features
blob.dur = blob.maxT - blob.minT # duration
blob.Fspan = blob.maxF - blob.minF # linear frequency span
blob.ncycle = blob.dur*blob.peakF/1e3 # number of cycles
blob.Foct = getFoct(blob.minF,blob.maxF)
###
w2 = int(blob.width() / 2.)
left,right,bottom,top = blob.left,blob.right+1,blob.bottom,blob.top # these are indices into TFR (wavelet spectrogram)
#print(bdx,left,right,bottom,top,offidx)
subimg = img[bottom:top+1,left:right+1] # is right+1 correct if already inc'ed above?
blob.avgpow = mean(subimg) # avg power of all pixels in event bounds
#thresh = max(medthresh, min(medthresh, endfctr * blob.maxval)) # lower value threshold used to find end of event
thresh = min(medthresh, endfctr * blob.maxval) # lower value threshold used to find end of event -- original rule!!
#thresh = max(medthresh, endfctr * blob.maxval) # upper value threshold used to find end of event
#thresh = max(medthresh, (medthresh + endfctr*blob.maxval)/2.0) # upper value threshold used to find end of event
thsubimg = subimg >= thresh #
#print(bdx,endfctr,blob.maxval,thresh,subimg.shape,thsubimg.shape,left,right,bottom,top)
#print(amax(subimg),amin(thsubimg),amax(thsubimg))
blob.avgpowevent = ndimage.mean(subimg,thsubimg,[1])[0] # avg power of suprathreshold pixels
if blob.avgpow>0.0: blob.dom = float(blob.maxval/blob.avgpow) # depth of modulation (all pixels)
if blob.avgpowevent>0.0: blob.domevent = float(blob.maxval/blob.avgpowevent) # depth of modulation (suprathreshold pixels)
if mua is not None:
blob.MUA = mean(mua[left+offidx:right+offidx]) # offset from spectrogram index into original MUA,CSD time-series
blob.arrMUA = mean(MUA[:,left+offidx:right+offidx],axis=1) # avg MUA from each channel during the event
if mua is not None and right - left > 1: blob.CSDMUACorr = pearsonr(csd[left+offidx:right+offidx],mua[left+offidx:right+offidx])[0]
# a few waveform features
wvlen2 = (1e3/blob.peakF)/2 # 1/2 wavelength in milliseconds
wvlensz2 = int(wvlen2*sampr/1e3) # 1/2 wavelength in samples
blob.WavePeakVal,blob.WavePeakIDX = findpeak(csd, int(blob.maxpos[1])+offidx, left+offidx, right+offidx, wvlensz2)
blob.WaveTroughVal,blob.WaveTroughIDX = findtrough(csd, int(blob.maxpos[1])+offidx, left+offidx, right+offidx, wvlensz2)
blob.WavePeakIDX -= offidx; blob.WaveTroughIDX -= offidx; # keep indices within spectrogram image
blob.WaveH = blob.WavePeakVal - blob.WaveTroughVal
blob.WavePeakT = 1e3*blob.WavePeakIDX/sampr
blob.WaveTroughT = 1e3*blob.WaveTroughIDX/sampr
blob.WaveW = 2 * abs(blob.WavePeakT - blob.WaveTroughT) # should update to use wavelet peak (phase= 0)/trough(phase= -PI)
if getphase: # wavelet-based features
freqIDX = list(ms.f).index(blob.peakF) # index into frequency array
PHS = ms.PHS[freqIDX,:]
blob.WaveletPeak.phs,blob.WaveletPeak.idx=findclosest(PHS,int(blob.maxpos[1]),left,right,wvlensz2,0.0)
blob.WaveletPeak.val = csd[blob.WaveletPeak.idx+offidx] # +offidx for correct index into csd (blob.WaveletPeak.idx is into PHS)
blob.WaveletPeak.T = 1e3*blob.WaveletPeak.idx/sampr #
blob.WaveletLeftTrough.phs,blob.WaveletLeftTrough.idx=findclosest(PHS,int(blob.WaveletPeak.idx),left,right,wvlensz2+int(wvlensz2/2),-pi,lookleft=True,lookright=False)
blob.WaveletLeftTrough.val = csd[blob.WaveletLeftTrough.idx+offidx]# +offidx for correct index into csd (WaveletLeftTrough.idx is into PHS)
blob.WaveletLeftTrough.T = 1e3*blob.WaveletLeftTrough.idx/sampr #
blob.WaveletRightTrough.phs,blob.WaveletRightTrough.idx=findclosest(PHS,int(blob.WaveletPeak.idx),left,right,wvlensz2+int(wvlensz2/2),pi,lookleft=False,lookright=True)
blob.WaveletRightTrough.val = csd[blob.WaveletRightTrough.idx+offidx]# +offidx for correct index into csd (WaveletRightTrough.idx is into PHS)
blob.WaveletRightTrough.T = 1e3*blob.WaveletRightTrough.idx/sampr #
blob.WaveletLeftH = blob.WaveletPeak.val - blob.WaveletLeftTrough.val
blob.WaveletLeftW = blob.WaveletPeak.T - blob.WaveletLeftTrough.T
if blob.WaveletLeftW != 0.0: blob.WaveletLeftSlope = blob.WaveletLeftH / blob.WaveletLeftW
blob.WaveletRightH = blob.WaveletPeak.val - blob.WaveletRightTrough.val
blob.WaveletRightW = blob.WaveletRightTrough.T - blob.WaveletPeak.T
if blob.WaveletRightW != 0.0: blob.WaveletRightSlope = blob.WaveletRightH / blob.WaveletRightW
blob.WaveletFullH = blob.WaveletRightTrough.val - blob.WaveletLeftTrough.val
blob.WaveletFullW = blob.WaveletRightTrough.T - blob.WaveletLeftTrough.T
if blob.WaveletFullW != 0.0: blob.WaveletFullSlope = blob.WaveletFullH / blob.WaveletFullW
if getfilt:
padsz = int(sampr*0.2)
x0 = left+offidx
x1 = right+offidx-1
x0p = max(0,x0-padsz)
x1p = min(len(csd),x1+padsz)
fsig = bandpass(csd[x0p:x1p], blob.minF, blob.maxF, sampr, zerophase=True)
#print(x0,x1,x0p,x1p,len(fsig))
blob.filtsig = fsig[x0-x0p:x0-x0p+x1-x0]
if x1-x0>1: blob.filtsigcor = pearsonr(blob.filtsig,csd[x0:x1])[0]
# look at values in period before event
idx0 = max(0,blob.left - wvlensz2) #max(0,blob.left - w2)
idx1 = blob.left
if idx1 > idx0 + 1: # any period before?
subimg = img[blob.bottom:blob.top+1,idx0:idx1]
blob.minvalbefore = amin(subimg)
blob.maxvalbefore = amax(subimg)
blob.avgpowbefore = mean(subimg)
if blob.avgpowbefore>0.0: blob.dombefore = float(blob.maxvalbefore/blob.avgpowbefore)
idx0 += offidx; idx1 += offidx # offset from spectrogram index into original MUA,CSD time-series
if mua is not None:
blob.MUAbefore = mean(mua[idx0:idx1]) # offset from spectrogram index into original MUA,CSD time-series
blob.arrMUAbefore = mean(MUA[:,idx0:idx1],axis=1) # avg MUA from each channel before the event
if mua is not None and idx1-idx0>1:
blob.CSDMUACorrbefore = pearsonr(csd[idx0:idx1],mua[idx0:idx1])[0]
blob.hasbefore = True
#idx0 = max(0,blob.left - wvlensz2*2)
#idx1 = blob.left
#blob.laggedCOHbefore = lagged_coherence(csd[idx0:idx1], (blob.minF,blob.maxF), sampr)#, n_cycles=blob.ncycle) # quantifies rhythmicity
#if isnan(blob.laggedCOHbefore): blob.laggedCOHbefore = -1.0
else:
blob.hasbefore = False
# look at values in period after event
idx0 = blob.right+1
idx1 = min(idx0 + wvlensz2,img.shape[1]) # min(idx0 + w2,img.shape[1])
if idx1 > idx0 + 1: # any period after?
subimg = img[blob.bottom:blob.top+1,idx0:idx1]
blob.minvalafter = amin(subimg)
blob.maxvalafter = amax(subimg)
blob.avgpowafter = mean(subimg)
if blob.avgpowafter>0.0: blob.domafter = float(blob.maxvalafter/blob.avgpowafter)
idx0 += offidx; idx1 += offidx # offset from spectrogram index into original MUA,CSD time-series
if mua is not None:
blob.MUAafter = mean(mua[idx0:idx1])
blob.arrMUAafter = mean(MUA[:,idx0:idx1],axis=1) # avg MUA from each channel after the event
if mua is not None and idx1-idx0>1:
blob.CSDMUACorrafter = pearsonr(csd[idx0:idx1],mua[idx0:idx1])[0]
blob.hasafter = True
#idx1 = min(idx0 + wvlensz2*2,img.shape[1]) # min(idx0 + w2,img.shape[1])
#blob.laggedCOHafter = lagged_coherence(csd[idx0:idx1], (blob.minF,blob.maxF), sampr)#, n_cycles=blob.ncycle) # quantifies rhythmicity
#if isnan(blob.laggedCOHafter): blob.laggedCOHafter = -1.0
else:
blob.hasafter = False
getcoband(lblob) # get band of events co-occuring on same channel
#
def getcycbyband (dframe, lband, sampr):
dbprop = {b:{} for b in lband}
for b in lband:
dfb = dframe[dframe.band == b]
for idx in dfb.index:
sig = dframe.at[idx,'filtsig']
dprop = getcyclefeatures(sig, sampr, 1.5 * dframe.at[idx,'maxF'])
if 'rdsym' not in dbprop[b]:
for k in dprop.keys(): dbprop[b][k] = []
for k in dprop.keys():
if not iterable(dprop[k]):
if not isnan(dprop[k]):
dbprop[b][k].append(dprop[k])
else:
for x in dprop[k]:
if not isnan(x):
dbprop[b][k].append(x)
return dbprop
# get cycle information in a dictionary, using same index as into dframe
# operates on either select or full set of osc. events
def getcycbyevidx (dframe, levidx, sampr):
ddprop = OrderedDict() # to make sure the event time order is preserved
for evidx in levidx:
sig = dframe.at[evidx,'filtsig']
dprop = getcyclefeatures(sig, sampr, 1.5 * dframe.at[evidx,'maxF'])
ddprop[evidx] = dprop
return ddprop
#
def getintrapeakdistrib (ddprop):
lout = []
for idx in ddprop.keys():
for x in ddprop[idx]['interpeakt']: lout.append(x)
return lout
# this function assumes that ddprop and dframe have events sorted by increasing time
def getinterpeakdistrib (dframe, ddprop):
#newlist = sorted(lblob, key=lambda x: x.left)
lout = []
lkey = list(ddprop.keys())
for i in range(0,len(lkey)-1,1):
idx = lkey[i]
lastpkT = dframe.at[idx,'absminT'] + ddprop[idx]['peakt'][-1]
jdx = lkey[i+1]
nextpkT = dframe.at[jdx,'absminT'] + ddprop[jdx]['peakt'][0]
interT = nextpkT - lastpkT
if interT >= 0: lout.append(interT)
return lout
# from https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array
def detectpeaks (image):
"""
Takes an image and detect the peaks usingthe local maximum filter.
Returns a boolean mask of the peaks (i.e. 1 when
the pixel's value is the neighborhood maximum, 0 otherwise)
"""
# define an 8-connected neighborhood
neighborhood = generate_binary_structure(2,2)
#apply the local maximum filter; all pixel of maximal value
#in their neighborhood are set to 1
local_max = maximum_filter(image, footprint=neighborhood)==image
#local_max is a mask that contains the peaks we are
#looking for, but also the background.
#In order to isolate the peaks we must remove the background from the mask.
#we create the mask of the background
background = (image==0)
#a little technicality: we must erode the background in order to
#successfully subtract it form local_max, otherwise a line will
#appear along the background border (artifact of the local maximum filter)
eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)
#we obtain the final mask, containing only peaks,
#by removing the background from the local_max mask (xor operation)
detected_peaks = local_max ^ eroded_background
return detected_peaks
#
def getallchanblobs (dat,medthresh):
outd = {}
nchan = dat.shape[1]
for chan in range(dat.shape[1]):
outd[chan] = {}