-
Notifications
You must be signed in to change notification settings - Fork 0
/
AS.py
2941 lines (2721 loc) · 124 KB
/
AS.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 25 15:21:14 2020
@author: fearthekraken
"""
import sys
import re
import os.path
import numpy as np
import pandas as pd
import copy
from itertools import chain
from functools import reduce
import matplotlib
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
import scipy.io as so
import scipy.stats as stats
import math
from statsmodels.stats.multicomp import MultiComparison
from statsmodels.stats.anova import AnovaRM
import pdb
import pyphi
import sleepy
import pwaves
################# SUPPORT FUNCTIONS #################
def upsample_mx(x, nbin, axis=1):
"""
Upsample input data by duplicating each element (if $x is a vector)
or each row/column (if $x is a 2D array) $nbin times
@Params
x - input data
nbin - factor by which to duplicate
axis - specifies dimension to upsample for 2D input data
if 0 or 'y' - duplicate rows
if 1 or 'x' - duplicate columns
@Returns
y - upsampled data
"""
if nbin == 1:
return x
# get no. elements in vector to be duplicated
if axis == 0 or axis == 'y' or x.ndim == 1:
nelem = x.shape[0]
elif axis == 1 or axis == 'x':
nelem = x.shape[1]
# upsample 1D input data
if x.ndim == 1:
y = np.zeros((nelem * nbin,))
for k in range(nbin):
y[k::nbin] = x
# upsample 2D input data
else:
if axis == 0 or axis == 'y':
y = np.zeros((nelem * nbin, x.shape[1]))
for k in range(nbin):
y[k::nbin, :] = x
elif axis == 1 or axis == 'x':
y = np.zeros((x.shape[0], nelem * nbin))
for k in range(nbin):
y[:, k::nbin] = x
return y
def downsample_vec(x, nbin):
"""
Downsample input vector by replacing $nbin consecutive bins by their mean
@Params
x - input vector
bin - factor by which to downsample
@Returns
y - downsampled vector
"""
n_down = int(np.floor(len(x) / nbin))
x = x[0:n_down*nbin]
x_down = np.zeros((n_down,))
for i in range(nbin) :
idx = list(range(i, int(n_down*nbin), int(nbin)))
x_down += x[idx]
y = x_down / nbin
return y
def downsample_mx(x, nbin, axis=1):
"""
Downsample input matrix by replacing $nbin consecutive rows or columns by their mean
@Params
x - input matrix
nbin - factor by which to downsample
axis - specifies dimension to downsample
if 0 or 'y' - downsample rows
if 1 or 'x' - downsample columns
@Returns
y - downsampled matrix
"""
# downsample rows
if axis == 0 or axis == 'y':
n_down = int(np.floor(x.shape[0] / nbin))
x = x[0:n_down * nbin, :]
x_down = np.zeros((n_down, x.shape[1]))
for i in range(nbin):
idx = list(range(i, int(n_down * nbin), int(nbin)))
x_down += x[idx, :]
# downsample columns
elif axis == 1 or axis == 'x':
n_down = int(np.floor(x.shape[1] / nbin))
x = x[:, 0:n_down * nbin]
x_down = np.zeros((x.shape[0], n_down))
for i in range(nbin):
idx = list(range(i, int(n_down * nbin), int(nbin)))
x_down += x[:, idx]
y = x_down / nbin
return y
def time_morph(X, nstates):
"""
Set size of input data to $nstates bins
X - input data; if 2D matrix, resample columns
nstates - no. elements/columns in returned vector/matrix
@Returns
Y - resampled data
"""
# upsample elements/columns by $nstates
if X.ndim == 1:
m = X.shape[0]
else:
m = X.shape[1]
A = upsample_mx(X, nstates)
# downsample A to desired size
if X.ndim == 1:
Y = downsample_vec(A, int((m * nstates) / nstates))
else:
Y = downsample_mx(A, int((m * nstates) / nstates))
return Y
def smooth_data(x, sig):
"""
Smooth data vector using Gaussian kernel
@Params
x - input data
sig - standard deviation for smoothing
@Returns
sm_data - smoothed data
"""
sig = float(sig)
if sig == 0.0:
return x
# create gaussian
gauss = lambda x, sig : (1/(sig*np.sqrt(2.*np.pi)))*np.exp(-(x*x)/(2.*sig*sig))
bound = 1.0/10000
L = 10.
p = gauss(L, sig)
while (p > bound):
L = L+10
p = gauss(L, sig)
# create smoothing filter
F = [gauss(x, sig) for x in np.arange(-L, L+1.)]
F = F / np.sum(F)
# convolve data vector with filter
sm_data = scipy.signal.convolve2d(np.array((x,)), np.array((F,)), 'same', 'symm')
return sm_data
def smooth_data2(x, nstep):
"""
Smooth data by replacing each of $nstep consecutive bins with their mean
@Params
x - input data
nstep - no. consecutive samples to average
@Returns
x2 - smoothed data
"""
x2 = [[np.mean(x[i:i+nstep])]*nstep for i in np.arange(0, len(x), nstep)]
x2 = list(chain.from_iterable(x2))
x2 = np.array((x2))
x2 = x2[0:len(x)]
return x2
def convolve_data(x, psmooth, axis=2):
"""
Smooth data by convolving with filter defined by $psmooth
@Params
x - input data
psmooth - integer or 2-element tuple describing filter for convolution
* for 2-element $psmooth param, idx1 smooths across rows and idx2 smooths
across columns
axis - specifies filter if $psmooth is an integer
if 0 or 'y' - convolve across rows
if 1 or 'x' - convolve across columns
if 2 or 'xy' - convolve using box filter
@Returns
smooth - smoothed data
"""
if not psmooth:
return x
if np.isnan(x).any():
raise KeyError('ERROR: NaN(s) found in data')
# smooth across 1D data vector
if x.ndim == 1:
if type(psmooth) in [int, float]:
filt = np.ones(psmooth) / np.sum(np.ones(psmooth))
elif type(psmooth) in [list, tuple] and len(psmooth)==1:
filt = np.ones(psmooth[0]) / np.sum(np.ones(psmooth[0]))
else:
raise KeyError('ERROR: incorrect number of values in $psmooth parameter for 1-dimensional data')
xsmooth = scipy.signal.convolve(x, filt, mode='same')
# smooth 2D data matrix
elif x.ndim == 2:
if type(psmooth) in [int, float]:
if axis == 0 or axis == 'y':
filt = np.ones((psmooth,1))
elif axis == 1 or axis == 'x':
filt = np.ones((1, psmooth))
elif axis == 2 or axis == 'xy':
filt = np.ones((psmooth, psmooth))
elif type(psmooth) in [list, tuple] and len(psmooth)==2:
filt = np.ones((psmooth[0], psmooth[1]))
else:
raise KeyError('ERROR: incorrect number of values in $psmooth parameter for 2-dimensional data')
filt = filt / np.sum(filt)
xsmooth = scipy.signal.convolve2d(x, filt, boundary='symm', mode='same')
else:
raise KeyError('ERROR: inputted data must be a 1 or 2-dimensional array')
return xsmooth
def load_recordings(ppath, trace_file, dose, pwave_channel=False):
"""
Load recording names, drug doses, and P-wave channels from .txt file
@Params
ppath - path to $trace_file
trace_file - .txt file with recording information
dose - if True, load drug dose info (e.g. '0' or '0.25' for DREADD experiments)
pwave_channel - if True, load P-wave detection channel ('X' for mice without clear P-waves)
@Returns
ctr_list - list of control recordings
* if $dose=True: exp_dict - dictionary of experimental recordings (keys=doses, values=list of recording names)
* if $dose=False: exp_list - list of experimental recordings
"""
# read in $trace_file
rfile = os.path.join(ppath, trace_file)
f = open(rfile, newline=None)
lines = f.readlines()
f.close()
# list of control recordings
ctr_list = []
# if file includes drug dose info, store experimental recordings in dictionary
if not dose:
exp_list = []
# if no dose info, store exp recordings in list
else:
exp_dict = {}
for l in lines :
# if line starts with $ or #, skip it
if re.search('^\s+$', l) :
continue
if re.search('^\s*#', l) :
continue
# a is any line that doesn't start with $ or #
a = re.split('\s+', l)
# for control recordings
if re.search('C', a[0]) :
# if file includes P-wave channel info, collect recording name and P-wave channel
if pwave_channel:
ctr_list.append([a[1], a[-2]])
# if no P-wave channel info, collect recording name
else:
ctr_list.append(a[1])
# for experimental recordings
if re.search('E', a[0]) :
# if no dose info, collect exp recordings in list
if not dose:
if pwave_channel:
exp_list.append([a[1], a[-2]])
else:
exp_list.append(a[1])
# if file has dose info, collect exp recordings in dictionary
# (keys=doses, values=lists of recording names)
else:
if a[2] in exp_dict:
if pwave_channel:
exp_dict[a[2]].append([a[1], a[-2]])
else:
exp_dict[a[2]].append(a[1])
else:
if pwave_channel:
exp_dict[a[2]] = [[a[1], a[-2]]]
else:
exp_dict[a[2]] = [a[1]]
# returs 1 list and 1 dict if file has drug dose info, or 2 lists if not
if dose:
return ctr_list, exp_dict
else:
return ctr_list, exp_list
def load_surround_files(ppath, pload, istate, plaser, null, signal_type=''):
"""
Load raw data dictionaries from saved .mat files
@Params
ppath - folder with .mat files
pload - base filename
istate - brain state(s) to load data files
plaser - if True, load files for laser-triggered P-waves, spontaneous P-waves,
successful laser pulses, and failed laser pulses
if False, load file for all P-waves
null - if True, load file for randomized control points
signal_type - string indicating type of data loaded (e.g. SP, LFP), completes
default filename
@Returns
*if plaser --> lsr_pwaves - dictionaries with brain states as keys, and sub-dictionaries as values
Sub-dictionaries have mouse recordings as keys, with lists of 2D or 3D signals as values
Signals represent the time window surrounding each laser-triggered P-wave
spon_pwaves - signals surrounding each spontaneous P-wave
success_lsr - signals surrounding each successful laser pulse
fail_lsr - signals surrounding each failed laser pulse
null_pts - signals surrounding each random control point
data_shape - tuple with shape of the data from one trial
*if not plaser --> p_signal - signals surrounding each P-wave
null_signal - signals surrounding each random control point
data_shape - tuple with shape of the data from one trial
"""
if plaser:
filename = pload if isinstance(pload, str) else f'lsrSurround_{signal_type}'
lsr_pwaves = {}
spon_pwaves = {}
success_lsr = {}
fail_lsr = {}
null_pts = {}
try:
for s in istate:
# load .mat files with stored data dictionaries
lsr_pwaves[s] = so.loadmat(os.path.join(ppath, f'{filename}_lsr_pwaves_{s}.mat'))
spon_pwaves[s] = so.loadmat(os.path.join(ppath, f'{filename}_spon_pwaves_{s}.mat'))
success_lsr[s] = so.loadmat(os.path.join(ppath, f'{filename}_success_lsr_{s}.mat'))
fail_lsr[s] = so.loadmat(os.path.join(ppath, f'{filename}_fail_lsr_{s}.mat'))
if null:
null_pts[s] = so.loadmat(os.path.join(ppath, f'{filename}_null_pts_{s}.mat'))
# remove MATLAB keys so later functions can get recording list
for mat_key in ['__header__', '__version__', '__globals__']:
_ = lsr_pwaves[s].pop(mat_key)
_ = spon_pwaves[s].pop(mat_key)
_ = success_lsr[s].pop(mat_key)
_ = fail_lsr[s].pop(mat_key)
if null:
_ = null_pts[s].pop(mat_key)
data_shape = so.loadmat(os.path.join(ppath, f'{filename}_data_shape.mat'))['data_shape'][0]
print('\nLoading data dictionaries ...\n')
return lsr_pwaves, spon_pwaves, success_lsr, fail_lsr, null_pts, data_shape
except:
print('\nUnable to load .mat files - collecting new data ...\n')
return []
elif not plaser:
filename = pload if isinstance(pload, str) else f'Surround_{signal_type}'
p_signal = {}
null_signal = {}
try:
for s in istate:
# load .mat files with stored data
p_signal[s] = so.loadmat(os.path.join(ppath, f'{filename}_pwaves_{s}.mat'))
if null:
null_signal[s] = so.loadmat(os.path.join(ppath, f'{filename}_null_{s}.mat'))
# remove MATLAB keys so later functions can get recording list
for mat_key in ['__header__', '__version__', '__globals__']:
_ = p_signal[s].pop(mat_key)
if null:
_ = null_signal[s].pop(mat_key)
data_shape = so.loadmat(os.path.join(ppath, f'{filename}_data_shape.mat'))['data_shape'][0]
print('\nLoading data dictionaries ...\n')
return p_signal, null_signal, data_shape
except:
print('\nUnable to load .mat files - calculating new spectrograms ...\n')
return []
def get_emg_amp(mSP, mfreq, r_mu = [10,500]):
"""
Calculate EMG amplitude from input EMG spectrogram
@Params
mSP - EMG spectrogram
mfreq - list of frequencies, corresponding to $mSP rows
r_mu - [min,max] frequencies summed to get EMG amplitude
@Returns
p_mu - EMG amplitude vector
"""
i_mu = np.where((mfreq >= r_mu[0]) & (mfreq <= r_mu[1]))[0]
p_mu = np.sqrt(mSP[i_mu, :].sum(axis=0) * (mfreq[1] - mfreq[0]))
return p_mu
def highres_spectrogram(ppath, rec, nsr_seg=2, perc_overlap=0.95, recalc_highres=False,
mode='EEG', get_M=False):
"""
Load or calculate high-resolution spectrogram for a recording
@Params
ppath - base folder
rec - name of recording
nsr_seg, perc_overlap - set FFT bin size (s) and overlap (%) for spectrogram calculation
recalc_highres - if True, recalculate high-resolution spectrogram from EEG,
using $nsr_seg and $perc_overlap params
if False, load existing spectrogram from saved file
mode - specifies EEG channel for calculating spectrogram
'EEG' - return hippocampal spectrogram
'EEG2' - return prefrontal spectrogram
'EMG' - return EMG spectrogram
get_M - if True, load high-res brain state annotation from saved file
@Returns
SP - loaded or calculated high-res spectrogram
freq - list of spectrogram frequencies, corresponding to SP rows
t - list of spectrogram time bins, corresponding to SP columns
dt - no. seconds per SP time bin
M_dt - brain state annotation upsampled to match SP time resolution
"""
import time
if mode == 'EEG':
sp_file = 'SP'
elif mode == 'EEG2':
sp_file = 'SP2'
elif mode == 'EMG':
sp_file = 'mSP'
M_dt = np.nan
# load high-resolution spectrogram if it exists
if not recalc_highres:
if os.path.exists(os.path.join(ppath, rec, '%s_highres_%s.mat' % (sp_file.lower(), rec))):
try:
SPEC = so.loadmat(os.path.join(ppath, rec, '%s_highres_%s.mat' % (sp_file.lower(), rec)))
SP = SPEC[sp_file]
freq = SPEC['freq'][0]
t = SPEC['t'][0]
dt = SPEC['dt'][0][0] # number of seconds in each SP bin
nbin = SPEC['nbin'][0][0] # number of EEG/EMG samples in each SP bin
except:
recalc_highres = True
if get_M:
# load high-resolution brain state annotation if it exists, calculate if not
if os.path.exists(os.path.join(ppath, rec, 'remidx_highres_%s.mat' % rec)):
M_dt = np.squeeze(so.loadmat(os.path.join(ppath, rec, 'remidx_highres_%s.mat' % rec))['M'])
else:
M, _ = sleepy.load_stateidx(ppath, rec)
if len(M) == SP.shape[1]:
M_dt = M
elif len(M) < SP.shape[1]:
M_dt = time_morph(M, SP.shape[1])
so.savemat(os.path.join(ppath, rec, 'remidx_highres_%s.mat' % rec), {'M' : M_dt, 'S' : {}})
else:
recalc_highres = True
if recalc_highres:
print('Calculating high-resolution %s spectrogram for %s ...' % (mode, rec))
# load sampling rate, s per time bin, and raw EEG/EMG
sr = sleepy.get_snr(ppath, rec)
dt = nsr_seg*(1-perc_overlap)
if mode == 'EEG':
data = so.loadmat(os.path.join(ppath, rec, 'EEG.mat'), squeeze_me=True)['EEG']
elif mode == 'EEG2':
data = so.loadmat(os.path.join(ppath, rec, 'EEG2.mat'), squeeze_me=True)['EEG2']
elif mode == 'EMG':
data = so.loadmat(os.path.join(ppath, rec, 'EMG.mat'), squeeze_me=True)['EMG']
# calculate and save high-res spectrogram
freq, t, SP = scipy.signal.spectrogram(data, fs=sr, window='hanning', nperseg=int(nsr_seg * sr),
noverlap=int(nsr_seg * sr * perc_overlap))
nbin = len(data) / SP.shape[1]
so.savemat(os.path.join(ppath, rec, '%s_highres_%s.mat' % (sp_file.lower(), rec)), {sp_file:SP, 'freq':freq, 't':t, 'dt':dt, 'nbin':nbin})
time.sleep(1)
if get_M:
# upsample brainstate annotation in SP-resolution bins
M, _ = sleepy.load_stateidx(ppath, rec)
if len(M) == SP.shape[1]:
M_dt = M
elif len(M) < SP.shape[1]:
M_dt = time_morph(M, SP.shape[1])
elif len(M) > SP.shape[1]:
M_dt = np.zeros((SP.shape[1], )) # no valid way to downsample M yet
so.savemat(os.path.join(ppath, rec, 'remidx_highres_%s.mat' % rec), {'M' : M_dt, 'S' : {}})
return SP, freq, t, dt, nbin, M_dt
def adjust_brainstate(M, dt, ma_thr=20, ma_state=3, flatten_tnrem=False, keep_MA=[1,4,5], noise_state=2):
"""
Handle microarousals and transition states in brainstate annotation
@Params
M - brain state annotation
dt - s per time bin in M
ma_thr - microarousal threshold
ma_state - brain state to assign microarousals (2=wake, 3=NREM, 6=separate MA state)
flatten_tnrem - specifies handling of transition states, manually annotated
as 4 for successful transitions and 5 for failed transitions
if False - no change in annotation
if integer - assign all transitions to specified brain state (3=NREM, 4=general "transition state")
keep_MA - microarousals directly following any brain state in $keep_MA are exempt from
assignment to $ma_state; do not change manual annotation
noise_state - brain state to assign manually annotated EEG/LFP noise
@Returns
M - adjusted brain state annotation
"""
# assign EEG noise (X) to noise state
M[np.where(M==0)[0]] = noise_state
# handle microarousals
ma_seq = sleepy.get_sequences(np.where(M == 2.0)[0])
for s in ma_seq:
if 0 < len(s) < ma_thr/dt:
if M[s[0]-1] not in keep_MA:
M[s] = ma_state
# handle transition states
if flatten_tnrem:
M[np.where((M==4) | (M==5))[0]] = flatten_tnrem
return M
def adjust_spectrogram(SP, pnorm, psmooth, freq=[], fmax=False):
"""
Normalize and smooth spectrogram
@Params
SP - input spectrogram
pnorm - if True, normalize each frequency in SP its mean power
psmooth - 2-element tuple describing filter to convolve with SP
* idx1 smooths across rows/frequencies, idx2 smooths across columns/time
freq - optional list of SP frequencies, corresponding to rows in SP
fmax - optional cutoff indicating the maximum frequency in adjusted SP
@Returns
SP - adjusted spectrogram
"""
if psmooth:
if psmooth == True: # default box filter
filt = np.ones((3,3))
elif isinstance(psmooth, int): # integer input creates box filter with area $psmooth^2
filt = np.ones((psmooth, psmooth))
elif type(psmooth) in [tuple, list] and len(psmooth) == 2:
filt = np.ones((psmooth[0], psmooth[1]))
# smooth SP
filt = filt / np.sum(filt)
SP = scipy.signal.convolve2d(SP, filt, boundary='symm', mode='same')
# normalize SP
if pnorm:
SP_mean = SP.mean(axis=1)
SP = np.divide(SP, np.repeat([SP_mean], SP.shape[1], axis=0).T)
# cut off SP rows/frequencies above $fmax
if len(freq) > 0:
if fmax:
ifreq = np.where(freq <= fmax)[0]
if len(ifreq) < SP.shape[0]:
SP = SP[ifreq, :]
return SP
############### DATA ANALYSIS FUNCTIONS ###############
def dff_activity(ppath, recordings, istate, tstart=10, tend=-1, pzscore=False,
ma_thr=20, ma_state=3, flatten_tnrem=False):
"""
Plot average DF/F signal in each brain state
@Params
ppath - base folder
recordings - list of recordings
istate - brain state(s) to analyze
tstart, tend - time (s) into recording to start and stop collecting data
pzscore - if True, z-score DF/F signal by its mean across the recording
ma_thr, ma_state - max duration and brain state for microarousals
flatten_tnrem - brain state for transition sleep
@Returns
df - dataframe with avg DF/F activity in each brain state for each mouse
"""
states = {1:'REM', 2:'Wake', 3:'NREM', 4:'tNREM', 5:'failed-tNREM', 6:'Microarousals'}
# clean data inputs
if type(recordings) != list:
recordings = [recordings]
if type(istate) != list:
istate = [istate]
state_labels = [states[s] for s in istate]
mice = dict()
# get all unique mice
for rec in recordings:
idf = re.split('_', rec)[0]
if not idf in mice:
mice[idf] = 1
mice = list(mice.keys())
nmice = len(mice)
# create data dictionaries
nstates = len(istate)
mean_act = {m:[] for m in mice}
mean_var = {m:[] for m in mice}
mean_yerr = {m:[] for m in mice}
for rec in recordings:
idf = re.split('_', rec)[0]
print('Getting data for ' + rec + ' ... ')
# load sampling rate
sr = sleepy.get_snr(ppath, rec)
nbin = int(np.round(sr) * 2.5)
dt = (1.0 / sr) * nbin
# load and adjust brain state annotation
M = sleepy.load_stateidx(ppath, rec)[0]
M = adjust_brainstate(M, dt, ma_thr=ma_thr, ma_state=ma_state, flatten_tnrem=flatten_tnrem)
# define start and end points of analysis
istart = int(np.round(tstart/dt))
if tend == -1:
iend = M.shape[0]
else:
iend = int(np.round(tend/dt))
M = M[istart:iend]
# calculate DF/F signal using high cutoff frequency for 465 signal
# and very low cutoff frequency for 405 signal
pyphi.calculate_dff(ppath, rec, wcut=10, wcut405=2, shift_only=False)
# load DF/F calcium signal
dff = so.loadmat(os.path.join(ppath, rec, 'DFF.mat'), squeeze_me=True)['dffd'][istart:iend]
if pzscore:
dff = (dff-dff.mean()) / dff.std()
else:
dff *= 100.0
dff_mean = np.zeros((nstates,))
dff_var = np.zeros((nstates,))
dff_yerr = np.zeros((nstates,))
# get mean, variance, & SEM of DF/F signal in each brain state
for i, s in enumerate(istate):
sidx = np.where(M==s)[0]
dff_mean[i] = np.mean(dff[sidx])
dff_var[i] = np.var(dff[sidx])
dff_yerr[i] = np.std(dff[sidx]) / np.sqrt(len(dff[sidx])) # sem
mean_act[idf].append(dff_mean)
mean_var[idf].append(dff_var)
mean_yerr[idf].append(dff_yerr)
# create matrices of mouse-averaged DF/F stats (mice x brain states)
mean_mx = np.zeros((nmice, nstates))
var_mx = np.zeros((nmice, nstates))
yerr_mx = np.zeros((nmice, nstates))
for i,idf in enumerate(mice):
mean_mx[i,:] = np.array(mean_act[idf]).mean(axis=0)
var_mx[i, :] = np.array(mean_var[idf]).mean(axis=0)
yerr_mx[i, :] = np.array(mean_yerr[idf]).mean(axis=0)
# create dataframe with DF/F activity data
df = pd.DataFrame({'Mouse' : np.tile(mice, len(state_labels)),
'State' : np.repeat(state_labels, len(mice)),
'DFF' : np.reshape(mean_mx,-1,order='F')})
# plot signal in each state
plt.figure()
sns.barplot(x='State', y='DFF', data=df, ci=68, palette={'REM':'cyan','Wake':'darkviolet',
'NREM':'darkgray', 'tNREM':'darkblue'})
sns.pointplot(x='State', y='DFF', hue='Mouse', data=df, ci=None, markers='', color='black')
plt.gca().get_legend().remove()
plt.show()
# stats
res_anova = AnovaRM(data=df, depvar='DFF', subject='Mouse', within=['State']).fit()
mc = MultiComparison(df['DFF'], df['State']).allpairtest(stats.ttest_rel, method='bonf')
print(res_anova)
print('p = ' + str(float(res_anova.anova_table['Pr > F'])))
print(''); print(mc[0])
return df
def laser_brainstate(ppath, recordings, pre, post, tstart=0, tend=-1, ma_thr=20, ma_state=3,
flatten_tnrem=4, single_mode=False, sf=0, cond=0, edge=0, ci='sem',
offset=0, pplot=True, ylim=[]):
"""
Calculate laser-triggered probability of REM, Wake, NREM, and IS
@Params
ppath - base folder
recordings - list of recordings
pre, post - time window (s) before and after laser onset
tstart, tend - time (s) into recording to start and stop collecting data
ma_thr, ma_state - max duration and brain state for microarousals
flatten_tnrem - brain state for transition sleep
single_mode - if True, plot individual mice
sf - smoothing factor for vectors of brain state percentages
cond - if 0, plot all laser trials
if integer, only plot laser trials where mouse was in brain state $cond
during onset of the laser
edge - buffer time (s) added to edges of [-pre,post] window, prevents filtering artifacts
ci - plot data variation ('sd'=standard deviation, 'sem'=standard error,
integer between 0 and 100=confidence interval)
offset - shift (s) of laser time points, as control
pplot - if True, show plots
ylim - set y axis limits of brain state percentage plot
@Returns
BS - 3D data matrix of brain state percentages (mice x time bins x brain state)
t - array of time points, corresponding to columns in $BS
df - dataframe of brain state percentages in time intervals before, during, and
after laser stimulation
"""
# clean data inputs
if type(recordings) != list:
recordings = [recordings]
pre += edge
post += edge
BrainstateDict = {}
mouse_order = []
for rec in recordings:
# get unique mice
idf = re.split('_', rec)[0]
BrainstateDict[idf] = []
if not idf in mouse_order:
mouse_order.append(idf)
nmice = len(BrainstateDict)
for rec in recordings:
idf = re.split('_', rec)[0]
# load sampling rate
sr = sleepy.get_snr(ppath, rec)
nbin = int(np.round(sr) * 2.5)
dt = (1.0 / sr) * nbin
# load and adjust brain state annotation
M = sleepy.load_stateidx(ppath, rec)[0]
M = adjust_brainstate(M, dt, ma_thr=ma_thr, ma_state=ma_state,
flatten_tnrem=flatten_tnrem)
# define start and end points of analysis
istart = int(np.round(tstart / dt))
if tend == -1:
iend = len(M)
else:
iend = int(np.round(tend / dt))
# define start and end points for collecting laser trials
ipre = int(np.round(pre/dt))
ipost = int(np.round(post/dt))
# load and downsample laser vector
lsr = sleepy.load_laser(ppath, rec)
(idxs, idxe) = sleepy.laser_start_end(lsr, offset=offset)
idxs = [int(i/nbin) for i in idxs]
idxe = [int(i/nbin) for i in idxe]
laser_dur = np.mean((np.array(idxe) - np.array(idxs))) * dt
# collect brain states surrounding each laser trial
for (i,j) in zip(idxs, idxe):
if i>=ipre and i+ipost<=len(M)-1 and i>istart and i < iend:
bs = M[i-ipre:i+ipost+1]
BrainstateDict[idf].append(bs)
t = np.linspace(-ipre*dt, ipost*dt, ipre+ipost+1)
izero = np.where(t>0)[0][0] # 1st time bin overlapping with laser
izero -= 1
# create 3D data matrix of mice x time bins x brain states
BS = np.zeros((nmice, len(t), 4))
Trials = []
imouse = 0
for mouse in mouse_order:
if cond==0:
# collect all laser trials
M = np.array(BrainstateDict[mouse])
Trials.append(M)
for state in range(1,5):
C = np.zeros(M.shape)
C[np.where(M==state)] = 1
BS[imouse,:,state-1] = C.mean(axis=0)
if cond>0:
# collect laser trials during brain state $cond
M = BrainstateDict[mouse]
Msel = []
for trial in M:
if trial[izero] == cond:
Msel.append(trial)
M = np.array(Msel)
Trials.append(M)
for state in range(1,5):
C = np.zeros(M.shape)
C[np.where(M==state)] = 1
BS[imouse,:,state-1] = C.mean(axis=0)
imouse += 1
# flatten Trials
Trials = reduce(lambda x,y: np.concatenate((x,y), axis=0), Trials)
# smooth mouse averages
if sf > 0:
for state in range(4):
for i in range(nmice):
BS[i, :, state] = smooth_data(BS[i, :, state], sf)
nmice = imouse
### GRAPHS ###
if pplot:
state_label = {0:'REM', 1:'Wake', 2:'NREM', 3:'IS'}
it = np.where((t >= -pre + edge) & (t <= post - edge))[0]
plt.ion()
if not single_mode:
# plot average % time in each brain state surrounding laser
plt.figure()
ax = plt.axes([0.15, 0.15, 0.6, 0.7])
colors = ['cyan', 'purple', 'gray', 'darkblue']
for state in [3,2,1,0]:
if type(ci) in [int, float]:
# plot confidence interval
BS2 = BS[:,:,state].reshape(-1,order='F') * 100
t2 = np.repeat(t, BS.shape[0])
sns.lineplot(x=t2, y=BS2, color=colors[state], ci=ci, err_kws={'alpha':0.4, 'zorder':3},
linewidth=3, ax=ax)
else:
# plot SD or SEM
tmp = BS[:, :, state].mean(axis=0) *100
plt.plot(t[it], tmp[it], color=colors[state], lw=3, label=state_label[state])
if nmice > 1:
if ci == 'sem':
smp = BS[:,:,state].std(axis=0) / np.sqrt(nmice) * 100
elif ci == 'sd':
smp = BS[:,:,state].std(axis=0) * 100
plt.fill_between(t[it], tmp[it]-smp[it], tmp[it]+smp[it],
color=colors[state], alpha=0.4, zorder=3)
# set axis limits and labels
plt.xlim([-pre+edge, post-edge])
if len(ylim) == 2:
plt.ylim(ylim)
ax.add_patch(patches.Rectangle((0,0), laser_dur, 100, facecolor=[0.6, 0.6, 1],
edgecolor=[0.6, 0.6, 1]))
sleepy.box_off(ax)
plt.xlabel('Time (s)')
plt.ylabel('Brain state (%)')
plt.legend()
plt.draw()
else:
# plot % brain states surrounding laser for each mouse
plt.figure(figsize=(7,7))
clrs = sns.color_palette("husl", nmice)
for state in [3,2,1,0]:
ax = plt.subplot('51' + str(5-state))
for i in range(nmice):
plt.plot(t[it], BS[i,it,state]*100, color=clrs[i], label=mouse_order[i])
# plot laser interval
ax.add_patch(patches.Rectangle((0, 0), laser_dur, 100, facecolor=[0.6, 0.6, 1],
edgecolor=[0.6, 0.6, 1], alpha=0.8))
# set axis limits and labels
plt.xlim((t[it][0], t[it][-1]))
if len(ylim) == 2:
plt.ylim(ylim)
plt.ylabel('% ' + state_label[state])
if state==0:
plt.xlabel('Time (s)')
else:
ax.set_xticklabels([])
if state==3:
ax.legend(mouse_order, bbox_to_anchor=(0., 1.0, 1., .102), loc=3,
mode='expand', ncol=len(mouse_order), frameon=False)
sleepy.box_off(ax)
# plot brain state surrounding each laser trial
plt.figure(figsize=(4,6))
sleepy.set_fontarial()
ax = plt.axes([0.15, 0.1, 0.8, 0.8])
cmap = plt.cm.jet
my_map = cmap.from_list('ha', [[0,1,1],[0.5,0,1],[0.6, 0.6, 0.6],[0.1,0.1,0.5]], 4)
x = list(range(Trials.shape[0]))
im = ax.pcolorfast(t,np.array(x), np.flipud(Trials), cmap=my_map)
im.set_clim([1,4])
# plot laser interval
ax.plot([0,0], [0, len(x)-1], color='white')
ax.plot([laser_dur,laser_dur], [0, len(x)-1], color='white')
# set axis limits and labels
ax.axis('tight')
plt.draw()
plt.xlabel('Time (s)')
plt.ylabel('Trial No.')
sleepy.box_off(ax)
plt.show()
# create dataframe with baseline and laser values for each trial
ilsr = np.where((t>=0) & (t<=laser_dur))[0]
ibase = np.where((t>=-laser_dur) & (t<0))[0]
iafter = np.where((t>=laser_dur) & (t<laser_dur*2))[0]
S = ['REM', 'Wake', 'NREM', 'IS']
mice = mouse_order + mouse_order + mouse_order
lsr = np.concatenate((np.ones((nmice,), dtype='int'), np.zeros((nmice,), dtype='int'),
np.ones((nmice,), dtype='int')*2))
lsr_char = pd.Series(['LSR']*nmice + ['PRE']*nmice + ['POST']*nmice,
dtype='category')
df = pd.DataFrame(columns = ['Mouse'] + S + ['Lsr'])
df['Mouse'] = mice
df['Lsr'] = lsr
# slightly different dataframe organization
df2 = pd.DataFrame(columns = ['Mouse', 'State', 'Perc', 'Lsr'])
for i, state in enumerate(S):
state_perc = np.concatenate((BS[:,ilsr,i].mean(axis=1), BS[:,ibase,i].mean(axis=1),
BS[:,iafter,i].mean(axis=1)))*100
state_label = [state]*len(state_perc)
df[state] = state_perc
df2 = df2.append(pd.DataFrame({'Mouse':mice, 'State':state_label,
'Perc':state_perc, 'Lsr':lsr_char}))
if pplot:
# plot bar grah of % time in each brain state during pre-laser vs. laser interval
plt.figure()
fig, axs = plt.subplots(2,2, constrained_layout=True)
axs = axs.reshape(-1)
if ci == 'sem':
ci = 68
for i in range(len(S)):
sdf = df2.iloc[np.where(df2['State'] == S[i])[0], :]
sns.barplot(x='Lsr', y='Perc', order=['PRE', 'LSR'], data=sdf, ci=ci,
palette={'PRE':'gray', 'LSR':'blue'}, ax=axs[i])
sns.pointplot(x='Lsr', y='Perc', hue='Mouse', order=['PRE', 'LSR'], data=sdf,
color='black', markers='', ci=None, ax=axs[i])
axs[i].get_legend().remove()
axs[i].set_title(S[i]); axs[i].set_ylabel('Amount (%)')
plt.show()
# stats
clabs = ['% time spent in ' + state for state in S]
pwaves.pairT_from_df(df, cond_col='Lsr', cond1=1, cond2=0, test_cols=S,
c1_label='during-laser', c2_label='pre-laser', test_col_labels=clabs)
return BS, t, df
def laser_triggered_eeg(ppath, name, pre, post, fmax, pnorm=1, psmooth=0, vm=[], tstart=0,
tend=-1, cond=0, harmcs=0, iplt_level=1, peeg2=False, prune_trials=False,
mu=[10,100], offset=0, pplot=True):
"""
Calculate average laser-triggered spectrogram for a recording
@Params
ppath - base folder
name - recording folder
pre, post - time window (s) before and after laser onset
fmax - maximum frequency in spectrogram
pnorm - method for spectrogram normalization (0=no normalization
1=normalize SP by recording
2=normalize SP by pre-lsr baseline interval)
psmooth - method for spectrogram smoothing (1 element specifies convolution along X axis,
2 elements define a box filter for smoothing)
vm - controls spectrogram saturation
tstart, tend - time (s) into recording to start and stop collecting data
cond - if 0, plot all laser trials
if integer, only plot laser trials where mouse was in brain state $cond
during onset of the laser
harmcs - if > 0, interpolate harmonics of base frequency $harmcs
iplt_level - if 1, interpolate one SP row above/below harmonic frequencies
if 2, interpolate two SP rows
peeg2 - if True, load prefrontal spectrogram
prune_trials - if True, automatically remove trials with EEG/EMG artifacts
mu - [min,max] frequencies summed to get EMG amplitude
offset - shift (s) of laser time points, as control
pplot - if True, show plot
@Returns
EEGLsr - average EEG spectrogram surrounding laser (freq x time bins)
EMGLsr - average EMG spectrogram
freq[ifreq] - array of frequencies, corresponding to rows in $EEGLsr
t - array of time points, corresponding to columns in $EEGLsr
"""
def _interpolate_harmonics(SP, freq, fmax, harmcs, iplt_level):
"""
Interpolate harmonics of base frequency $harmcs by averaging across 3-5
surrounding frequencies
"""
df = freq[2]-freq[1]
for h in np.arange(harmcs, fmax, harmcs):
i = np.argmin(np.abs(freq - h))
if np.abs(freq[i] - h) < df and h != 60:
if iplt_level == 2:
SP[i,:] = (SP[i-2:i,:] + SP[i+1:i+3,:]).mean(axis=0) * 0.5
else:
SP[i,:] = (SP[i-1,:] + SP[i+1,:]) * 0.5
return SP
# load sampling rate
sr = sleepy.get_snr(ppath, name)
nbin = int(np.round(sr) * 2.5)
# load laser, get start and end idx of each stimulation train
lsr = sleepy.load_laser(ppath, name)
idxs, idxe = sleepy.laser_start_end(lsr, sr, offset=offset)
laser_dur = np.mean((idxe-idxs)/sr)
print('Average laser duration: %f; Number of trials %d' % (laser_dur, len(idxs)))
# downsample laser to SP time
idxs = [int(i/nbin) for i in idxs]
idxe = [int(i/nbin) for i in idxe]
# load EEG and EMG signals
if peeg2:
P = so.loadmat(os.path.join(ppath, name, 'sp2_' + name + '.mat'))
else: