forked from acsutt0n/Drosophila-larvae_old
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maria.py
2313 lines (1939 loc) · 73 KB
/
maria.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
# Stuff for Maria
# Make sure we're in python 2.7
import sys
if sys.version_info.major > 2:
print('Need to run with python 2.7 (for PyMC capability)!!')
else:
import pymc as pm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import subprocess
import collections
def loadCSVfeatures(fname, rmoutliers=False):
"""
Load a csv, keep only the features (and times), dropna, return df.
"""
df = pd.read_csv(fname)
checks = ['maxV', 'maxDerivV', 'maxDerivdV', 'minDerivV',
'minDerivdV', 'preMinV', 'postMinV', 'preMaxCurveV',
'preMaxCurveK', 'postMaxCurveV', 'postMaxCurveK', 'times',
'height', 'repolarizationV', 'intervals', 'frequencies',
'clust_inds', 'mslength']
for col in df.columns:
if col not in checks:
df = df.drop(col, 1)
df = df.dropna()
if rmoutliers: # Treat outliers
for col in checks:
if col != 'times':
df[col] = outlier(df[col])
df = df.dropna()
return df
def containsSpikes(filelist):
"""
Given a txt file which is a list of .csv files, this returns the
files that have valid spikes (>= 1 spike) and the files that do not.
"""
fnames, numlines = [], []
# Load the filenames
with open(filelist, 'r') as fIn:
for line in fIn:
if line:
fnames.append(line.split(None)[0])
# Run through the filenames and get the number of lines
for nam in fnames:
# runstr = 'wc -l %s' %nam
p = subprocess.Popen(['wc', '-l', nam],
stdout=PIPE, stderr=PIPE, stdin=PIPE)
out = p.stdout.read()
try:
numlines.append(int(out.split(None)[0]))
except:
numlines.append(0)
# print(numlines[:10])
# Find the min (as long as it's not zero)
minlines = np.inf
for n in range(len(numlines)):
if numlines[n] < minlines and numlines[n] != 0:
minlines = numlines[n]
# And replace that and min with nan, export the resulting list
newlines = [1 if i > minlines else 0 for i in numlines]
# print(newlines[:10])
return [fnames[u] for u in range(len(newlines)) if newlines[u] > 0]
def showprofile(csvfile, color='rand'):
"""
Show all properties of the data frame. The fields listed below
are ignored.
"""
ignore = ['n1List', 'n2List', 'maxVtms', 'maxVinds', 'maxDerivtms',
'maxDerivinds', 'minDerivtms', 'minDerivinds', 'preMintms', 'preMininds',
'postMintms', 'postMininds', 'preMaxCurvetms', 'preMaxCurveinds',
'postMaxCurvetms', 'postMaxCurveinds', 'times']
f = pd.read_csv(csvfile)
columns = [col for col in f.columns if col not in ignore and len(col.split(None)) == 1]
ncol = int(len(columns)/2.) + 1
if color is 'rand':
color = np.random.random(3)
# Plot these mofos
fig = plt.figure()
plots = [fig.add_subplot(2, ncol, i+1) for i in range(len(columns))]
for col in range(len(columns)):
try:
plots[col].hist(f[columns[col]].dropna(), bins=50, facecolor=color,
edgecolor='none', alpha=0.5)
except:
print(columns[col])
plots[col].set_title(columns[col])
plots[col].set_ylim()
plt.show()
return
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter.
The Savitzky-Golay filter removes high frequency noise from data.
It has the advantage of preserving the original shape and
features of the signal better than other types of filtering
approaches, such as moving averages techniques.
Parameters
----------
y : array_like, shape (N,)
the values of the time history of the signal.
window_size : int
the length of the window. Must be an odd integer number.
order : int
the order of the polynomial used in the filtering.
Must be less then `window_size` - 1.
deriv: int
the order of the derivative to compute (default = 0 means only smoothing)
Returns
-------
ys : ndarray, shape (N)
the smoothed signal (or it's n-th derivative).
Notes
-----
The Savitzky-Golay is a type of low-pass filter, particularly
suited for smoothing noisy data. The main idea behind this
approach is to make for each point a least-square fit with a
polynomial of high order over a odd-sized window centered at
the point.
Examples
--------
t = np.linspace(-4, 4, 500)
y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape)
ysg = savitzky_golay(y, window_size=31, order=4)
import matplotlib.pyplot as plt
plt.plot(t, y, label='Noisy signal')
plt.plot(t, np.exp(-t**2), 'k', lw=1.5, label='Original signal')
plt.plot(t, ysg, 'r', label='Filtered signal')
plt.legend()
plt.show()
References
----------
.. [1] A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of
Data by Simplified Least Squares Procedures. Analytical
Chemistry, 1964, 36 (8), pp 1627-1639.
.. [2] Numerical Recipes 3rd Edition: The Art of Scientific Computing
W.H. Press, S.A. Teukolsky, W.T. Vetterling, B.P. Flannery
Cambridge University Press ISBN-13: 9780521880688
"""
from math import factorial
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError: #, msg:
raise ValueError("window_size and order have to be of type int")
if window_size % 2 != 1 or window_size < 1:
raise TypeError("window_size size must be a positive odd number")
if window_size < order + 2:
raise TypeError("window_size is too small for the polynomials order")
order_range = range(order+1)
half_window = (window_size -1) // 2
# precompute coefficients
b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
# pad the signal at the extremes with
# values taken from the signal itself
firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
y = np.concatenate((firstvals, y, lastvals))
return np.convolve( m[::-1], y, mode='valid')
def getCenters(df, show=False):
"""
Get the bin centers
"""
def whichPeaks(trace):
"""Find the peaks for the dist."""
peaks = []
df = np.diff(trace)
for t in range(len(df)-4):
if df[t] > 0 and df[t+1] > 0:
if df[t+2] < 0 and df[t+3] < 0: # Potential peak
if trace[t+2] > np.mean(trace):
peaks.append([t+2, trace[t+2]])
return peaks
# Get the interval data and bin it
int_data = df.intervals
hist, bin_e = np.histogram(int_data, bins=50)
bin_cents = (bin_e[:-1]+bin_e[1:])*.5
# Smooth the data and identify the probable peaks
histhat = savitzky_golay(hist, 11, 3)
pks = whichPeaks(histhat)
print('Found peaks at :')
cents = [bin_cents[p[0]] for p in pks]
# print(cents)
if show:
plt.bar(bin_cents, hist, color='blue', edgecolor='white',
alpha=0.4)
plt.plot(bin_cents, histhat, color='blue', lw=2)
for c in cents:
plt.axvline(c, 0, max(hist), '--', color='red', lw=1)
plt.show()
return cents
def runMCMC(df, cents, show=False):
"""
Run the MCMC algo for as many centers as needed
"""
if type(cents) is not list:
cents = [cents]
numCents = len(cents)
p = None
# Tau = the precision of the normal distribution (of the above peaks)
taus = 1. / pm.Uniform('stds', 0, 100, size=numCents)**2 # tau = 1/sigma**2
centers = pm.Normal('centers', cents, [0.0025 for i in cents],
size=numCents)
if numCents == 2: # Assignment probability
p = pm.Uniform('p', 0, 1)
assignment = pm.Categorical('asisgnment', [p, 1-p],
size=len(df.intervals))
@pm.deterministic
def center_i(assignment=assignment, centers=centers):
return centers[assignment]
@pm.deterministic
def tau_i(assignment=assignment, taus=taus):
return taus[assignment]
observations = pm.Normal('obs', center_i, tau_i, value=df.intervals,
observed=True)
# Create the model 2 peaks
mcmc = pm.MCMC([p, assignment, observations, taus, centers])
else:
observations = pm.Normal('obs', value=df.intervals, observed=True)
mcmc = pm.MCMC([observations, taus, centers]) # Create model, 1 peak
# Run the model
mcmc.sample(50000)
center_trace = mcmc.trace("centers")[:]
try:
clusts = [center_trace[:,i] for i in range(numCents)]
except:
clusts = [center_trace]
if show:
for i in range(numCents):
plt.hist(center_trace[:,i], bins=50, histtype='stepfilled',
color=['blue', 'red'][i], alpha=0.7)
plt.show()
print('Evolved clusters at:')
print([np.mean(c) for c in clusts])
return clusts
def assignSpikes(clusts, df, show=False, force=True):
"""
Assign each spiking event to either cluster 1 or cluster 2.
"""
if 'clust_inds' in df.columns and force is False:
print('Data frame already contains clust_inds')
return
def assignTms(clusts, tms):
# Assign a delta_tms to cluster1 or cluster2
assns = [abs(np.mean(clusts[c])-tms) for c in range(len(clusts))]
return assns.index(min(assns))
# Assign each spike time to a cluster
clust_tms = [ [] for c in clusts]
for t in range(len(df.times)-1):
t_clust = assignTms(clusts, df.times.values[t+1]-df.times.values[t])
clust_tms[t_clust].append(df.times.values[t])
# Group spikes from same spike type together
type_tms = []
for c in range(len(clust_tms)):
for t in clust_tms[c]:
type_tms.append([t, c]) # [spk tms, clust index]
# Group these together
clust_id = []
for i in range(df.shape[0]):
if df.iloc[i].times in [k[0] for k in type_tms]:
clust_id.append(type_tms[[k[0] for k in type_tms].index(df.iloc[i].times)][1])
else: # Not matching spike found -- happens w/ isolated spikes
clust_id.append(np.nan)
df['clust_inds'] = clust_id
print([clust_id.count(j) for j in list(set(clust_id))], list(set(clust_id)))
if show: # Show the cluter spikes
for c in range(max(clust_id)+1): # Plot cluster spikes individually
temp_spikes = df[df['clust_inds']==c]['times']
plt.plot(temp_spikes, [c+1 for i in temp_spikes], '|',
color=['blue', 'red'][c])
plt.ylim([0,3])
plt.show()
return df
def timeInClusters(df, thresh=2000., show=False):
"""
thresh (ms): how much time should elapse before a bout is
automatically ended.
"""
clust_tms = [ list(df[df.clust_inds==i]['times']) for i in
range(int(max(df.clust_inds))+1) ]
cluster_bouts = [ [] for c in clust_tms ]
for c in range(len(clust_tms)): # Each new cluster
on = False
for t in range(len(clust_tms[c])-1):
if clust_tms[c][t+1] - clust_tms[c][t] > thresh: # 2-s threshold
if on: # If this is a bout, end it
cluster_bouts[c].append(clust_tms[c][t])
on = False
# Else, ignore it (too sparse for tonic)
else: # Close enough to be a continuation or new bout
if on is False: # Not an active bout, so start it
cluster_bouts[c].append(clust_tms[c][t])
on = True
# Else, ignore it (continue the bout)
if on: # If a bout is active at the end, end it with
cluster_bouts[c].append(clust_tms[c][-1])
# Calculate time spent in each cluster (assumes unit is ms)
timeIn = [sum([cluster_bouts[c][2*i+1]-cluster_bouts[c][2*i]
for i in range(len(cluster_bouts[c])/2)])
for c in range(len(cluster_bouts))]
percentIn = [i/max([max(cl) for cl in clust_tms]) for i in timeIn]
for t in timeIn: # Time is dependent on dT
print('Time (percent) spent in cluster %i: %.3f s (%.2f)'
%(timeIn.index(t), t/10000., percentIn[timeIn.index(t)]))
if show: # Show plots
for clust in range(len(cluster_bouts)):
for b in range(len(cluster_bouts[clust])/2):
plt.plot([cluster_bouts[clust][b*2], cluster_bouts[clust][b*2+1]],
[clust+1, clust+1], lw=5, color=['blue', 'red'][clust])
plt.ylim([0,len(cluster_bouts)+1])
plt.show()
print(timeIn, cluster_bouts)
return timeIn, cluster_bouts
#########################################################################
# Feature-specific stuff, outliers
def showVs(df, feat1, feat2):
"""
Show some sample features.
"""
colors = ['blue', 'red', 'green', 'coral']
for u in range(len(cBouts)):
plt.plot(f[f['clust_ind'] == u][feat1],
f[f['clust_ind'] == u][feat2], 'o', color=colors[u],
alpha=0.6, markeredgecolor='none')
plt.xlabel(feat1)
plt.ylabel(feat2)
plt.show()
return
def discrim(a, b):
return (np.mean(a)-np.mean(b))/ \
np.sqrt(0.5*(np.var(a)**2 + np.var(b)**2))
def outlier(arr, as_nan=True, thresh=0.05, show=False, report=False):
"""
Return nan instead (more robust) of nothing (loss of index parity).
Median is more robust than mean.
"""
if len(arr) < 3:
return arr
if show:
plt.subplot(1,2,1) # Plot part 1 first
plt.plot(np.random.random(len(arr)), thing1, 'o', color='blue',
markeredgecolor='none', alpha=0.4)
plt.title('With outliers')
med_res = [(np.median(arr)-i)**2 for i in arr]
med_res_ix = [u for u in med_res] # Create index
arr_copy = [u for u in arr] # The copy will be edited first
stds = []
med_res.sort(reverse=True) # Largest to smallest
# print(med_res[:10])
numPts = max([int(len(arr)*thresh), 2])
# print('Testing largest %i residuals' %numPts)
# Pretend to remove 10% of points
for i in range(numPts): #for i in range(int(len(arr)*.1)): #
stds.append(np.std(arr_copy))
rm_ix = med_res_ix.index(med_res[i])
try:
rm = arr[rm_ix]
except:
print('tried to remove ix %i but arr is len %i'
%(rm_ix, len(arr)))
try:
arr_copy.pop(arr_copy.index(rm))
except:
print('tried to remove %f but not in arr_copy' %rm)
# Find the greatest d(std)
dstd = np.diff(stds)
dstd = [abs(i) for i in dstd]
rm_to = list(dstd).index(max(dstd))+1 # len(diff) = len(arr)-1
#print('Mean d(std): %.3f, removing all above %.3f (%i pts)'
# %(np.mean(dstd), dstd[rm_to-1], rm_to))
for i in range(rm_to):
arr[med_res_ix.index(med_res[i])] = np.nan
if show: # Show
plt.subplot(1,2,2)
plt.plot(np.random.random(len(arr)), arr, 'o',
color='red', markeredgecolor='none', alpha=0.4)
plt.title('Without outliers')
plt.show()
if as_nan:
return arr
return [i for i in arr if not pd.isnull(i)] # Else just eliminate it.
def csvSpikes(fname, show=False):
"""
Run most of the above spike sorting stuff for a csv file.
"""
df = loadCSVfeatures(fname, rmoutliers=True)
cents = getCenters(df, show=show)
clusts = runMCMC(df, cents, show=show)
df = assignSpikes(clusts, df, show=show, force=True)
timeincluster, _ = timeInClusters(df, show=show)
# Give it a new name to differentiate the sorted spikes
newn = fname.split('.')[0]+'_clusters.csv'
writeNewDF(df, fname, newn)
return df
def batchAnalysis(groupfil):
"""
Compile lists of the features listed below grouped by the groupfil.
A line of groupfil is /path/to/file.csv,group name
"""
groups = []
with open(groupfil, 'r') as fIn:
for line in fIn:
groups.append(line.strip().split(','))
checks = ['maxV', 'maxDerivV', 'maxDerivdV', 'minDerivV',
'minDerivdV', 'preMinV', 'postMinV', 'preMaxCurveV',
'preMaxCurveK', 'postMaxCurveV', 'postMaxCurveK',
'height', 'repolarizationV', 'intervals', 'frequencies']
props = {ch: {gr: {} for gr in list(set([g[1] for g in groups]))}
for ch in checks} # A dict of dicts
# props [properties] [group name] [cell name]
cells = [f[0].split('/')[-1].split('_')[0] for f in groups]
# Add a few more keys
props['activity'] = {gr: {} for gr in list(set([g[1] for g in groups]))}
# Assign all the properties to the props dict
for g in groups:
df = pd.read_csv(g[0])
df = df.drop('Unnamed: 33', 1) # Garbage
df = df.drop('freq', 1) # These are downsampled
df = df.dropna() # Dropna
# If there are multiple clusters, add them in order
if max(df.clust_inds) == 1: # Two clusters
numClusts = int(max(df.clust_inds)+1)
for ch in checks:
for clust in range(numClusts):
try:
props[ch][g[1]][cells[groups.index(g)]].append(df[df['clust_inds']==clust][ch].dropna().values)
except:
props[ch][g[1]][cells[groups.index(g)]] = [df[df['clust_inds']==clust][ch].dropna().values]
else: # Just one cluster
for ch in checks:
props[ch][g[1]][cells[groups.index(g)]] = [df[ch].dropna().values]
# Get activity profile
tIn, cBouts = timeInClusters(df)
props['activity'][g[1]][cells[groups.index(g)]] = [tIn, cBouts]
return props
def cellAnalysis(celltypelist, fullcsvpaths):
"""
Organize by cell type first, then treatment 2nd.
celltypelist: 'unknown,15827010.abf,F/I steps (sometimes ramp)'
Generated from
"""
typelist, paths = [], []
with open(celltypelist, 'r') as fIn:
for line in fIn:
typelist.append(line.strip().split(','))
with open(fullcsvpaths, 'r') as fIn:
for line in fIn:
paths.append(line.strip())
# Create the default dicts
types = list(set([p[0] for p in typelist]))
groups = list(set([p[2] for p in typelist]))
checks = ['maxV', 'maxDerivV', 'maxDerivdV', 'minDerivV',
'minDerivdV', 'preMinV', 'postMinV', 'preMaxCurveV',
'preMaxCurveK', 'postMaxCurveV', 'postMaxCurveK',
'height', 'repolarizationV', 'intervals', 'frequencies']
props = {typ: {ch: {gr: {} for gr in groups} for ch in checks} for typ in types}
# Add a few more keys
for typ in types:
props[typ]['activity'] = {gr: {} for gr in groups}
props[typ]['duration'] = {gr: {} for gr in groups}
# Find the matching csv files
paths = [p for p in paths if p.split('_')[-1]=='clusters.csv'] # If it's a clusters file
reffils = [f.split('/')[-1].split('_')[0].split('.')[0] for f in paths] # ref to cluster file
typepaths = []
#print(
for fil in typelist:
t_ = fil[1].split('.')[0]
if t_ in reffils:
typepaths.append(paths[reffils.index(t_)])
else:
typepaths.append('none')
# Populate the dictionary
fail, success = [], []
print('%i (of %i) files seem to be present' %(len(typepaths)-typepaths.count('none'),
len(typepaths)))
for g in range(len(typepaths)): # This retains the order of typelist
try:
df = pd.read_csv(typepaths[g])
df = df.drop('Unnamed: 33', 1) # Garbage
df = df.drop('freq', 1) # These are downsampled
df = df.dropna() # Dropna
# If there are multiple clusters, add them in order
if max(df.clust_inds) == 1: # Two clusters
numClusts = int(max(df.clust_inds)+1)
for ch in checks:
type_ = typelist[g][0]
group_ = typelist[g][2]
cell_ = typelist[g][1].split('.')[0]
for clust in range(numClusts):
props[type_][ch][group_][cell_].append(df[df['clust_inds']==clust][ch].dropna().values)
else: # Just one cluster
for ch in checks:
props[type_][ch][group_][cell_] = [df[ch].dropna().values]
# Get activity profile
tIn, cBouts = timeInClusters(df)
props[type_]['activity'][group_][cell_] = [tIn, cBouts]
props[type_]['duration'][group_][cell_] = df.times.iloc[-1]
success.append(typelist[g])
except:
fail.append(typelist[g])
#print(failed)
return props, success, fail
def activityProps(pdict):
"""
Analysis of activity (burst, tonic, etc). Props comes from
"""
# For baseline, establish the precentage of time each cell of each type
act = {gr: {'burst': [], 'tonic': [], 'silent': [],
'burstLoc': [], 'tonicLoc': []} for gr in pdict.keys()}
# Populate the dict
for group in pdict.keys():
for cell in pdict[group]['intervals']['GapFree I=0 / Baseline recording'].keys():
inters, timeSpent = [], []
for clust in range(len(pdict[group]['intervals']['GapFree I=0 / Baseline recording'][cell])):
inters.append(np.mean(pdict[group]['intervals']['GapFree I=0 / Baseline recording'][cell][clust]))
timeSpent.append(np.mean(pdict[group]['activity']['GapFree I=0 / Baseline recording'][cell][0][clust]))
# Add these percentages
maxT = pdict[group]['duration']['GapFree I=0 / Baseline recording'][cell]
if len(inters) > 1:
time_sort =[x for (y,x) in sorted(zip(inters, timeSpent))]
inter_sort = [i for i in sorted(inters)]
act[group]['burst'].append(time_sort[0]/maxT)
act[group]['tonic'].append(time_sort[1]/maxT)
act[group]['silent'].append(1-(time_sort[0]+time_sort[1])/maxT)
act[group]['burstLoc'].append(inter_sort[0])
act[group]['tonicLoc'].append(inter_sort[1])
else:
act[group]['tonic'].append(timeSpent[0]/maxT)
act[group]['tonicLoc'].append(inters[0])
act[group]['silent'].append(1-(timeSpent[0]/maxT))
# Each cell done
# Group done
# All groups done
return act
# Make a list of props dicts for each treatment combination ??
def actSnapshot(df, where=-1, T=20000, var='intervals'):
"""
Get a snapshot of activity for the first (where=0) or last (-1) t-milliseconds.
"""
if type(df) is str:
df = pd.read_csv(df)
if var in ['counts', 'freq', 'count']:
var_ = 'intervals'
else:
var_ = var
keep, su_, g = [], 0., 0
inters = df[var_].dropna().values
go = list(range(len(inters)))
if where == -1: # Reverse order, otherwise leave it
go = go[::-1]
while su_ < T and g < len(go):
t_ = df[var_].values[go[g]]
if not pd.isnull(t_):
keep.append(t_)
su_ = su_ + t_
g += 1
if len(keep) < 1:
return None
if var == 'intervals':
return 1./(np.mean(keep)*1000)
elif var in ['count', 'counts']:
return len(keep)
elif var == 'freq':
return len(keep)/(float(T)/T)
return np.mean(keep)
def byTreatment(df, keep=['GapFree', 'Pilo', 'CCh', 'ModA', 'Washout', 'MCA', 'Nico'],
goi='OK371-GFP-Gal4', var='intervals'):
"""
Show treatments by cell type if they contain any of 'keep' list.
In 'keep' list, *baseline must be first!*.
Show %-change from baseline.
"""
linked = findExtInDF(df, ext='abf', labrow=1, refCol=0, outfile=None)
# Make the cell dict first -- easier this way
props, glist, clist, newl = {}, [], [], []
for l in linked: # linked: ['2015_05_11_c2', '15511005.abf', '3.3mM calcium ModA'],
for k in keep:
if k in l[2] and l not in newl:
if l[2].count('.') > 1: # Multiple files, probably
l[2] = '.'.join
newl.append(l)
print('Keeping %i (of %i) files' %(len(newl), len(linked)))
# Organize by cell & treatment
cell_tx = {}
for l in newl:
#print(l[2])
if l[0] not in cell_tx.keys(): # Add new cell
cell_tx[l[0]] = {'type': df.ix[ list(df.ix[:,0].values).index(l[0]), 5 ],
'genotype': df.ix[ list(df.ix[:,0].values).index(l[0]), 4 ],
}
t_path = getFullPath(l[1].split('.')[0]+'_props.csv')[0]
df_t = None
try:
df_t = pd.read_csv(t_path)
except:
print('could not load %s' %t_path)
if df_t is not None:
if keep[0] in l[2]: # This is baseline
cell_tx[l[0]]['baseline'] = actSnapshot(df_t, where=0, var=var) # From the beginning
# Check the other treatments
for k in keep:
if k in l[2]:
snap = actSnapshot(df_t, where=-1, var=var) # From the end
if snap is not None:
cell_tx[l[0]][l[2]] = snap
else:
print('Could not add %s (%s)' %(l[2], t_path))
for l in newl:
if l[2] not in props.keys(): # Check each treatment
props[l[2]] = {}
gen_ = df.ix[ list(df.ix[:,0].values).index(l[0]), 4 ] # Get the genotype
if gen_ not in props[l[2]].keys(): # Check each genotype
props[l[2]][gen_] = {}
glist.append(gen_)
cell_ = df.ix[ list(df.ix[:,0].values).index(l[0]), 5 ] # Get the celltype
if cell_ not in props[l[2]][gen_].keys():
props[l[2]][gen_][cell_] = []
clist.append(cell_)
# return props
clist, glist = list(set(clist)), list(set(glist))
print(props.keys(), glist, clist)
# Round out the dictionaries
for p in props.keys():
for g in glist:
if g not in props[p].keys():
props[p][g] = {}
for c in clist:
if c not in props[p][g].keys():
props[p][g][c] = []
# Populate the props dictionary with the property, here activity
for ck in cell_tx.keys():
cel_ = cell_tx[ck]
for tx in cel_.keys():
if tx not in ['type', 'genotype', 'baseline']:
if var == 'count':
try:
props[tx] [cel_['genotype']] [cel_['type']].append(float(cel_[tx])-float(cel_['baseline']))
except:
props[tx] [cel_['genotype']] [cel_['type']].append(float(cel_[tx]))
else:
try:
props[tx] [cel_['genotype']] [cel_['type']].append(float(cel_[tx])/float(cel_['baseline']))
except:
props[tx] [cel_['genotype']] [cel_['type']].append(1.)
for i in list(props.keys()):
if goi is not None:
genoByCell({i: {goi: props[i][goi]}})
return props
def burstActivity(csvfile, tryburst=True, show=True):
"""
Show the bursting activity, or whatever.
"""
# Clean the filename (if as abf)
if '.abf' in csvfile:
try: # Try for clusters first
df = loadCSVfeatures(csvfile.split('.')[0]+'_props_clusters.csv')
tryburst = False
except:
df = loadCSVfeatures(csvfile.split('.')[0]+'_props.csv')
else:
try: # Assume it's already a csv
df = loadCSVfeatures(csvfile)
if 'clusters' in csvfile:
tryburst = False
except: # It must be a df
df = csvfile
if 'clust_inds' in df.columns:
tryburst = False
# Get the bursts (if needed)
if tryburst:
print('Trying to find the bursts!')
cents = getCenters(df, show=False)
clusts = runMCMC(df, cents, show=False)
df = assignSpikes(clusts, df, show=False, force=True)
timeIn, cluster_bouts = timeInClusters(df, thresh=2000., show=False)
# Show the bursting activity
if 'clust_inds' not in df.columns:
print('Could not segregate clusters!')
return df
if show:
# First is the simple color-by-burst plot
collist = ['blue', 'red', 'forestgreen', 'goldenrod', 'purple', 'yellowgreen',
'skyblue', 'tomato', 'darkgray']
for i in range(df.shape[0]):
plt.plot([df.ix[i].times, df.ix[i].times],
[df.ix[i].clust_inds-1, df.ix[i].clust_inds],
color=collist[df.ix[i].clust_inds], linewidth=1.)
patches = []
for u in range(int(max(df.clust_inds))):
patches.append(mpatches.Patch(color=collist[u],
label='Cluster %i' %u))
plt.legend(handles=patches)
# Next is the burst activity patterns
plt.figure()
checks = ['maxDerivV', 'maxDerivdV',
'minDerivdV', 'preMaxCurveK', 'postMaxCurveK',
'height', 'repolarizationV', 'intervals', 'frequencies']
# for ch in range(len(checks)):
# plt.subplot(2,int(len(checks)/2 +1), checks.index(ch)+1)
# for clust in range(max(df.clust_inds)+1): # For each cluster
# plotthis = df[df.clust_inds==clust][ch]
# plt.plot([i+clust for i in np.random.random(len(
return
def assignToBurst(abfroot, burst, show=True, rmoutliers=True):
"""
Show bursting activity by cell. abfroot should be without .abf ext.
Burst should be either a df (bursttms) or a path to that df.
"""
# Find out type of input
if type(abfroot) is str:
if '.' in abfroot:
abfroot = abfroot.split('.')[0]
if '/' not in abfroot:
try:
dfroot = getFullPath(abfroot+'_props_clusters.csv')[0]
df = pd.read_csv(dfroot)
except:
dfroot = getFullPath(abfroot+'_props.csv')[0]
df = pd.read_csv(dfroot)
else:
dfroot = abfroot
# %print('Trying to load %s ....' %dfroot)
df = pd.read_csv(dfroot)
if type(burst) is str:
if '/' not in burst:
try:
burst = getFullPath(burst, '/home/alex/data/misc')[0]
except:
burst = getFullPath(burst)[0]
burst = pd.read_csv(burst)
# Now have both as data frames
bs_cells = [i.split('s')[0].split('_')[1] for i in burst.columns] # Make sure it's in burst df
if abfroot not in bs_cells:
df['in_burst'] = [False for f in range(df.shape[0])]
return df # No bursts, just return the df
cell_id = 'id_'+ abfroot
start = burst[cell_id+'start'].dropna().values
stop = burst[cell_id+'stop'].dropna().values
in_burst = [] # Check if each spike belongs to a burst
for i in range(df.shape[0]):
t_ = df.ix[i]['times']/1000. # For each spike time
ibs = False
for bur in range(len(start)): # Check if it fits inside a burst!
if start[bur] < t_ < stop[bur]:
ibs = True
in_burst.append(int(ibs))
df['in_burst'] = in_burst
# Now do all the plotting!
if show:
# First is the simple color-by-burst plot
collist = ['blue', 'red', 'forestgreen', 'goldenrod', 'purple', 'yellowgreen',
'skyblue', 'tomato', 'darkgray']
for i in range(df.shape[0]):
plt.plot([df.ix[i].times, df.ix[i].times],
[df.ix[i].in_burst-1, df.ix[i].in_burst],
color=collist[int(df.ix[i].in_burst)], linewidth=1.)
patches = []
labs = ['Tonic', 'Burst']
for u in range(int(max(df.in_burst)+1)):
patches.append(mpatches.Patch(color=collist[u],
label=labs[u]))
plt.legend(handles=patches)
plt.ylim([-1.5, max(df.in_burst)+.5])
# Next is the burst activity patterns
plt.figure()
checks = ['maxDerivV', 'maxDerivdV',
'minDerivdV', 'preMaxCurveK', 'postMaxCurveK',
'height', 'repolarizationV', 'intervals', 'frequencies']
for ch in range(len(checks)):
plt.subplot(2,int(len(checks)/2 +1), ch+1)
labels = ['Tonic', 'Burst']
for clust in range(max(df.in_burst)+1): # For each cluster
plotthis = df[df.in_burst==clust][checks[ch]].values
if rmoutliers:
plotthis = outlier(plotthis, as_nan=False)
plotthis = outlier(plotthis, as_nan=False)
plt.plot([i*0.2+clust for i in np.random.random(len(plotthis))],
plotthis, 'o', color=collist[clust], markeredgecolor='none',
alpha=0.3)
plt.plot([clust, clust+.2], [np.mean(plotthis), np.mean(plotthis)],
color='black', lw=2)
plt.plot([clust+.1, clust+.1],
[np.percentile(plotthis, 25), np.percentile(plotthis, 75)],
color='black', lw=2)
labels = [labels[i] for i in range(max(df.in_burst)+1)]
poses = [i+.1 for i in range(len(labels))]
plt.xticks(poses, labels, rotation=45)
plt.xlim([-.1, max(df.in_burst)+.3])
plt.title(checks[ch])
plt.show()
return df
#
def burstDFhelper(tdf, temp, bs, cell_id):
"""
Populate the temp dictionary.
"""
def ibi_cv(bstart, bstop):
"""
Calculate inter-burst interval coefficient of variation.
"""
ibis = []
for b in range(len(bstart)-1):
if bstart[b+1] > bstop[b]: # ortho, correct
ibis.append(bstart[b+1] - bstop[b])
else:
print(' In %s, %.2f starts before burst ends at %.2f'
%(cell_id, bstart[b+1], bstop[b]))
return np.mean(ibis), np.std(ibis)/np.mean(ibis)
def spikesperburst(tdf, bstart, bstop):
"""
Count spikes per burst and spikes/burst CV.
"""
tms = list(tdf.times.dropna().values)
bursts = [[tms[u] for u in range(len(tms)) if bstart[k]<(tms[u]/1000.)<bstop[k] ]
for k in range(len(bstart))]
bursts = [len(i) for i in bursts]
return np.mean(bursts), np.std(bursts)/np.mean(bursts)
def burst_time(temp, bstart, bstop):
"""
Make sure bstop[i] is always after bstart[i]; also burst length
"""
to_sum = []
for b in range(len(bstart)):
if bstop[b]-bstart[b] >= 0:
to_sum.append(bstop[b]-bstart[b])
elif bstop[b]-bstart[b] < 0 and b == len(bstop)+1: # Make it go to end
to_sum.append(temp['length']/1000.-bstart[b])
else:
pass
return np.mean(to_sum), np.std(to_sum)/np.mean(to_sum), sum(to_sum)/(temp['length']/1000.)
bs_cells = [i.split('s')[0].split('_')[1] for i in bs.columns]
#print(cell_id, bs_cells)
if cell_id in bs_cells:
bstart = bs['id_'+cell_id+'start'].dropna().values
bstop = bs['id_'+cell_id+'stop'].dropna().values
temp['numbursts'] = len(bstart) # Number of bursts
print(' --> Found %i bursts ' %temp['numbursts'])
temp['burst_length'], temp['burst_length_cv'], \
temp['burst'] = burst_time(temp, bstart, bstop)
temp['spikespburst'], temp['spikespburst_cv'] = \
spikesperburst(tdf, bstart, bstop)
if temp['burst'] < 0:
print(' Warning! Found %.4f burst time for %s!'
%(temp['burst'], temp['file']))
temp['burst'] = 0.
else:
temp['burst'] = temp['burst']/(temp['length']/1000.) # Burst time in s!!!
temp['ibi_length'], temp['ibi_cv'] = ibi_cv(bstart, bstop)
else: # Else, it doesn't burst
temp['burst'], temp['burst_length_cv'], temp['ibi_cv'] = 0., np.nan, np.nan
temp['tonic'] = sum(tdf[tdf.in_burst==0]['intervals'].dropna().values)/temp['length']
temp['silent'] = 1. - (temp['burst']+temp['tonic'])
return temp