forked from OpenSourceBrain/GranCellSolinasEtAl10
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStimhelp.py
executable file
·3504 lines (2521 loc) · 119 KB
/
Stimhelp.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
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 8 19:12:05 2011
@author: chris
"""
from __future__ import division
#import sys
#sys.path.insert(0, "/home/chris/lib/python") # for new matplotlib!!!
from pylab import *
from numpy import round, random, any
from units import *
import time
from NeuroTools import stgen
import h5py
import os
import shutil
def noclip(ax):
"Turn off all clipping in axes ax; call immediately before drawing"
ax.set_clip_on(False)
artists = []
artists.extend(ax.collections)
artists.extend(ax.patches)
artists.extend(ax.lines)
artists.extend(ax.texts)
artists.extend(ax.artists)
for a in artists:
a.set_clip_on(False)
def make_colormap(seq):
import matplotlib.colors as mcolors
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
def create_colnoise(t, sexp, cutf = None, seed = None, onf = None):
'''x = create_colnoise(t, sexp, cutf)
Make coloured noise signal
t = vector of times
sexp = spectral exponent - Power ~ 1 / f^sexp
cutf = frequency cutoff - Power flat (white) for f <~ cutf
cutf == None OR sexp == 0: white noise
output: mean = 0, std of signal = 1/2 => max 95% is 1
'''
from scipy import signal
nt = len(t)
dt = (t[-1] - t[0]) / (nt - 1)
random.seed(seed)
#if sexp == 0: # no smooth cutoff
# N = 10001 # number of filter taps
# xp = int((N-1)/2)
# x = random.standard_normal(size = len(t)+xp)
#else:
# x = random.standard_normal(size = shape(t))
x = random.standard_normal(size = shape(t))/2
#print std(x)
if cutf == None:
pass
else:
if sexp == 0: # no cutoff
pass
# OLD: sharp cutoff
#x = fft(x)
#f = fftfreq(nt, dt)
#x[nonzero(f == 0)] = 0 # remove zero frequency contribution
##i = nonzero(f != 0) # find indices i of non-zero frequencies
##x[i]=x[i] / (cutf ** 2 + f[i] ** 2) ** (sexp / 4) # using i allows cutf = 0
#x = real(ifft(x)) # ignore imaginary part (numerical error)
#x = x / std(x) # std of signal = 1/2, mean = 0
#fs = 1/dt # sampling rate
#fc = cutf/(0.5*fs) # cutoff frequency
#a = 1 # filter denominator
#b = signal.firwin(N, cutoff=fc, window='hamming') #'blackmanharris') # filter numerator
#x = signal.lfilter(b, a, x) # filtered output
#x = x[xp:]
##w,h = signal.freqz(b,a)
##h_dB = 20 * log10 (abs(h))
##figure(77)
##semilogx(w/max(w),h_dB)
##show()
elif sexp == -1: # sharp cutoff
x, freq, freq_wp, freq_used = create_multisines(t, freq_used=None, cutf=cutf, onf=onf)
#print std(x)
x = x / std(x) / 2 # std of signal = 1, mean = 0
else: # smooth cutoff
x = fft(x)
f = fftfreq(nt, dt)
x[nonzero(f == 0)] = 0 # remove zero frequency contribution
i = nonzero(f != 0) # find indices i of non-zero frequencies
x[i]=x[i] / (cutf ** 2 + f[i] ** 2) ** (sexp / 4) # using i allows cutf = 0
x = real(ifft(x)) # ignore imaginary part (numerical error)
x = x / std(x) / 2 # std of signal = 1/2, mean = 0
return x
def create_multisines(t, freq_used=array([1]), cutf = None, onf = None):
"""
This function will produce a colored noise signal using the time points
as defined in array t. The signal will be constructed using sinosoids with
frequencies as defined in the array freq_used and randomized phases.
The output consists of signal x
"""
tstop = t[-1]
df = 1 / tstop # frequency stepsize
dt = t[2] - t[1]
data_points = len(t) # number of time or frequency steps
vector_freq = zeros(data_points)
vector_phase = zeros(data_points)
if cutf != None:
f = arange(0,data_points)*df
if onf != None:
freq_used = f[nonzero((f <= cutf) & (f >= onf))]
#print freq_used
else:
freq_used = f[nonzero((f <= cutf) & (f > 0))]
index_f_used = round(freq_used / df).astype('int') # get indices of used frequencies in frequency vector
index_fneg_used = (data_points - index_f_used).astype('int') # indices of negative frequencies
index_fall_used = concatenate((index_f_used, index_fneg_used)) # indices of pos+neg frequencies
vector_freq[index_fall_used] = data_points / 2 # each frequency used ???
phase = 2*pi*(random.rand(len(freq_used),1)-0.5) # pick phases randomly shifted by +-pi (sould there by another 2* to shift +-2pi???)
vector_phase[index_f_used] = phase # assign positive phases to full vector
vector_phase[index_fneg_used] = -phase # assign negative phases to full vector
freqtemp = vector_freq * exp(1j * vector_phase) # generate frequency domain response
x = real(ifft(freqtemp)) # convert into time domain
#print "- Number of msine frequencies: " + str(2 * std(x) ** 2)
noise_data = x/max(abs(x)) # scale so that signal amplitude is 1
freq = fftfreq(data_points, dt)[ 0:round(data_points / 2) ] # positive frequency vector
noise_power = abs(fft(noise_data))[ 0:round(data_points / 2) ] # compute noise power
freq_wp = find(noise_power > 2 * std(noise_power)) # threshold to discriminate the indexes of peak frequencies
freq_used = freq[freq_wp] # vector of used frequencies [Hz]
return noise_data, freq, freq_wp, freq_used
def create_singlesine(fu = 5, amp = 0.5, ihold = 1, dt = 0.025*ms, periods = 10, minlength = 1*s, t_prestim = 2*s, l_zeros = 2):
"""
This function will produce a single sine signal of frequency fu with holding current ihold
Signal has at least the length periods*T (s) or minlength (s).
Use stimulate with pre stimulus of length t_prestim (s)
"""
fs = 1 / dt # sampling rate
tnext = 0
# delay for no noise input
start_zeros = zeros(l_zeros * fs)
t_zeros = tnext + arange(0, l_zeros, dt)
tnext = t_zeros[-1] + dt
l_pre_signal = ceil(t_prestim / (1. / fu)) * 1. / fu # length of pre stimulus should to be at least t_prestim seconds but with length of full periods
t_pre_signal = arange(0, l_pre_signal, dt) # create pre time vector
pre_signal = amp * sin(2 * pi * t_pre_signal * fu) # create pre signal vector
t_pre_signal = t_pre_signal + tnext
tnext = t_pre_signal[-1] + dt
l_t = max(minlength, periods * 1 / fu) # length of input_signal: stimulate for at least periods*T or minlength
t_input_signal = arange(0, l_t, dt) # create stimulus time vector
#window = sin(2 * pi * t_input_signal * 1/l_t/2) # not really good if nonlinear membrane function!!!!
input_signal = amp * sin(2 * pi * t_input_signal * fu)
t_input_signal = t_input_signal + tnext
i_start = len(start_zeros) + len(pre_signal)
i_stop = len(start_zeros) + len(pre_signal) + len(input_signal)
tnext = t_input_signal[-1] + dt
l_post_signal = 1 # length of post stimulus should only be 1 s, equivalent to 1 Hz lower bound for spike cutoff
t_post_signal = arange(0, l_post_signal, dt) # create pre time vector
post_signal = amp * sin(2 * pi * t_post_signal * fu) # create pre signal vector
t_post_signal = t_post_signal + tnext
all_data = concatenate((start_zeros, pre_signal, input_signal, post_signal)) # combine all
t = concatenate((t_zeros, t_pre_signal, t_input_signal, t_post_signal)) # combine all
t1 = arange(0, size(all_data) * dt, dt) # time vector of stimulus [s]
i_startstop = array([i_start, i_stop])
t_startstop = array([t[i_start], t[i_stop]])
iholdvec = concatenate((zeros(1 * fs), ones(len(all_data) - 1 * fs) * ihold)) # create holding current vector
#iholdvec = concatenate((zeros(1 * fs), ones(len(all_data) - 2 * fs) * ihold, zeros(1 * fs))) # create holding current vector
stimulus = all_data + iholdvec # create full stimulus vector
return t, stimulus, i_startstop, t_startstop
def create_ZAP(dt=0.025*ms, ihold=1*nA, amp=0.1*nA, fmax=100, t_stim=30*s, ex=2):
t = arange(0,t_stim,dt)
zap = amp*sin(2*pi*((fmax*t**ex)/((ex+1)*t_stim**ex))*t) + ihold
f=(fmax*t**ex)/(t_stim**ex)
return t, zap, f
def aiftransfer(freq = arange(0,1000,1), tau = 20*ms, f0 = 100*Hz, i0 = 0*nA, rm = 10*MOhm, Vreset = 0, Vth = 1, Vrest = 0, delta_t = 0):
"""
Create theoretical transfer function of a simplified integrate and fire neuron
from Knight 1972
"""
gamma = 1/tau
# theoretical transfer function H(2*pi*i*freq)
z = (gamma + 2 * pi * freq * 1j) / f0
if i0 == 0:
s0 = gamma / (1 - exp(-gamma / f0)) # theoretical current for f0
H = f0/s0 * exp(gamma / f0) * (1 - exp(-z)) / z * exp(- 2*pi*delta_t*1j)
else:
s0 = (i0*rm + (Vrest - Vreset)) / (Vth - Vreset)
H = rm/(Vth - Vreset) * f0/s0 * exp(gamma / f0) * (1 - exp(-z)) / z * exp(- 2*pi*delta_t*1j)
# useful to return TF for zero gamma
z = (2 * pi * freq * 1j) / f0
H0 = f0/s0 * (1 - exp(-z)) / z
return H, H0
def syn_kernel(t, tau1 = 5, tau2 = 10):
if tau1 == 0:
G = exp(-t/tau2)
else:
if (tau1/tau2 > .9999):
tau1 = .9999*tau2
tp = (tau1*tau2)/(tau2 - tau1) * log(tau2/tau1)
factor = -exp(-tp/tau1) + exp(-tp/tau2)
factor = 1/factor
G = factor * (exp(-t/tau2) - exp(-t/tau1))
return G
#def pop_giftransfer(freq = arange(0,1000,1), C = 0.5*1e-9, g = 0.025*1e-6, gr = 0.025*1e-6, tau_r = 100*1e-3, Vreset = -56*1e-3, Vth = -50*1e-3):
# """
# Create theoretical population transfer function of a general integrate and fire neuron with resonance
# from Magnus et al. 2003
# """
#
# omega = 2*pi*freq
#
# gamma = gr/g
# tau_m = C/g
#
# def Y(omega):
# (1 - g * tau_m * (Vth - Vreset) * A_LIF(omega)) / (1 + 1j * omega * tau_m)
#
# def A_LIF(omega):
#
# def A(omega):
# return (1 - gamma * Y(omega) / (1 + gamma * Y(omega) + 1j * omega * tau_r)) * A_LIF(omega)
#
# return A(omega)
def fit_aiftransfer(freq, H0, f0, i0):
"""
Fit theoretical transfer function of a simplified integrate and fire neuron to actual transfer function
freq = used frequencies
H = transfer function
"""
from scipy.optimize import fmin, leastsq
def peval(freq, f0, i0, p):
H, _ = aiftransfer(freq, tau = p[0], f0 = f0, i0 = i0, delta_t = p[2])
return p[1] * H
def residuals(p, H0, freq, f0, i0):
H = peval(freq, f0, i0, p)
#err = sum( abs(abs(H0) - abs(H)) + abs(unwrap(angle(H0)) - unwrap(angle(H0))) * 180/pi )**2 #
err = sum( ( concatenate((real(H0), imag(H0))) - concatenate((real(H), imag(H))) )**2 )
#err = sum( (abs(H0) - abs(H))**2 )
return err
p0 = array([20*ms, 1, 0]) # tau, rm
plsq = fmin(residuals, p0, args=(H0, freq, f0, i0))
#print plsq
tau = plsq[0] #[0] #plsq[0][0]
scale = plsq[1] #[1]
delta_t = plsq[2]
H, _ = aiftransfer(freq, tau = tau, f0 = f0, i0 = i0, delta_t = delta_t)
H = scale*H
return tau, scale, H, delta_t
def fit_sinusoid(f, t0, u0, t = None):
"""
Fit sinusoid of known frequency to signal
f = known frequency
t0 = timebase
u0 = signal
t = optional interpolation timebase
"""
e = ones(size(t0))
c = sin(2 * pi * f * t0)
s = cos(2 * pi * f * t0)
a = array((e, c, s)).T
b = linalg.lstsq(a, u0.T)[0]
umean = b[0]
uamp = sqrt(b[1] ** 2 + b[2] ** 2)
uphase = math.atan2(b[2], b[1]) # convention: cos(2*pi*f*t+uphase)
if t is not None:
u = umean + uamp * sin(2 * pi * f * t + uphase)
else:
u = umean + uamp * sin(2 * pi * f * t0 + uphase)
t = t0
# from scipy import io
#if f == 1:
# figure(9)
# plot(t0, u0, 'b.', t, u, 'r')
# #ylim(25, 40)
# from datetime import datetime
# idate = datetime.now().strftime('%Y%m%d_%H%M%S') # %S
# savefig("./figs/" + idate + "-sin_" + str(f) + ".png", dpi = 300) # save it
# txt=array((t0,u0,u)).T
# savetxt("./figs/" + idate + "-sin_" + str(f) + ".txt", txt)
# show()
# clf()
return umean, uamp, uphase, u
def fit_sinusoid2(f, t0, u0, t = None):
"""
Fit sinusoid of known frequency to signal
f = known frequency
t0 = timebase
u0 = signal
t = optional interpolation timebase
"""
from scipy.optimize import leastsq
def peval(t, f, p):
return p[0] + p[1] * sin(2 * pi * f * t + p[2])
def residuals(p, u, t, f):
err = u-peval(t, f, p)
return err
p0 = array([0, 0, 0])
plsq = leastsq(residuals, p0, args=(u0, t0, f))
umean = plsq[0][0]
uamp = plsq[0][1]
uphase = plsq[0][2]
if t is not None:
u = umean + uamp * sin(2 * pi * f * t + uphase)
else:
u = umean + uamp * sin(2 * pi * f * t0 + uphase)
t = t0
return umean, uamp, uphase, u
def fit_sinusoid_fft(f, t0, u0, t = None, i = None):
"""
Fit sinusoid of known frequency to signal using fft
f = known frequency
t0 = timebase
u0 = signal
t = optional interpolation timebase
i = optional stimulus current (will return magnitude)
"""
e = ones(size(t0))
c = sin(2 * pi * f * t0)
s = cos(2 * pi * f * t0)
a = array((e, c, s)).T
b = linalg.lstsq(a, u0.T)[0]
umean = b[0]
umean = mean(u0)
if i is not None:
b = linalg.lstsq(a, i.T)[0]
imean = b[0]
expb = exp(-2 * pi * 1j * f * t0) # exponetial basis for Fourier series
G = sum((u0 - umean) * expb) / sum((i - imean) * expb)
uamp = abs(G)
uphase = angle(G)
u = []
else:
expb = exp(-2 * pi * 1j * f * t0 / len(t0)) # exponetial basis for Fourier series
G = sum((u0 - umean) * expb)
uamp = abs(G)
uphase = angle(G)-pi/2
if t is not None:
u = umean + uamp * sin(2 * pi * f * t + uphase)
else:
u = umean + uamp * sin(2 * pi * f * t0 + uphase)
t = t0
return umean, uamp, uphase, u
def fit_exp(t0, u0, p0 = array([0, 0]), delay = 0):
"""
Fit exponential to signal
t0 = timebase
u0 = signal
"""
from scipy.optimize import leastsq
def peval(t, p, delay = 0):
dt = t[1]-t[0]
u = p[0] * (1 - exp(-(t-delay)/p[1]))
u[0:delay/dt]=0
return u
def residuals(p, u, t, delay = 0):
err = u-peval(t, p, delay)
return err
plsq = leastsq(residuals, p0, args=(u0, t0, delay))
udecay = plsq[0][0]
utau = plsq[0][1]
u = peval(t0, array([udecay,utau]), delay)
return udecay, utau, u
def fit_dualexp(t0, u0, p0 = array([0, 0, 0]), delay = 0):
"""
Fit exponential to signal
t0 = timebase
u0 = signal
"""
from scipy.optimize import leastsq
def peval(t, p, delay = 0):
dt = t[1]-t[0]
tp = (p[1]*p[2])/(p[2] - p[1]) * log(p[2]/p[1])
factor = 1 / (-exp(-tp/p[1]) + exp(-tp/p[2]))
u = factor * p[0] * ( -exp(-(t-delay)/p[1]) + exp(-(t-delay)/p[2]) )
u[0:delay/dt]=0
return u
def residuals(p, u, t, delay = 0):
err = u-peval(t, p, delay)
return err
plsq = leastsq(residuals, p0, args=(u0, t0, delay))
umax = plsq[0][0]
utau1 = plsq[0][1]
utau2 = plsq[0][2]
u = peval(t0, array([umax,utau1,utau2]), delay)
return umax, utau1, utau2, u
def fit_twodualexp(t0, u0, p0 = array([0, 0, 0, 0, 0, 0]), delay = 0):
"""
Fit exponential to signal
t0 = timebase
u0 = signal
"""
from scipy.optimize import leastsq
def peval(t, p, delay = 0):
dt = t[1]-t[0]
u = p[0] * ( -exp(-(t-delay)/p[1]) + exp(-(t-delay)/p[2]) )
v = p[3] * ( -exp(-(t-delay)/p[4]) + exp(-(t-delay)/p[5]) )
tp = (p[1]*p[2])/(p[2] - p[1]) * log(p[2]/p[1])
factor = 1 / (-exp(-tp/p[1]) + exp(-tp/p[2]))
u = factor * p[0] * ( -exp(-(t-delay)/p[1]) + exp(-(t-delay)/p[2]) )
tp = (p[4]*p[5])/(p[5] - p[4]) * log(p[5]/p[4])
factor = 1 / (-exp(-tp/p[4]) + exp(-tp/p[5]))
v = p[3] * ( -exp(-(t-delay)/p[4]) + exp(-(t-delay)/p[5]) )
u = u+v
u[0:delay/dt]=0
return u
def residuals(p, u, t, delay = 0):
err = u-peval(t, p, delay)
return err
plsq = leastsq(residuals, p0, args=(u0, t0, delay))
umax = plsq[0][0]
utau1 = plsq[0][1]
utau2 = plsq[0][2]
vmax = plsq[0][3]
vtau1 = plsq[0][4]
vtau2 = plsq[0][5]
u = peval(t0, array([umax,utau1,utau2,vmax,vtau1,vtau2]), delay)
return umax, utau1, utau2, u, vmax,vtau1,vtau2
def fit_threedualexp(t0, u0, p0 = array([0, 0, 0, 0, 0, 0, 0, 0, 0]), delay = 0):
"""
Fit exponential to signal
t0 = timebase
u0 = signal
"""
from scipy.optimize import leastsq
def peval(t, p, delay = 0):
dt = t[1]-t[0]
tp = (p[1]*p[2])/(p[2] - p[1]) * log(p[2]/p[1])
factor = 1 / (-exp(-tp/p[1]) + exp(-tp/p[2]))
u = factor * p[0] * ( -exp(-(t-delay)/p[1]) + exp(-(t-delay)/p[2]) )
tp = (p[4]*p[5])/(p[5] - p[4]) * log(p[5]/p[4])
factor = 1 / (-exp(-tp/p[4]) + exp(-tp/p[5]))
v = p[3] * ( -exp(-(t-delay)/p[4]) + exp(-(t-delay)/p[5]) )
tp = (p[7]*p[8])/(p[8] - p[7]) * log(p[8]/p[7])
factor = 1 / (-exp(-tp/p[7]) + exp(-tp/p[8]))
z = p[6] * ( -exp(-(t-delay)/p[7]) + exp(-(t-delay)/p[8]) )
u = u+v+z
u[0:delay/dt]=0
return u
def residuals(p, u, t, delay = 0):
err = u-peval(t, p, delay)
return err
plsq = leastsq(residuals, p0, args=(u0, t0, delay))
umax = plsq[0][0]
utau1 = plsq[0][1]
utau2 = plsq[0][2]
vmax = plsq[0][3]
vtau1 = plsq[0][4]
vtau2 = plsq[0][5]
zmax = plsq[0][6]
ztau1 = plsq[0][7]
ztau2 = plsq[0][8]
u = peval(t0, array([umax,utau1,utau2,vmax,vtau1,vtau2,zmax,ztau1,ztau2]), delay)
return umax, utau1, utau2, u, vmax, vtau1, vtau2, zmax, ztau1, ztau2
def fit_tripleexp(t0, u0, p0 = array([0, 0, 0, 0]), delay = 0):
"""
Fit exponential to signal
t0 = timebase
u0 = signal
"""
from scipy.optimize import leastsq
def peval(t, p, delay = 0):
dt = t[1]-t[0]
u = p[0] * ( -exp(-(t-delay)/p[1]) + exp(-(t-delay)/p[2]) + exp(-(t-delay)/p[3]) )
u[0:delay/dt]=0
return u
def residuals(p, u, t, delay = 0):
err = u-peval(t, p, delay)
return err
plsq = leastsq(residuals, p0, args=(u0, t0, delay))
umax = plsq[0][0]
utau1 = plsq[0][1]
utau2 = plsq[0][2]
utau3 = plsq[0][3]
u = peval(t0, array([umax,utau1,utau2,utau3]), delay)
return umax, utau1, utau2, utau3, u
def shannon_interp(t0, y0, t, tu=None, chunk_size=0):
"""
function y = shannon_interp(t0, y0, t, tu)
band-passed interpolation of non-uniform sampled data to
done by brute-force n x n matrix inversion, so only viable for
small sample numbers n.
t0 = non-uniform sample times
with t0 = [] uses linspaced data with same range as tu
y0 = sample data
tu = uniform sampling times (same length as t0)
t = timebase for interpolation
y = values at interpolated times t
"""
#print size(y0)
y = []
tn = []
it_start = 0
if chunk_size == 0:
chunk_size = len(t0)
for i in xrange(0, len(t0), chunk_size): # split with given chunk_size
t0_chunk = t0[i:i + chunk_size]
y0_chunk = y0[i:i + chunk_size]
if i == int((ceil((len(t0) / double(chunk_size)) - 1) * chunk_size)): # if this the last run
it_end = len(t) # use full rest of t
else:
it_end = t.searchsorted(t0_chunk[-1]) + 1
## test searchsorted()
# t = array([1,2,3,3.9,4.1,5,6])
# t.searchsorted(4)
# print str(it_start) + " " + str(it_end)
t_offset = t[it_start]
t0_chunk = t0_chunk - t_offset
t_chunk = t[it_start:it_end+1] - t_offset
it_start = it_end + 1
nsamp = len(t0_chunk)
if tu == None:
tu = linspace(t0_chunk[0], t0_chunk[-1], nsamp)
T = tu[2]-tu[1]
G = zeros((nsamp, nsamp))
for l in range(nsamp):
for k in range(nsamp):
G[l, k] = sinc((t0_chunk[l] - tu[k]) / T)
yu = linalg.solve(G,y0_chunk)
y_chunk = 0
for l in range(nsamp):
y_chunk = y_chunk + yu[l] * sinc((t_chunk - tu[l]) / T)
y.append(y_chunk)
tn.append(t_chunk)
y = concatenate(y)
tn = concatenate(tn)
#plot(t0, y0, "*b", t, y, "-r")
#axis(ymin=min(y0), ymax=max(y0))
#show()
## check missed values
#print set(t).difference(set(tn))
return y
def get_spikes(v, vthres, t):
'''
s, ts = get_spikes(v, vthres, t)
Spike detection implemented as voltage threshold crossings
v = membrane potential
vthres = threshold
t = time vector (in s)
-
s = spike 'bit' vector s
ts = (interpolated) spike times
'''
s = zeros(len(v))
s[1:] = ((v[:-1] <= vthres) & (v[1:] > vthres)).astype(float)
i = nonzero(s)[0]
ts = t[i-1]+(t[i]-t[i-1])*(vthres-v[i-1])/(v[i]-v[i-1])
return s, ts
def get_spikefreq(spike_times, stimlength = 0, compute_mean = 0, change_factor = 0.3):
'''
Compute spike frequency, set to second spike for causality,
also returns mean and onset frequency
Note: time in s now!
'''
if len(np.array(spike_times)) >= 2: # compute only if at least 2 spikes
spike_diff = diff(spike_times) # differentiate for spike intervals!
spike_freq = 1 / spike_diff # spike_times is in s
freq_times = spike_times[1:] # Set frequency to second spike for causality!
freq_onset = spike_freq[0] # Onset frequency only
a = [0]
if compute_mean > 1:
a = where(freq_times > (stimlength - 1))
print a
elif change_factor == 0:
freq_mean = mean(spike_freq[int(np.ceil(len(spike_freq)*9/10.)):])
elif any(spike_times > (stimlength / 2)) & compute_mean: # compute only if there is sustained spiking and a request is actually made
freq_change = abs(diff(spike_freq)) # check how the firing rate is changing
a = where(freq_change < change_factor) # check if rate is adapting
if any(a): # only compute mean firing rate if spiking adapts
freq_stable = a[0][0] # get first tuple and first element. here the firing rate has adapted
freq_mean = mean(spike_freq[freq_stable:]) # compute mean firing rate
else:
freq_mean = float('NaN')
else:
freq_times = np.array([])
spike_freq = np.array([])
freq_mean = float('NaN')
freq_onset = float('NaN')
return freq_times, spike_freq, freq_mean, freq_onset
def get_magphase(input_signal, t, output_signal, t_out, method = "peak", f = None, deb = 0):
"""
Compute the mean amplitude, mean magnitude and mean phase from an input and
output signal with a single frequency.
Default method *peak": peak detection
Magnitude is computed by: full oscillation out / full oscillation in
Minimum length of signal and response has to be 1.5 * 1 / f
Other method "fit": least-square fit, f has to be given!
"""
if method == "peak": # t and t_out have to be identical!
if size(t) != size(t_out):
raise ValueError('Input and output need same timebase! Use method "fit" instead!')
dt = t[2] - t[1]
input_signal_temp = input_signal - mean(input_signal) # remove holding current for amplitude detection
pos_halfwaves = concatenate((where(input_signal_temp > 0.75 * max(input_signal_temp))[0], array([len(input_signal_temp)]))) # detect the positive half waves
iend = pos_halfwaves[where(diff(pos_halfwaves) > 2)[0]] # detect where the half waves end, limit of 2 is arbitrary, 1 would also work
f = 1 / (mean(diff(iend)) * dt) # compute frequency
peak_vec_in = zeros(len(iend)-1) # construct vectors for peak values
peak_vec_out = zeros(len(iend)-1) # construct vectors for peak values
peak_vec_in_index = zeros(len(iend)-1, int) # construct vectors for peak indexes
peak_vec_out_index = zeros(len(iend)-1, int) # construct vectors for peak indexes
amptwice_vec_in = zeros(len(iend)-1) # construct vectors for size of full oscillation
amptwice_vec_out = zeros(len(iend)-1) # construct vectors for size of full oscillation
mean_vec_out = zeros(len(iend)-1) # construct vectors for size of full oscillation
for i in range(len(iend)-1): # iterate through all sections
wave_cut_in = input_signal[iend[i]:iend[i+1]] # cut out input section
peak_vec_in[i], i_in, min_in = wave_cut_in.max(0), wave_cut_in.argmax(0), wave_cut_in.min(0) # get peak positions, indexes and minimas
amptwice_vec_in[i] = peak_vec_in[i] - min_in
peak_vec_in_index[i] = int(iend[i] + i_in) # convert to global indexes
wave_cut_out = output_signal[iend[i]:iend[i+1]] # cut out output section
peak_vec_out[i], i_out, min_out = wave_cut_out.max(0), wave_cut_out.argmax(0), wave_cut_out.min(0) # get peak positions, indexes and minimas
amptwice_vec_out[i] = peak_vec_out[i] - min_out
peak_vec_out_index[i] = int(iend[i] + i_out) # convert to global indexes
mean_vec_out[i] = amptwice_vec_out[i]*0.5 + min_out
phase_mean = mean((peak_vec_in_index-peak_vec_out_index) * dt / (1 / f) * 360) # compute phase
mag_mean = mean(amptwice_vec_out / amptwice_vec_in) # compute magnitude
amp_mean = mean(peak_vec_out) # just compute mean of amplitude
umean = mean(mean_vec_out[i])
if method == "fit":
print "- fitting"
imean, iamp, iphase, i = fit_sinusoid(f, t, input_signal)
umean, uamp, uphase, u = fit_sinusoid(f, t_out, output_signal, t)
phase_mean = (uphase - iphase) * (180 / pi)
mag_mean = uamp / iamp
amp_mean = uamp + umean # for voltage amplitude DAngelo 2001
if method == "fft":
if any(abs(t_out - t) > 0.00000001): # bloody floating point precision
raise ValueError('Time base of input (t) and output (t_out) have to be identical')
imean, iamp, iphase, i = fit_sinusoid(f, t, input_signal)
umean, ramp, rphase, u = fit_sinusoid_fft(f, t_out, output_signal, i = input_signal)
phase_mean = rphase * (180 / pi)
mag_mean = ramp
amp_mean = ramp * iamp
print f, amp_mean
#plt.figure('FIT')
#ax99 = plt.subplot(1,1,1)
#ax99.plot(t_out, output_signal,'b')
#ax99.plot(t_out, u,'r')
#plt.savefig("./figs/fit_" + str(f) + ".pdf", dpi = 300, transparent=True) # save it
#plt.clf()
return amp_mean, mag_mean, phase_mean, umean, u
def construct_Stimulus(noise_data, fs, amp = 1, ihold = 0, tail_points = 2, delay_baseline = 4):
"""
Construct Stimulus from cnoise/msine input and other parameters.
"""
#inin = 8 # stimulate before with 10 s of signal
inin = np.array((len(noise_data)/fs)*0.1).clip(max=8)
stim_data = concatenate((noise_data[-inin*fs:], noise_data)) # increase length of stimulus # no normalization here: / max(abs(noise_data))
stimulus = concatenate((concatenate((zeros(round(delay_baseline*fs)), amp * stim_data)), zeros(round(tail_points*fs)))) # construct stimulus
iholdvec = concatenate((zeros(round(fs)), ones(round(len(stimulus) - 1 * fs)) * ihold))
stimulus = stimulus + iholdvec
dt = 1 / fs
t = arange(0, len(stimulus) * dt,dt) # time vector of stimulus [s]
t_startstop = np.array([inin+delay_baseline, inin+delay_baseline+len(noise_data)/fs])
return stimulus, t, t_startstop
def construct_Pulsestim(dt = 0.025e-3, pulses = 1, latency = 10e-3, stim_start = 0.02, stim_end = 0.02, len_pulse = 0.5e-3, amp_init = 1, amp_next = None):
"""
Construct a pulse stimulus in the form of |---stim_start---|-len_pulse-|--(latency-len_pulse)--|...|-len_pulse-|--(latency-len_pulse)--|--stim_end--|
For stim_end shorter than pulse: stim_end = stim_end + len_pulse
"""
#print dt
fs = 1 / dt
if len(np.shape(amp_next)) > 0:
pulses = len(amp_next)
amp_vec = amp_next
else:
if amp_next == None:
amp_vec = np.ones(pulses)*amp_init
else:
amp_vec = np.ones(pulses)*amp_next
amp_vec[0] = amp_init
if len(np.shape(latency)) > 0:
pass
else:
latency = np.ones(pulses)*latency
if len(amp_vec) != len(latency):
raise ValueError('amp_vec and latency vectors do not have the same size!!!')
if stim_end < len_pulse:
print "From construct_Pulsestim: stim_end shorter than pulse, setting stim_end = stim_end + len_pulse"
stim_end = stim_end + len_pulse
ivec = zeros(round((stim_start + sum(latency) + stim_end)*fs)) # construct zero vector to begin with
t = arange(0, len(ivec))*dt # construct time vector
ivec[round(stim_start*fs):round((stim_start+len_pulse)*fs)] = amp_vec[0]
for i in range(1, pulses):
ivec[round((stim_start+sum(latency[0:i]))*fs):round((stim_start+sum(latency[0:i])+len_pulse)*fs)] = amp_vec[i]
#ivec_new = concatenate((zeros(round((stim_start + (i - 1) * latency[i-1]) * fs)), ones(round(len_pulse * fs)) * amp)) # stimulus delay + spike
#
#ivec_new = concatenate((ivec_new, zeros(round(((pulses - i + 1) * latency[i-1] - len_pulse + stim_end) * fs)))) # rest of stimulus
#
#if len(ivec) > len(ivec_new):
# ivec_new = concatenate(( ivec_new, zeros(len(ivec)-len(ivec_new)) ))
#
#if len(ivec) < len(ivec_new):
# rem = -1*(len(ivec_new)-len(ivec))
# ivec_new = ivec_new[:rem]
#ivec = ivec + ivec_new
#if len(t) != len(ivec):
#raise ValueError('Both vectors do not have the same size!!!')
return t, ivec
def compute_Impedance(voltage, current, t1, stimulus, t, noise_data_points, freq_wp = None, do_csd = 0, w_length = 5):
"""
Compute the impedance using input and output and cross spectral density method,
cut out relevant parts with knowledge of noise_data_points
w_length: desired length of csd window
"""
from matplotlib.mlab import csd
response = voltage
#stimulus_out = current
# no interpolation is best !!
#stimulus_out_ds = interp(t,t1[:-1],stimulus_out[:-1]) # interpolate (downsample) to be eqivalent with input
response_ds = interp(t,t1[:-1],response[:-1]) # interpolate (downsample) to be eqivalent with input
#stimulus_out_ds = stimulus_out[:end-1] # no interpolation