-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataAnalysis.py
7684 lines (6829 loc) · 406 KB
/
dataAnalysis.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 time
import numpy as np
import sys
import os
import scipy, scipy.io
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from scipy import io
import pdb
import scipy.ndimage
import itertools
import pandas as pd
from scipy.interpolate import interp1d
# from sklearn.decomposition import PCA
# import cv2
from scipy import signal
from scipy.signal import find_peaks
import pickle
import random
from statsmodels.stats.anova import anova_single
# import scikits.bootstrap as boot
from scipy import ndimage
from matplotlib import rcParams
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm
import matplotlib
import multiprocessing as mp
# from joblib import Parallel, delayed
import scipy.stats as stats
# from tools.pyqtgraph.Qt import QtGui, QtCore
# import tools.pyqtgraph as pg
matplotlib.use('TkAgg') # WxAgg
from array import array
import scipy.interpolate as interpolate
import scipy.optimize as optimize
import array as arr
from numpy import trapz
import numpy as np
import scipy.optimize
import matplotlib.pyplot as plt
# from sklearn.cluster import KMeans
# numcores = mp.cpu_count()-1
# from sklearn import linear_model
# from sklearn import preprocessing
# from sklearn.model_selection import GroupKFold
# from sklearn.model_selection import KFold
# from sklearn.model_selection import cross_val_score
# from sklearn.model_selection import RepeatedKFold
from scipy.stats import vonmises_line
import datetime
from functools import wraps
from pathlib import Path
import tools.createGroupVisualizations as createGroupVisualizations
import numpy as np
import pandas as pd
import scipy.stats as stats
import statsmodels.api as sm
from scipy.optimize import curve_fit
import tools.Doric as dr
from scipy.ndimage import gaussian_filter1d
groupFigDir = r"C:\Analysis\groupFigures"
groupAnalysisDir = r"C:\Analysis\groupAnalysisDir"
cV = createGroupVisualizations.createGroupVisualizations(groupFigDir,groupAnalysisDir)
def find_closest_indices(sample_times, time_array):
"""
For each time in the behavior_times list, find the closest index in the fiber_time_array.
Parameters:
- behavior_times: list of times from the behavior part.
- fiber_time_array: time array corresponding to fiber photometry signal.
Returns:
- closest_indices: list of indices in fiber_time_array corresponding to the closest times to behavior_times.
"""
closest_indices = []
for behavior_time in sample_times:
# Find the index of the closest time in fiber_time_array
closest_idx = (np.abs(time_array - behavior_time)).argmin()
closest_indices.append(closest_idx)
return closest_indices
def extract_bout_data(onset, fiber_time, dFF, pre_event_window=5, post_event_window=5):
"""
Extracts the data segment around a specific onset and returns both the centered time window and signal.
Parameters:
- onset: The time point of the event.
- fiber_time: 1D numpy array representing the time values.
- dFF: 1D numpy array representing the signal data.
- pre_event_window: Time in seconds before the onset to include (default is 5).
- post_event_window: Time in seconds after the onset to include (default is 5).
Returns:
- segment_time_centered: Time values centered around the onset.
- segment: Signal values in the segment.
"""
# Find indices for the specified time window around the onset
start_idx = (np.abs(fiber_time - (onset - pre_event_window))).argmin()
end_idx = (np.abs(fiber_time - (onset + post_event_window))).argmin()
# Extract the segments for both time and signal
segment_time = fiber_time[start_idx:end_idx]
segment = dFF[start_idx:end_idx]
# Center segment_time around the onset
segment_time_centered = segment_time - onset
return segment_time_centered, segment
def extract_behavior_events(
animal, eventName, time_array, behavior_array,
time_range=None, min_duration=1, eventNb=None, index_range=None,
max_duration=None, fuseTime=None, plot=False):
"""
Extract behavior events from time and behavior arrays, with optional trimming of event duration,
fusing of close events, and plot statistics.
Parameters:
- time_array: Array of timestamps.
- behavior_array: Array of behavior (1 or 0) corresponding to each timestamp.
- time_range: Tuple (start_time, end_time) to filter events within this time range.
- min_duration: Minimum duration of behavior events to be recorded. None to disable.
- eventNb: Maximum number of events to record. None to disable.
- index_range: Tuple (start_idx, end_idx) to filter events within this index range.
- max_duration: Maximum duration for each event. None to disable trimming.
- fuseTime: Time threshold in seconds; consecutive events closer than this are fused into one. None to disable.
- plot: Boolean to indicate if event statistics should be plotted before filtering.
"""
events = {
"animal": animal,
"event_name": eventName,
"onset_times": [],
"offset_times": [],
"durations": [],
"onset_indices": [],
"offset_indices": []
}
in_zone = False
onset_time = None
onset_idx = None
# Apply time range filtering if specified
if time_range:
start_time, end_time = time_range
valid_indices = [i for i, t in enumerate(time_array) if start_time <= t <= end_time]
if not valid_indices:
return events # Return empty if no valid indices in the range
time_array = [time_array[i] for i in valid_indices]
behavior_array = [behavior_array[i] for i in valid_indices]
# Apply index range filtering if specified
if index_range:
start_idx, end_idx = index_range
start_idx = max(0, start_idx)
end_idx = min(len(time_array), end_idx)
time_array = time_array[start_idx:end_idx]
behavior_array = behavior_array[start_idx:end_idx]
# Iterate over the behavior and time arrays
for i in range(len(behavior_array)):
if eventNb is not None and len(events["onset_times"]) >= eventNb:
break # Stop if the maximum number of events has been reached
if behavior_array[i] == 1 and not in_zone:
onset_time = time_array[i]
onset_idx = i
in_zone = True
elif behavior_array[i] == 0 and in_zone:
offset_time = time_array[i]
offset_idx = i
duration = offset_time - onset_time
# Apply max_duration trim if specified
if max_duration is not None and duration > max_duration:
offset_time = onset_time + max_duration
offset_idx = next(j for j, t in enumerate(time_array) if t >= offset_time)
duration = max_duration
# Fuse events if fuseTime is specified
if fuseTime is not None and events["offset_times"] and (onset_time - events["offset_times"][-1]) < fuseTime:
events["offset_times"][-1] = offset_time
events["durations"][-1] = events["offset_times"][-1] - events["onset_times"][-1]
events["offset_indices"][-1] = offset_idx
else:
if min_duration is None or duration >= min_duration:
events["onset_times"].append(onset_time)
events["offset_times"].append(offset_time)
events["durations"].append(duration)
events["onset_indices"].append(onset_idx)
events["offset_indices"].append(offset_idx)
in_zone = False
if in_zone and (eventNb is None or len(events["onset_times"]) < eventNb):
offset_time = time_array[-1]
offset_idx = len(time_array) - 1
duration = offset_time - onset_time
if max_duration is not None and duration > max_duration:
offset_time = onset_time + max_duration
offset_idx = next(j for j, t in enumerate(time_array) if t >= offset_time)
duration = max_duration
if min_duration is None or duration >= min_duration:
events["onset_times"].append(onset_time)
events["offset_times"].append(offset_time)
events["durations"].append(duration)
events["onset_indices"].append(onset_idx)
events["offset_indices"].append(offset_idx)
# Plot event statistics if requested
if plot:
fig, axs = plt.subplots(3, 1, figsize=(10, 12))
fig.suptitle(f"Behavior Event Statistics - {eventName}")
axs[0].hist(events["durations"], bins=10)
axs[0].set_title("Distribution of Event Durations")
axs[0].set_xlabel("Duration (s)")
axs[0].set_ylabel("Frequency")
axs[1].bar(range(len(events["durations"])), events["durations"])
axs[1].set_title("Event Durations in Order of Appearance")
axs[1].set_xlabel("Event Order")
axs[1].set_ylabel("Duration (s)")
for onset, offset in zip(events["onset_times"], events["offset_times"]):
axs[2].fill_betweenx([0, 1], onset, offset, color="gray", alpha=0.3)
axs[2].set_title("Event Time Intervals - After Filtering and Fusion")
axs[2].set_xlabel("Time (s)")
axs[2].set_yticks([])
plt.tight_layout()
return events
def getSpeed(angles,times,circumsphere,minSpacing):
angleJumps = angles[np.concatenate((([True]),np.diff(angles)!=0.))] # find angles at the points where the angle value changes
timePoints = times[np.concatenate((([True]),np.diff(angles)!=0.))] # find times at the points where the angle value changes
#
#
dt = np.diff(timePoints) # delta t values of the time array
dtMultipleSpace = dt//minSpacing # how many times does the minSpacing fit in the gaps
dtMultipleSpace = dtMultipleSpace[dtMultipleSpace>1] # gap must be as big as 2 times the spacing to add a point
# note that gap must be larger than 2 times the spacing
startGap = np.arange(len(timePoints))[np.hstack(((dt>2.*minSpacing),np.array(False)))] # index values of the start of the gap
endGap = np.arange(len(timePoints))[np.hstack((np.array(False),(dt>2.*minSpacing)))] # index values of the end of the gap
newSpacingValue = (timePoints[endGap] - timePoints[startGap]) / dtMultipleSpace
newTvalues = []
newAvalues = []
for i in range(len(dtMultipleSpace)):
newTvalues.extend(timePoints[startGap][i] + newSpacingValue[i] * np.arange(1, dtMultipleSpace[i]))
newAvalues.extend(np.repeat(angleJumps[startGap][i], (dtMultipleSpace[i] - 1)))
timesNew = np.hstack((timePoints,np.asarray(newTvalues)))
anglesNew = np.hstack((angleJumps,np.asarray(newAvalues)))
both = np.row_stack((timesNew,anglesNew))
bothSorted = both[:,both[0].argsort()]
angularSpeed = np.diff(bothSorted[1])/np.diff(bothSorted[0])
angularSpeedM = (angularSpeed[1:]+angularSpeed[:-1])/2.
linearSpeed = angularSpeedM*circumsphere/360.
speedTimes = bothSorted[0][1:-1]
#pdb.set_trace()
angularSpeedSmooth = scipy.signal.medfilt(angularSpeed,kernel_size=9)
linearSpeedSmooth = scipy.signal.medfilt(linearSpeed,kernel_size=9)
return (angularSpeedSmooth,linearSpeedSmooth,speedTimes,angularSpeed,linearSpeed)
def crosscorr(deltat, y0, y1, correlationRange=1.5, fast=False):
"""
home-written routine to calcualte cross-correlation between two contiuous traces
new version from February 9th, 2011
"""
if len(y0) != len(y1):
print('Data to be correlated has different dimensions!')
sys.exit(1)
y0mean = y0.mean()
y1mean = y1.mean()
y0sd = y0.std()
y1sd = y1.std()
if y0sd != 0 and y1sd != 0:
y0norm = (y0 - y0mean) / y0sd
y1norm = (y1 - y1mean) / y1sd
else:
y0norm = y0 - y0mean
y1norm = y1 - y1mean
# defined range calculation of cross-correlation
# value is specified in main routine
# deltat = 0.9
pointnumber1 = len(y0)
ncorrrange = np.ceil(correlationRange / deltat)
corrrange = np.arange(2 * ncorrrange + 1) - ncorrrange
ycorr = np.zeros(len(corrrange))
# print corrrange
if fast:
pass
else:
for n in corrrange:
corrpairs = pointnumber1 - abs(n)
# ccc = arange(corrpairs)
# print n
if n < 0:
y1mod = np.hstack((y1norm[int(-abs(n)):], y1norm[:-int(abs(n))]))
ycorr[int(n + ncorrrange)] = (np.add.reduce(y0norm * y1mod)) / (float(pointnumber1))
# if n > -10 :
# print n, ncorrrange, n+ncorrrange, ycorr[n+ncorrrange], float(pointnumber1)
elif n == 0:
ycorr[int(n + ncorrrange)] = (np.add.reduce(y0norm * y1norm)) / (float(pointnumber1))
# print n, ncorrrange, n+ncorrrange, ycorr[n+ncorrrange], (float(pointnumber1-1))
elif n > 0:
y1mod = np.hstack((y1norm[int(abs(n)):], y1norm[:int(abs(n))]))
ycorr[int(n + ncorrrange)] = (np.add.reduce(y0norm * y1mod)) / (float(pointnumber1))
# if n < 10 :
# print n, ncorrrange, n+ncorrrange, ycorr[n+ncorrrange], float(pointnumber1-1)
else:
print('Problem!')
exit(1)
# print n , ycorr[n+ncorrrange]
float_corrrange = np.array([float(i) for i in corrrange])
xcorr = float_corrrange * deltat
normcorr = np.column_stack((xcorr, ycorr))
return normcorr
############################################################
## high-pass filter from http://nullege.com/codes/show/[email protected]@obspy@[email protected]
############################################################
def highpass(data, freq, df=200, corners=4, zerophase=False):
"""
Butterworth-Highpass Filter.
Filter data removing data below certain frequency freq using corners.
:param data: Data to filter, type numpy.ndarray.
:param freq: Filter corner frequency.
:param df: Sampling rate in Hz; Default 200.
:param corners: Filter corners. Note: This is twice the value of PITSA's
filter sections
:param zerophase: If True, apply filter once forwards and once backwards.
This results in twice the number of corners but zero phase shift in
the resulting filtered trace.
:return: Filtered data.
"""
fe = 0.5 * df
[b, a] = iirfilter(corners, freq / fe, btype='highpass', ftype='butter', output='ba')
if zerophase:
firstpass = lfilter(b, a, data)
return lfilter(b, a, firstpass[::-1])[::-1]
else:
return lfilter(b, a, data)
############################################################
## high-pass filter from http://stackoverflow.com/questions/12093594/how-to-implement-band-pass-butterworth-filter-with-scipy-signal-butter
############################################################
def butter_highpass(interval, sampling_rate, cutoff, order=5):
nyq = sampling_rate * 0.5
stopfreq = float(cutoff)
cornerfreq = 0.4 * stopfreq # (?)
ws = cornerfreq / nyq
wp = stopfreq / nyq
# for bandpass:
# wp = [0.2, 0.5], ws = [0.1, 0.6]
N, wn = scipy.signal.buttord(wp, ws, 3, 16) # (?)
# for hardcoded order:
# N = order
b, a = scipy.signal.butter(N, wn, btype='high') # should 'high' be here for bandpass?
sf = scipy.signal.lfilter(b, a, interval)
return sf
##################################################################
## high-pass filters the ephys recording and extracts spikes through thresholding
##################################################################
def extractSpikes(eData, eTime, stim=False):
highpassfreq = 150. # Hz
spikecountwindow = 0.05 # in sec
binWidth = 1.E-3 # in sec
stimRinging = 0.002
dt = np.mean(eTime[1:] - eTime[:-1])
rate = 1. / dt
# set binned array for convolution
binWidth = 1.E-3 # in sec
tbins = np.linspace(0., len(eData) * dt, int(len(eData) * dt / binWidth) + 1)
nspikecountwindow = spikecountwindow / binWidth
############################################
# create new group in hdf5 file
#grp_spikes = self.analyzed_data.require_group('spiking_data')
detectSpikes = True
#if ('spikeTreshold' in grp_spikes.keys()) and ('artifactTreshold' in grp_spikes.keys()):
# input_ = raw_input('Spike and Artifact detection thresholds exist already. Do you want to re-detect spikes? (\'y\', or any other key for no) : ')
# if input_ != 'y':
# detectSpikes = False
if detectSpikes:
# get time of the stimuls
if stim:
# in case of external stimulation: exclude period of stimuli
stimuli = self.analyzed_data['stimulation_data/stimulus_times'].value
startStim = np.array(stimuli / dt, dtype=int)
endStim = int(stimuli[-1] / dt) + int(stimRinging / dt) # eDataReplaced = copy(eData)
# high-pass filter recording #################################
# eDataHP = self.analysisTools.highpass(eData,highpassfreq,rate,corners=4,zerophase=True)
eDataHP = butter_highpass(eData, rate, highpassfreq, order=4)
#self.h5pyTools.createOverwriteDS(grp_spikes, 'ephys_data_high-pass', eDataHP)
# detect spikes ################################################
app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Data plotting")
win.resize(1800, 600)
win.setWindowTitle('high-pass filtered recording')
label = pg.LabelItem(justify='right')
win.addItem(label)
pg.setConfigOptions(antialias=True)
x2 = np.linspace(-100, 100, 1000)
data2 = np.sin(x2) / x2
p8 = win.addPlot(row=1, col=0, title="set threshold for spike detection with mouse click")
p8.plot(eDataHP, pen=(255, 255, 255, 200))
# lr = pg.LinearRegionItem([400,700])
# lr.setZValue(-10)
# p8.addItem(lr)
vLine = pg.InfiniteLine(angle=90, movable=False)
hLine = pg.InfiniteLine(angle=0, movable=False)
hLineSpikes = pg.InfiniteLine(angle=0, pen=pg.mkPen(0, 255, 0), movable=False)
hLineArtifacts = pg.InfiniteLine(angle=0, pen=pg.mkPen(255, 0, 0), movable=False)
p8.addItem(vLine, ignoreBounds=True)
p8.addItem(hLine, ignoreBounds=True)
p8.addItem(hLineSpikes, ignoreBounds=True)
p8.addItem(hLineArtifacts, ignoreBounds=True)
vb = p8.vb
# detectionTreshold = empty(0)
def detectSpikeTimes(tresh):
global detectionTreshold
excursion = eDataHP < tresh # threshold ephys trace
excursionInt = np.array(excursion, dtype=int) # convert boolean array into array of zeros and ones
diff = excursionInt[1:] - excursionInt[:-1] # calculate difference
spikeStart = np.arange(len(eDataHP))[np.concatenate((np.array([False]), diff == 1))] # a difference of one is the start of a spike
spikeEnd = np.arange(len(eDataHP))[np.concatenate((np.array([False]), diff == -1))] # a difference of -1 is the spike end
if (spikeEnd[0] - spikeStart[0]) < 0.: # if trace starts below threshold
spikeEnd = spikeEnd[1:]
if (spikeEnd[-1] - spikeStart[-1]) < 0.: # if trace ends below threshold
spikeStart = spikeStart[:-1]
if len(spikeStart) != len(spikeEnd): # unequal lenght of starts and ends is a problem of course
print('problem in length of spikeStart and spikeEnd')
sys.exit(1)
spikeT = []
for i in range(len(spikeStart)):
if (spikeEnd[i] - spikeStart[i]) > 10: # ignore if difference between end and start is smaller than 15 points
nMin = np.argmin(eDataHP[spikeStart[i]:spikeEnd[i]]) + spikeStart[i]
spikeT.append(nMin)
# detectionTreshold = tresh
return spikeT
def mouseMoved(evt):
pos = evt[0] ## using signal proxy turns original arguments into a tuple
if p8.sceneBoundingRect().contains(pos):
mousePoint = vb.mapSceneToView(pos)
index = int(mousePoint.x())
if index > 0 and index < len(eDataHP):
label.setText("<span style='font-size: 12pt'>x=%0.1f, <span style='font-size: 12pt'>y=%s</span>" % (mousePoint.x(), eDataHP[index]))
vLine.setPos(mousePoint.x())
hLine.setPos(mousePoint.y())
pointSpikes = [0]
pointArtifacts = [0]
sSpikes = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(0, 255, 0))
sSpikes.addPoints(x=pointSpikes, y=len(pointSpikes) * [0])
p8.addItem(sSpikes)
sArtifacts = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 0, 0))
sArtifacts.addPoints(x=pointArtifacts, y=len(pointArtifacts) * [0])
p8.addItem(sArtifacts)
def mouseClickedSpikes(evt):
posClick = evt.pos()
if p8.sceneBoundingRect().contains(posClick):
mousePointC = vb.mapSceneToView(posClick)
hLineSpikes.setPos(mousePointC.y())
threshold = mousePointC.y()
pointSpikes = detectSpikeTimes(threshold)
# print 'spikes clicked:',pointSpikes
sSpikes.setData(x=pointSpikes, y=eDataHP[pointSpikes])
def mouseClickedArtifacts(evt):
posClick = evt.pos()
if p8.sceneBoundingRect().contains(posClick):
mousePointC = vb.mapSceneToView(posClick)
hLineArtifacts.setPos(mousePointC.y())
# print type(evt)
threshold = mousePointC.y()
pointArtifacts = detectSpikeTimes(threshold)
# sArtifacts.clear()
sSpikes.setData(x=spikesRaw[0], y=spikesRaw[1])
sArtifacts.setData(x=pointArtifacts, y=eDataHP[pointArtifacts])
# first graphical dialog to set spike treshold
proxy = pg.SignalProxy(p8.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)
p8.scene().sigMouseClicked.connect(mouseClickedSpikes)
pdb.set_trace() # input_ = input("Chose spike treshold in graphical window. Press any button to continue.")
spikesRaw = sSpikes.getData()
spikeTreshold = hLineSpikes.getPos()[1] # copy(detectionTreshold)
# second graphical dialog to set treshold for artifacts
p8.scene().sigMouseClicked.disconnect(mouseClickedSpikes)
p8.scene().sigMouseClicked.connect(mouseClickedArtifacts)
pdb.set_trace()
# input_ = input("Chose artifact treshold in graphical window. Press any button to continue.")
falseSpikes = sArtifacts.getData()
artifactTreshold = hLineArtifacts.getPos()[1]
while True:
input_ = input("Enter pairs of indicies of regions to excluce from spike detection (e.g. [[0,700],[5450,5560]]). Press any number if None. : ")
try:
aaa = len(input_)
except:
print('No regions to exclude specified.')
exclusionBorders = None
break
else:
print('recorded')
exclusionBorders = input_
break
while True:
input2_ = input("Enter steps to exclude after stimulus onset - length of stimulus artifact (e.g. 200 corresponding to 2 ms). Press any key if None. : ")
try:
type(input2_)
except:
print('No regions to exclude specified.')
artifactLength = None
break
else:
artifactLength = input2_
break
#
# pdb.set_trace()
lspikes = spikesRaw[0].tolist()
lartif = falseSpikes[0].tolist()
spikes0 = [x for x in lspikes if x not in lartif]
# add spike artifacts to regions to remove
if artifactLength:
if exclusionBorders == None:
exclusionBorders = []
if stim:
for i in range(len(startStim)):
exclusionBorders.append([startStim[i], startStim[i] + artifactLength])
# remove spikes which fall in to regions to exclude
if exclusionBorders:
spikes1 = list(spikes0)
for n in range(len(exclusionBorders)):
spikes1 = [x for x in spikes1 if not (x > exclusionBorders[n][0] and x < exclusionBorders[n][1])]
spikeTimes = eTime.value[np.array(spikes1, dtype=int)]
#firingRate = brian.firing_rate(spikeTimes)
#cv = brian.CV(spikeTimes)
# pdb.set_trace()
######################################################
# convolv original spike trains with Gaussian kernels
binnedspikes, _ = np.histogram(spikeTimes, tbins)
spikesconv = scipy.ndimage.filters.gaussian_filter1d(np.array(binnedspikes, float), sigma=nspikecountwindow)
# convert the convolved spike trains to units of spikes/sec
spikesconv *= 1. / binWidth
# save data
#self.h5pyTools.createOverwriteDS(grp_spikes, 'spikeTreshold', array([spikeTreshold]))
#self.h5pyTools.createOverwriteDS(grp_spikes, 'artifactTreshold', array([artifactTreshold]))
#self.h5pyTools.createOverwriteDS(grp_spikes, 'spikes', spikeTimes)
#self.h5pyTools.createOverwriteDS(grp_spikes, 'firing_rate_evolution', spikesconv, ['dt', binWidth])
#self.h5pyTools.createOverwriteDS(grp_spikes, 'firing_rate', array([firingRate]))
#self.h5pyTools.createOverwriteDS(grp_spikes, 'CV', array([cv]))
def NormalizeData(data):
return (data - np.min(data)) / (np.max(data) - np.min(data))
#################################################################################
# detect spikes in ephys trace
#################################################################################
def detectSpikeTimes(tresh,eDataHP,ephysTimes,positive=True,plot=False):
#global detectionTreshold
while True:
if positive :
excursion = eDataHP > tresh # threshold ephys trace
else:
excursion = eDataHP < tresh
excursionInt = np.array(excursion, dtype=int) # convert boolean array into array of zeros and ones
diff = excursionInt[1:] - excursionInt[:-1] # calculate difference
spikeStart = np.arange(len(eDataHP))[np.concatenate((np.array([False]), diff == 1))] # a difference of one is the start of a spike
spikeEnd = np.arange(len(eDataHP))[np.concatenate((np.array([False]), diff == -1))] # a difference of -1 is the spike end
if len(spikeEnd)>0 and len(spikeStart)>0:
if (spikeEnd[0] - spikeStart[0]) < 0.: # if trace starts below threshold
spikeEnd = spikeEnd[1:]
if (spikeEnd[-1] - spikeStart[-1]) < 0.: # if trace ends below threshold
spikeStart = spikeStart[:-1]
if len(spikeStart) != len(spikeEnd): # unequal lenght of starts and ends is a problem of course
print('problem in length of spikeStart and spikeEnd')
sys.exit(1)
spikeT = []
spikeStart = spikeStart[spikeStart>100]
#for i in range(len(spikeStart)):
# #if (spikeEnd[i] - spikeStart[i]) > 10: # ignore if difference between end and start is smaller than 15 points
# nMin = spikeStart[i] #np.argmin(eDataHP[spikeStart[i]:spikeEnd[i]]) + spikeStart[i]
# spikeT.append(nMin)
# detectionTreshold = tresh
#pdb.set_trace()
spikeTimes = ephysTimes[spikeStart]
if plot:
fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
ax.plot(ephysTimes,eDataHP)
ax.plot(ephysTimes[spikeStart], eDataHP[spikeStart],'.')
ax.axhline(y=tresh, ls='--', c='0.5')
plt.show()
if plot:
print('Is threshold ok? ->No : type new threshold value ->Yes : press Enter')
recInput = input()
if recInput == "":
break
else:
tresh = float(recInput)
print('new threshold : ', tresh)
else:
break
#recInputIdx = [int(i) for i in recInput.split(',')]
return (spikeTimes,spikeStart,tresh)
#################################################################################
# maps an abritray input array to the entire range of X-bit encoding
#################################################################################
def mapToXbit(inputArray,xBitEncoding):
oldMin = np.min(inputArray)
oldMax = np.max(inputArray)
newMin = 0.
newMax = 2**xBitEncoding-1.
normXBit = newMin + (inputArray - oldMin) * newMax / (oldMax - oldMin)
normXBitInt = np.array(normXBit, dtype=int)
return normXBitInt
#################################################################################
# maps an abritray input array to the entire range of X-bit encoding
#################################################################################
# dataAnalysis.determineFrameTimes(exposureArray[0],arrayTimes,frames)
def determineFrameTimes(exposureArray,arrayTimes,frames,rec=None):
display = False
#pdb.set_trace()
numberOfFrames = len(frames)
exposure = exposureArray > 20 # threshold trace
exposureInt = np.array(exposure, dtype=int) # convert boolean array into array of zeros and ones
difference = np.diff(exposureInt) # calculate difference
expStart = np.arange(len(exposureArray))[np.concatenate((np.array([False]), difference == 1))] # a difference of one is the start of a spike
expEnd = np.arange(len(exposureArray))[np.concatenate((np.array([False]), difference == -1))] # a difference of -1 is the spike end
if (expEnd[0] - expStart[0]) < 0.: # if trace starts above threshold
expEnd = expEnd[1:]
if (expEnd[-1] - expStart[-1]) < 0.: # if trace ends above threshold
expStart = expStart[:-1]
frameDuration = expEnd - expStart
midExposure = (expStart + expEnd)/2
expStartTime = arrayTimes[expStart.astype(int)]
expEndTime = arrayTimes[expEnd.astype(int)]
#framesIdxDuringRec = np.array(len(softFrameTimes))[(arrayTimes[expEnd[0]]+0.002) < softFrameTimes]
#framesIdxDuringRec = framesIdxDuringRec[:len(expStart)]
if arrayTimes[int(midExposure[0])]<0.015 and arrayTimes[int(midExposure[0])]>=0.003:
recordedFrames = frames[3:(len(midExposure) + 3)]
elif arrayTimes[int(midExposure[0])]<0.003:
recordedFrames = frames[2:(len(midExposure) + 2)]
else:
recordedFrames = frames[:len(midExposure)]
print('number of tot. frames, recorded frames, exposures start, end :',numberOfFrames,len(recordedFrames), len(expStart), len(expEnd))
if display:
ledON = np.zeros(len(exposureArray))
for i in range(11):
ledON[((i*1.)<=arrayTimes) & ((i*1.+0.2)>arrayTimes)] = 1.
ledON[29.<=arrayTimes] = 1.
data = np.loadtxt('/home/mgraupe/2019.04.01_000-%s.csv' % (rec[-3:]),delimiter=',',skiprows=1,usecols=(0,1))
print(len(data))
plt.plot(arrayTimes,exposureArray/32.)
plt.plot(arrayTimes,ledON)
print('fist frame at %s sec' % arrayTimes[int(midExposure[0])],end='')
if arrayTimes[int(midExposure[0])]<0.015 and arrayTimes[int(midExposure[0])]>=0.003:
plt.plot(arrayTimes[midExposure.astype(int)], (data[3:(len(midExposure) + 3), 1] - 148.6) / 105.4, 'o-')
print(3)
elif arrayTimes[int(midExposure[0])]<0.003:
plt.plot(arrayTimes[midExposure.astype(int)], (data[2:(len(midExposure) + 2), 1] - 148.6) / 105.4, 'o-')
print(2)
else:
plt.plot(arrayTimes[midExposure.astype(int)], (data[:len(midExposure), 1] - 148.6) / 105.4, 'o-')
print(0)
#plt.plot(softFrameTimes[data[:-6,0].astype(np.int)+6],(data[:-6,1]-148.6)/105.4)
#plt.plot(softFrameTimes,np.ones(len(softFrameTimes)),'|')
plt.show()
pdb.set_trace()
return (expStartTime,expEndTime,recordedFrames)
#################################################################################
def generatePlotWithSTD(data,std=[2,3,4],names = None):
matplotlib.use('TkAgg')
nData = len(data)
fig = plt.figure(figsize=(15,15))
for i in range(nData):
ax0 = fig.add_subplot(nData,1,i+1)
if names is not None:
ax0.set_title('%s' % names[i])
STD = np.std(data[i])
MM = np.mean(data[i])
for n in range(len(std)):
ax0.axhline(y=MM+std[n]*STD,ls='--',c=plt.cm.RdYlBu(n/len(std)),label='%s STD' % std[n])
ax0.axhline(y=MM-std[n]*STD, ls='--', c=plt.cm.RdYlBu(n/len(std)))
ax0.axhline(y=MM,c='C1',label='mean')
ax0.plot(data[i],c='C0')
if i==2:
ax0.plot(np.abs(data[i]), c='C4')
ax0.legend()
plt.show()
#################################################################################
# maps an abritray input array to the entire range of X-bit encoding
#################################################################################
def determineFramesToExclude(frames,probIdx):
listOfFramesToExclude = []
canBeUsed = True
# first let's decide on how many LED's (if any) are present in the FOV
for i in range(len(probIdx)):
currIdx = probIdx[i]
continueDetectLoop = True
while continueDetectLoop:
print('checking idx, started at :', currIdx, probIdx[i])
#frame8bit = np.array(np.transpose(frames[currIdx]), dtype=np.uint8)
img = cv2.cvtColor(frames[currIdx], cv2.COLOR_GRAY2BGR)
# rungs = []
#imgPure = img.copy()
cv2.imshow("PureImage", img)
print('e if to exclude; r to remove from exclude; left right arrows to go back-forward one frame; o to specify another idx; f to move to next; x if recording contains too many errors and cannot be used :')
PressedKey = cv2.waitKey(0)
print(PressedKey)
if PressedKey == 81: # left arrow key
currIdx -=1
elif PressedKey == 83: # right arrow key
currIdx +=1
elif PressedKey == 101: # y key
print('%s added to exclude list' %currIdx)
listOfFramesToExclude.append(currIdx)
elif PressedKey == 114: # e key
print('%s removed from exclude list' % currIdx)
listOfFramesToExclude.remove(currIdx)
elif PressedKey == 111 : # o key
nIdx = input('specify a new idx to check :')
currIdx = int(nIdx)
elif PressedKey == 102: # f key
continueDetectLoop = False
elif PressedKey == 120: # x key
canBeUsed = False
break
else:
print('Key not recognized, try again.')
print('current exclude list :',listOfFramesToExclude)
if not canBeUsed:
break
cv2.destroyWindow("PureImage") # only destroy window at the end of the exploration
lofEx = list(dict.fromkeys(listOfFramesToExclude)) # removes duplicates
lofEx.sort()
print('starting list of indexes :', probIdx)
print('indexes to exclude :', lofEx)
lofEx = np.asarray(lofEx,dtype=int)
#pdb.set_trace()
return (lofEx, canBeUsed)
#################################################################################
# maps an abritray input array to the entire range of X-bit encoding
#################################################################################
# ([ledTraces,ledCoordinates,frames,softFrameTimes,imageMetaInfo],[exposureDAQArray,exposureDAQArrayTimes],[ledDAQControlArray, ledDAQControlArrayTimes],verbose=True)
def determineErroneousFrames(frames):
# first threshold metrics of the movie to detect and exclude erroneous frames with horizontal lines, flash-back frames #########################
frameDiff = []
lineDiff = []
print('calculating frame and line diffs ... ',end='')
for i in range(len(frames)):
if i>0:
frameDiffAllPix = cv2.absdiff(frames[i],frames[i-1])
fD = np.average(frameDiffAllPix)
frameDiff.append(fD)
lineDiffAllLines = cv2.absdiff(frames[i][:,1:],frames[i][:,:-1])
lD = np.average(lineDiffAllLines,axis=0)
lineDiff.append(lD)
#pdb.set_trace()
print('done!')
frameDiff = np.asarray(frameDiff)
lineDiff = np.asarray(lineDiff)
lineDiffSum = np.sum(lineDiff,axis=1)
frameDiffDiff = np.diff(frameDiff)
generatePlotWithSTD([lineDiffSum,frameDiff,frameDiffDiff],std=[3,3.5,4],names=['lineDiffSum','frameDiff','diff of FrameDiff'])
# trick to display the above image
#frame8bit = np.array(np.transpose(frames[0]), dtype=np.uint8)
img = cv2.cvtColor(frames[0], cv2.COLOR_GRAY2BGR)
cv2.imshow('HoldImage',img)
cv2.waitKey(0) #cv2.imshow()
cv2.destroyWindow('HoldImage')
thresholdingInput = input("Specify which trace to use (lineDiffSum - 1, frameDiff - 2, diff of frameDiff - 3; and which multiple of the STD (e.g. 1 3.5); type '4 0' if recording cannote be used (too many errors); '5 0' for recordings without errors : ")
threshold = [float(i) for i in thresholdingInput.split()]
print('choice :', threshold)
#pdb.set_trace()
if threshold[0] == 5.:
idxToExclude = np.array([], dtype=np.int64)
canBeUsed = True
plt.close('all')
return(idxToExclude,canBeUsed)
elif threshold[0] == 1.:
thresholded = lineDiffSum > np.mean(lineDiffSum) + np.std(lineDiffSum)*threshold[1]
outlierIdx = np.arange(len(lineDiffSum))[thresholded] # use indices taking into account missed frames
elif threshold[0] == 2.:
thresholded = frameDiff > np.mean(frameDiff) + np.std(frameDiff) * threshold[1]
outlierIdx = np.arange(len(frameDiff))[thresholded] # use indices taking into account missed frames
outlierIdx += 1 # this is since the difference trace does not start at at the first frame but at the difference between first and second frame
elif threshold[0] == 3.:
thresholded = np.abs(frameDiffDiff) > np.mean(frameDiffDiff) + np.std(frameDiffDiff)*threshold[1]
outlierIdx = np.arange(len(frameDiffDiff))[thresholded] # use indices taking into account missed frames
outlierIdx += 2 # this is since the difference trace does not start at at the first frame but at the difference between first and second frame
elif threshold[0] == 4.:
canBeUsed = False
idxToExclude = np.array([], dtype=np.int64)
plt.close('all')
return (idxToExclude, canBeUsed)
print('length and identity of possible erronous frames :' , len(outlierIdx), outlierIdx)
(idxExclude,canBeUsed) = determineFramesToExclude(frames,outlierIdx)
#excludeMask = np.ones(len(ledVideoRoi[2]),dtype=bool)
# add indicies for equivalent frames
sameFrames = (frameDiff == 0)
sameFrameIdx = np.arange(len(frameDiff))[sameFrames]
sameFrameIdx += 1
print('same frames were recorded here :', sameFrameIdx)
idxToExclude = np.sort(np.concatenate((sameFrameIdx, idxExclude)))
#pdb.set_trace()
#excludeMask[idxToExclude] = False
plt.close('all')
return (idxToExclude,canBeUsed)
#################################################################################
# maps an abritray input array to the entire range of X-bit encoding
#################################################################################
# ([ledTraces,ledCoordinates,frames,softFrameTimes,imageMetaInfo,idxToExclude],[exposureDAQArray,exposureDAQArrayTimes],[ledDAQControlArray, ledDAQControlArrayTimes],verbose=True)
def determineFrameTimesBasedOnLED(ledVideoRoi, cameraExposure, ledDAQc, pc, verbose=False, tail=False,manualThreshold=False):
##############################################################################################################
# auxiliary function to convert bimodal trace into boolean array
def traceToBinary(trace,threshold=None):
rescaledTrace = (trace - np.min(trace)) / (np.max(trace) - np.min(trace))
if threshold is None:
rescaledTraceBin = rescaledTrace > 0.3
else:
rescaledTraceBin = rescaledTrace > threshold
return (rescaledTrace,rescaledTraceBin)
##############################################################################################################
def traceToBinaryForChangingMaxMin(trace,threshold=None):
maxTrace = ndimage.maximum_filter(trace, size=5*2)
minTrace = ndimage.minimum_filter(trace, size=5*2)
rescaledTrace = (trace - minTrace) / (maxTrace - minTrace)
if threshold is None:
rescaledTraceBin = rescaledTrace > 0.3
else:
rescaledTraceBin = rescaledTrace > threshold
return (rescaledTrace,rescaledTraceBin)
##############################################################################################################
# maps LED daq control trace to boolean array ################################################################
# TODO this number is zero on the behavior setup and 4 here
if pc == 'behaviorPC':
LEDcontrolIdx = 0 # which trace of the DAQ recording is linked to the !!!
elif pc == '2photonPC':
LEDcontrolIdx = 4
else:
print('Make sure the computer of the recording is specified.')
ledDAQcontrolBin = traceToBinary(ledDAQc[0][LEDcontrolIdx])[1] # here the threshold is not important as the trace is binary to start out with
# convert LED roi traces from video to boolean arrays
ledVideoRoiBins = []
ledVideoRoiRescaled = []
allLEDVideoRoiValues = []
# determine threshold [ledTraces,ledCoordinates,frames,softFrameTimes,imageMetaInfo,idxToExclude]
# tail covering the LEDs for some
if tail:
matplotlib.use('TkAgg')
print(' in tail ...')
anticipateCorrectValues = True
# for i in range(ledVideoRoi[1][0]):
# plt.plot(ledVideoRoi[0][i],'o-',ms=2,label='%s' % i)
# plt.legend(loc=1)
# plt.show()
if anticipateCorrectValues:
# inputA = input('Index until which the recording is not affected by the tail (integer; type 0 if recording is ok) :')
inputA=350
untilOKidx = int(inputA)
if untilOKidx != 0:
period = [7, 7, 7, 5]
for i in range(ledVideoRoi[1][0]):
maxVal = np.max(ledVideoRoi[0][i][20:untilOKidx])
minVal = np.min(ledVideoRoi[0][i][20:untilOKidx])
for n in range(period[i]):
# repeatValue(ledVideoRoi[0][i][(untilOKidx+n):],7)
isHigh = [True if abs(ledVideoRoi[0][i][(untilOKidx + n)] - maxVal) < abs(ledVideoRoi[0][i][(untilOKidx + n)] - minVal) else False]
if isHigh:
ledVideoRoi[0][i][(untilOKidx + n):][::period[i]] = ledVideoRoi[0][i][(untilOKidx + n)]
else:
ledVideoRoi[0][i][(untilOKidx + n):][::period[i]] = ledVideoRoi[0][i][(untilOKidx + n)] # ledVideoRoi[0][i][]
else:
maxV = [254,251,250,213]
minV = [200,174,217,147]
idxMaxV = [[8580,8582,8583,8585],
[],
[8589],
[]]
idxMinV = [[8581,8584,8586,8588],
[8579,8580],
[8590,8591],
[8584,8585,8586,8589,8590,8591]]
for i in range(4):
for n in idxMaxV[i]:
ledVideoRoi[0][i][n] = maxV[i]
for m in idxMinV[i]:
ledVideoRoi[0][i][m] = minV[i]
# fig = plt.figure()
# for i in range(ledVideoRoi[1][0]):
# #ax = fig.add_subplot(3,1,i)
# plt.plot(ledVideoRoi[0][i],'o-',ms=2,label='%s' % i)
# #ax.set_xlim(8)
# plt.legend(loc=1)
# plt.show()
# pdb.set_trace()
###########
for i in range(ledVideoRoi[1][0]):
allLEDVideoRoiValues.extend(traceToBinaryForChangingMaxMin(ledVideoRoi[0][i])[0]) # rescale all values to [0,1] and stack them
allLEDVideoRoiValues = np.sort(np.asarray(allLEDVideoRoiValues)) # convert to array and sort
luminocityDifferences = np.diff(allLEDVideoRoiValues)
idxMaxDiff = np.argmax(luminocityDifferences)
LEDVideoThreshold = allLEDVideoRoiValues[idxMaxDiff] + (allLEDVideoRoiValues[idxMaxDiff+1] - allLEDVideoRoiValues[idxMaxDiff])/2.
if pc == 'behaviorPC':
#illumLEDcontrolThreshold = LEDVideoThreshold**4.49185827 # mapping, i.e. exponent, from tools/fitOfIlluminationValues
illumLEDcontrolThreshold = LEDVideoThreshold**18.37008924
elif pc == '2photonPC':
illumLEDcontrolThreshold = LEDVideoThreshold**2.61290794 # 2pinvivo
# if (illumLEDcontrolThreshold) < 0.08 or manualThreshold:
# print('thresholds before: ',LEDVideoThreshold, illumLEDcontrolThreshold)
# #print('LED threshold extremly low! Fixed by setting both threshold to 0.8.')
# fig = plt.figure(figsize=(10,10))
# ax = fig.add_subplot(111)
# #ax.plot(np.ones(len(allLEDVideoRoiValues)),allLEDVideoRoiValues,'.',ms=0.5)
# ax.axhline(y=LEDVideoThreshold,ls='--',c='C0')
# ax.plot(allLEDVideoRoiValues,'.',ms=0.5,c='C0')
# #plt.plot(np.ones(len(ledDAQcontrolBin)),ledDAQcontrolBin,'.')
# #ax.plot(ledDAQcontrolBin,'.',ms=0.5)
# plt.show()
# # thresholdInput = '0.8,0.8'
# # thresholdInput = ''
# thresholdInput = input('Provide alternative thresholds (e.g. 0.8,0.7), otherwise press enter to keep current thresholds : ')
# if not thresholdInput == '':
# newThresholds = [float(i) for i in thresholdInput.split(',')]
# LEDVideoThreshold = newThresholds[0]
# illumLEDcontrolThreshold = newThresholds[1]