-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinference_methods.py
2056 lines (1751 loc) · 76.1 KB
/
inference_methods.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 python2
# -*- coding: utf-8 -*-
'''
collection of functions for the generation of synthetic data via simulation of
the generative models as well as for the evaluation of spike train likelihoods
-- written by Josef Ladenbauer in 2018/2019
'''
import numpy as np
import scipy.integrate
import scipy.optimize
import multiprocessing
from math import exp
from scipy.linalg import solve_banded
import tables
import time
from warnings import warn
import matplotlib.pyplot as plt
from numba import njit
### ===========================================================================
'''
1st part: functions for data generation, i.e., numerical simulation of stoch.
differential equations that implement (networks of) exponential/leaky
integrate-and-fire neurons subject to (external) fluctuating inputs
'''
@njit
def simulate_EIF_numba(tgrid,V_init,taum,Vth,Vr,VT,DeltaT,Tref,
mu_vec,sigma_vec,rand_vec):
dt = tgrid[1] - tgrid[0]
V = V_init*np.ones(len(tgrid))
Sp_times_dummy = np.zeros(int(len(tgrid)/10))
sp_count = int(0)
sqrt_dt = np.sqrt(dt)
input_dt = dt*mu_vec + sigma_vec*sqrt_dt*rand_vec
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
V[i_t] = V[i_t-1] + f1*V[i_t-1] + f2*np.exp((V[i_t-1]-VT)/DeltaT) + \
input_dt[i_t-1]
# refr. period
if sp_count>0 and tgrid[i_t]-Sp_times_dummy[sp_count-1]<Tref:
V[i_t] = Vr
if V[i_t]>Vth:
V[i_t] = Vr
sp_count += 1
Sp_times_dummy[sp_count-1] = tgrid[i_t]
Sp_times = np.zeros(sp_count)
if sp_count>0:
for i in range(sp_count):
Sp_times[i] = Sp_times_dummy[i]
return V, Sp_times
@njit
def simulate_EIF_alphapert_numba(tgrid,V_init,taum,Vth,Vr,VT,DeltaT,Tref,mu,sigma,
tperts,J_alpha,tau_alpha,d,rand_vec):
dt = tgrid[1] - tgrid[0]
V = V_init*np.ones(len(tgrid))
s = np.zeros_like(tgrid)
x = np.zeros_like(tgrid)
Sp_times_dummy = np.zeros(int(len(tgrid)/10))
sp_count = int(0)
J_alpha *= np.exp(1)/tau_alpha
tau2 = tau_alpha**2
sqrt_dt = np.sqrt(dt)
bg_input_dt = dt*mu + sigma*sqrt_dt*rand_vec
pert_cnt = 0
n_perts = len(tperts)
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
s[i_t] = s[i_t-1] + dt*x[i_t-1]
x[i_t] = x[i_t-1] - dt*(2.0/tau_alpha * x[i_t-1] + s[i_t-1]/tau2)
V[i_t] = V[i_t-1] + f1*V[i_t-1] + f2*np.exp((V[i_t-1]-VT)/DeltaT) + \
dt*J_alpha*s[i_t-1] + bg_input_dt[i_t-1]
# refr. period
if sp_count>0 and tgrid[i_t]-Sp_times_dummy[sp_count-1]<Tref:
V[i_t] = Vr
if V[i_t]>Vth:
V[i_t] = Vr
sp_count += 1
Sp_times_dummy[sp_count-1] = tgrid[i_t]
if pert_cnt<n_perts:
if tgrid[i_t]>=tperts[pert_cnt]+d and tgrid[i_t]<tperts[pert_cnt]+d+dt:
x[i_t] += 1.0
pert_cnt += 1
Sp_times = np.zeros(sp_count)
if sp_count>0:
for i in range(sp_count):
Sp_times[i] = Sp_times_dummy[i]
return V, J_alpha*s, Sp_times
@njit
def simulate_EIF_deltapert_numba(tgrid,V_init,taum,Vth,Vr,VT,DeltaT,Tref,mu,sigma,
tperts,J,d,rand_vec):
dt = tgrid[1] - tgrid[0]
V = V_init*np.ones(len(tgrid))
Sp_times_dummy = np.zeros(int(len(tgrid)/10))
sp_count = int(0)
sqrt_dt = np.sqrt(dt)
bg_input_dt = dt*mu + sigma*sqrt_dt*rand_vec
pert_cnt = 0
n_perts = len(tperts)
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
V[i_t] = V[i_t-1] + f1*V[i_t-1] + f2*np.exp((V[i_t-1]-VT)/DeltaT) + \
bg_input_dt[i_t-1]
# refr. period
if sp_count>0 and tgrid[i_t]-Sp_times_dummy[sp_count-1]<Tref:
V[i_t] = Vr
if V[i_t]>Vth:
V[i_t] = Vr
sp_count += 1
Sp_times_dummy[sp_count-1] = tgrid[i_t]
if pert_cnt<n_perts:
if tgrid[i_t]>=tperts[pert_cnt]+d and tgrid[i_t]<tperts[pert_cnt]+d+dt:
V[i_t] += J
pert_cnt += 1
Sp_times = np.zeros(sp_count)
if sp_count>0:
for i in range(sp_count):
Sp_times[i] = Sp_times_dummy[i]
return V, Sp_times
@njit
def simulate_EIF_mudyn_deltapert_numba(tgrid,V_init,taum,Vth,Vr,VT,DeltaT,Tref,
mu_vec,sigma,tperts,J,d,rand_vec):
dt = tgrid[1] - tgrid[0]
V = V_init
Sp_times_dummy = np.zeros(int(len(tgrid)/10))
sp_count = int(0)
sqrt_dt = np.sqrt(dt)
bg_input_dt = dt*mu_vec + sigma*sqrt_dt*rand_vec
pert_cnt = int(0)
n_perts = len(tperts)
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
V += f1*V + f2*np.exp((V-VT)/DeltaT) + bg_input_dt[i_t-1]
# refr. period
if sp_count>0 and tgrid[i_t]-Sp_times_dummy[sp_count-1]<Tref:
V = Vr
if V>Vth:
V = Vr
sp_count += 1
Sp_times_dummy[sp_count-1] = tgrid[i_t]
if pert_cnt<n_perts:
if tgrid[i_t]>=tperts[pert_cnt]+d and tgrid[i_t]<tperts[pert_cnt]+d+dt:
V += J
pert_cnt += 1
Sp_times = np.zeros(sp_count)
if sp_count>0:
for i in range(sp_count):
Sp_times[i] = Sp_times_dummy[i]
return Sp_times
@njit
def simulate_EIF_adapt_numba(tgrid,V_init,taum,Vth,Vr,VT,DeltaT,Tref,mu,sigma,
Dw,tau_w,rand_vec):
dt = tgrid[1] - tgrid[0]
V = V_init*np.ones(len(tgrid))
w = np.zeros_like(tgrid)
Sp_times_dummy = np.zeros(int(len(tgrid)/10))
sp_count = int(0)
sqrt_dt = np.sqrt(dt)
bg_input_dt = dt*mu + sigma*sqrt_dt*rand_vec
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
V[i_t] = V[i_t-1] + f1*V[i_t-1] + f2*np.exp((V[i_t-1]-VT)/DeltaT) - \
dt*w[i_t-1] + bg_input_dt[i_t-1]
w[i_t] = w[i_t-1] - dt*w[i_t-1]/tau_w
# refr. period
if sp_count>0 and tgrid[i_t]-Sp_times_dummy[sp_count-1]<Tref:
V[i_t] = Vr
if V[i_t]>Vth:
V[i_t] = Vr
w[i_t] += Dw # def.: += Dw
sp_count += 1
Sp_times_dummy[sp_count-1] = tgrid[i_t]
Sp_times = np.zeros(sp_count)
if sp_count>0:
for i in range(sp_count):
Sp_times[i] = Sp_times_dummy[i]
return V, w, Sp_times
@njit
def get_w0_values_numba(Sptimes, tau_w):
w0_vals = np.zeros_like(Sptimes)
t = Sptimes[0]
w = 0.0
dt = 0.1 #ms
f = dt/tau_w
n_sp = len(Sptimes)
sp_cnt = int(0)
tend = Sptimes[-1]+2*dt
w_sum = 0; w_cnt = 0
while t<tend:
if sp_cnt<n_sp:
if t>=Sptimes[sp_cnt] and t<Sptimes[sp_cnt]+dt:
w += 1.0
w0_vals[sp_cnt] = w
sp_cnt += 1
w -= f*w
t += dt
w_sum += w
w_cnt += 1
w_mean = w_sum/w_cnt
return w0_vals, w_mean
@njit
def get_w_trace_numba(Sptimes, tau_w, dt):
tgrid = np.arange(0, Sptimes[-1]+dt, dt)
w = np.zeros_like(tgrid)
f = dt/tau_w
sp_cnt = int(0)
for i_t in range(1,len(tgrid)):
if tgrid[i_t]>=Sptimes[sp_cnt] and tgrid[i_t]<Sptimes[sp_cnt]+dt:
w[i_t] = w[i_t-1] + 1.0
sp_cnt += 1
else:
w[i_t] = w[i_t-1]*(1.0 - f)
return tgrid, w
@njit
def simulate_EIF_net_numba(tgrid,V0vals,taum,Vth,Vr,VT,DeltaT,Tref,muvals,
sigmavals,Jmat,delay,input_cc,randnvals,randnvals_c):
dt = tgrid[1] - tgrid[0]
N = len(Jmat)
Nrange = range(N)
V = V0vals.copy()
#Dmat_ndt = np.round(Dmat/dt)
delay_dt = np.round(delay/dt)*dt # constant delay (needs to be a multiple of dt)
Sp_times_dummy = np.zeros((N,int(len(tgrid)/10)))
sp_counts = np.zeros(N)
hasspiked_dpassed = np.zeros(N) # indicates which neuron has spiked delay time ago
sqrt_dt = np.sqrt(dt)
common_noise_weight = np.sqrt(input_cc)
indep_noise_weight = np.sqrt(1.0-input_cc)
f1 = -dt/taum
f2 = dt/taum * DeltaT
if not f2>0:
DeltaT = 1.0 # to make sure we don't get errors below
for i_t in range(1,len(tgrid)):
ext_input_dt = dt*muvals + sigmavals*sqrt_dt* \
( common_noise_weight*randnvals_c[i_t-1] + \
indep_noise_weight*randnvals[:,i_t-1] )
hasspiked_dpassed *= 0
for i_N in Nrange:
if tgrid[i_t]-Sp_times_dummy[i_N,int(sp_counts[i_N])-1] == delay_dt:
hasspiked_dpassed[i_N] = 1.0
for i_N in Nrange:
V[i_N] += f1*V[i_N] + \
f2*np.exp((V[i_N]-VT)/DeltaT) + \
ext_input_dt[i_N]
V[i_N] += np.dot(Jmat[i_N,:], hasspiked_dpassed)
# refr. period
if sp_counts[i_N]>0 and \
tgrid[i_t]-Sp_times_dummy[i_N,int(sp_counts[i_N])-1]<Tref:
V[i_N] = Vr
if V[i_N]>Vth:
V[i_N] = Vr
sp_counts[i_N] += 1
Sp_times_dummy[i_N,int(sp_counts[i_N])-1] = tgrid[i_t]
# Sp_times_dict = {}
# for i_N in Nrange:
# if sp_counts[i_N]>0:
# Sp_times_dict[i_N] = Sp_times_dummy[i_N,Sp_times_dummy[i_N,:]>0]
# else:
# Sp_times_dict[i_N] = np.array([])
# Sp_times_list = list(Nrange)
# for i_N in Nrange:
# if sp_counts[i_N]>0:
# Spt_tmp = Sp_times_dummy[i_N,:]
# Sp_times_list[i_N] = Spt_tmp[Spt_tmp>0]
# else:
# Sp_times_list[i_N] = np.array([])
# return Sp_times_dict, V
return Sp_times_dummy, sp_counts, V
### ===========================================================================
'''
2nd part: (core) functions for the calculation of (log-)likelihoods
'''
@njit
def EIF_pertISIdensityhat_numba(V_vec, kr, taum, Vr, VT, DeltaT, Tref,
mu, sigma, w_vec, t_pert_vec):
# calculates the ISI density p_ISI in the frequency domain: the unperturbed
# one and the corrections due to perturbations, where here we consider as
# perturbations delta kicks at various times given by t_pert_vec (separately)
# see SI section S2.2 of the paper
epsilon = 1e-4
dV = V_vec[1]-V_vec[0]
sig2term = 2.0/sigma**2
n = len(V_vec)
m = len(t_pert_vec)
krange = range(n-1, 0, -1)
mrange = range(m)
wrange = range(len(w_vec))
w_vec_pos = w_vec # if w_vec starts with 0 this will be accounted for below
pISIhat0_vec = 1j*np.ones(len(w_vec))
pISIhat1_mat = 1j*np.ones((m,len(w_vec)))
phat_w0 = 1j*np.ones(n)
phat_wk = 1j*np.ones(n)
pah_vec = 1j*np.zeros(n)
sumsum = 1j*np.zeros((m,n))
if DeltaT>0:
Psi = DeltaT*np.exp((V_vec-VT)/DeltaT)
else:
Psi = 0.0*V_vec
F = sig2term*( ( V_vec-Psi )/taum - mu )
A = np.exp(dV*F)
F_dummy = F.copy()
F_dummy[F_dummy==0.0] = 1.0
B = (A - 1.0)/F_dummy * sig2term
sig2term_dV = dV * sig2term
# first the unperturbed ISI density
# start with zero frequency separately
if w_vec[0]==0:
qah = 1.0 + 0.0*1j; pah = 0.0*1j; qbh = 0.0*1j; pbh = 0.0*1j;
phat_w0[-1] = pbh # adjusted below
for k in krange:
if k>kr:
if not F[k]==0.0:
pah = pah * A[k] + B[k]
else:
pah = pah * A[k] + sig2term_dV
else:
if not F[k]==0.0:
pah = pah * A[k] + B[k]
pbh = pbh * A[k] - B[k]
else:
pah = pah * A[k] + sig2term_dV
pbh = pbh * A[k] - sig2term_dV
phat_w0[k-1] = pbh
pah_vec[k-1] = pah
pISIhat0_vec[0] = 1.0
phat_w0 += pISIhat0_vec[0]*pah_vec
w_vec_pos = w_vec[1:]
# continue with positive frequencies
for iw in range(len(w_vec_pos)):
qah = 1.0 + 0.0*1j; pah = 0.0*1j; qbh = 0.0*1j; pbh = 0.0*1j;
phat_wk[-1] = pbh # adjusted below
fw = dV*1j*w_vec_pos[iw]
refterm = np.exp(-1j*w_vec_pos[iw]*Tref)
for k in krange:
if not k==kr+1:
qbh_new = qbh + fw*pbh
else:
qbh_new = qbh + fw*pbh - refterm
if not F[k]==0.0:
pah_new = pah * A[k] + B[k] * qah
pbh_new = pbh * A[k] + B[k] * qbh
else:
pah_new = pah * A[k] + sig2term_dV * qah
pbh_new = pbh * A[k] + sig2term_dV * qbh
qah += fw*pah
qbh = qbh_new; pbh = pbh_new; pah = pah_new;
phat_wk[k-1] = pbh
pah_vec[k-1] = pah
pISIhat0_vec[iw+1] = -qbh/qah
phat_wk += pISIhat0_vec[iw+1]*pah_vec
for it in mrange:
sumsum[it,:] += np.exp(1j*w_vec_pos[iw]*t_pert_vec[it]) * phat_wk
# next the corrections due to perturbation
for it in mrange:
p0_tpert = (w_vec[1]-w_vec[0]) * (phat_w0 + sumsum[it,:] + \
np.conj(sumsum[it,:])) / (2*np.pi)
# the following 5 lines implement a correction of the membrane voltage
# density at the perturbation time, which may be necessary because of
# improper parameter values for the numerical scheme (allowing for
# increased efficiency and robustness of the method)
dummy = p0_tpert.real
k = n-1
while dummy[k]>=0 and k>0:
k -= 1
p0_tpert[:k+1] = 0.0
prop_not_spiked = dV*np.sum(p0_tpert[k:]) # can be interpreted as
# proportion of trials in which the neuron has not yet spiked
if prop_not_spiked.real>epsilon:
for iw in wrange:
qah = 1.0 + 0.0*1j; pah = 0.0*1j; qbh = 0.0*1j; pbh = 0.0*1j;
fw = dV*1j*w_vec[iw]
inhom = np.exp(-t_pert_vec[it]*1j*w_vec[iw]) * p0_tpert
for k in krange:
qbh_new = qbh + fw*pbh
if not F[k]==0.0:
pah_new = pah * A[k] + B[k] * qah
pbh_new = pbh * A[k] + B[k] * (qbh - inhom[k])
else:
pah_new = pah * A[k] + sig2term_dV * qah
pbh_new = pbh * A[k] + sig2term_dV * (qbh - inhom[k])
qah += fw*pah
qbh = qbh_new; pbh = pbh_new; pah = pah_new;
pISIhat1_mat[it,iw] = -qbh/qah
else:
pISIhat1_mat[it,:] = 0.0
return pISIhat0_vec, pISIhat1_mat
@njit
def EIF_ISIdensityhat_numba(V_vec, kr, taum, Vr, VT, DeltaT, Tref,
mu, sigma, w_vec):
# calculates the unperturbed ISI density in the frequency domain,
# see SI section S2.2 of the paper
dV = V_vec[1]-V_vec[0]
sig2term = 2.0/sigma**2
n = len(V_vec)
m = len(w_vec)
mrange = range(m)
krange = range(n-1, 0, -1)
fpth_vec = 1j*np.ones(m)
if DeltaT>0:
Psi = DeltaT*np.exp((V_vec-VT)/DeltaT)
else:
Psi = 0.0*V_vec
F = sig2term*( ( V_vec-Psi )/taum - mu )
A = np.exp(dV*F)
F_dummy = F.copy()
F_dummy[F_dummy==0.0] = 1.0
B = (A - 1.0)/F_dummy * sig2term
sig2term_dV = dV * sig2term
for iw in mrange:
qah = 1.0 + 0.0*1j; pah = 0.0*1j; qbh = 0.0*1j; pbh = 0.0*1j;
fw = dV*1j*w_vec[iw]
refterm = np.exp(-1j*w_vec[iw]*Tref)
for k in krange:
if not k==kr+1:
qbh_new = qbh + fw*pbh
else:
qbh_new = qbh + fw*pbh - refterm
if not F[k]==0.0:
pah_new = pah * A[k] + B[k] * qah
pbh_new = pbh * A[k] + B[k] * qbh
else:
pah_new = pah * A[k] + sig2term_dV * qah
pbh_new = pbh * A[k] + sig2term_dV * qbh
qah += fw*pah
qbh = qbh_new; pbh = pbh_new; pah = pah_new;
fpth_vec[iw] = -qbh/qah
return fpth_vec
def EIF_ISIdensity(V_vec, kr, taum, Vr, VT, DeltaT, Tref, mu, sigma, f_vec):
kr = np.argmin(np.abs(V_vec-Vr)) #re-calc to make sure kr corresponds to Vr
w_vec = 2*np.pi*f_vec
df = f_vec[1] - f_vec[0]
n = 2*len(f_vec)-1 #assuming f_vec starts with 0
dt = 1.0/(df*n)
pISI_times = np.arange(0,n)*dt
pISIhat = EIF_ISIdensityhat_numba(V_vec, kr, taum, Vr, VT, DeltaT, Tref,
mu, sigma, w_vec)
pISI_vals = np.fft.irfft(pISIhat,n)/dt
return pISI_times, pISI_vals
def find_mu_init(ISImean, args=()):
args = args + (ISImean,)
bnds = (-3.75, 1.75)
sol = scipy.optimize.minimize_scalar(find_mu_init_errorfun, bounds=bnds,
args=args, method='bounded',
options={'xatol': 1e-2})
mu_init = sol.x
return mu_init
def find_mu_init_errorfun(mu, *args):
params, sigma, ISImean = args
p_ss, r_ss, q_ss = EIF_steady_state_numba(params['V_vals'], params['V_r_idx'],
params['tau_m'], params['V_r'], params['V_T'],
params['Delta_T'], mu, sigma)
r_ss_ref = r_ss/(1+r_ss*params['T_ref'])
ISImean_cand = 1.0/r_ss_ref
return np.abs(ISImean_cand - ISImean)
def spiketrain_likel_musig(p, *args):
args = args + (p[0], p[1])
if p[1]<=0.3: #avoid sigma that is too small for Fokker-Planck method
loglval = 1e10
else:
_, loglval, _, _ = calc_spiketrain_likelihood(args)
if np.isnan(loglval):
loglval = 1e10 # optimization must be initialized within "non-nan region"
print('WARNING: optimization method stepped into nan-region')
error = np.abs(loglval)
return error
def spiketrain_likel_musigtaum(p, *args):
if p[2]<=0 or p[2]>50 or p[1]<=0.3: #avoid neg. taum, very large one, or
loglval = 1e10 #sigma that is too small
else:
args[0]['tau_m'] = p[2]
args = args + (p[0], p[1])
_, loglval, _, _ = calc_spiketrain_likelihood(args)
if np.isnan(loglval):
loglval = 1e10 # optimization must be initialized within "non-nan region"
print('WARNING: optimization method stepped into nan-region')
error = np.abs(loglval)
return error
def spiketrain_likel_alpha(p, *args):
# run LNexp model (w/o adaptation) for given parameters over specified
# duration and use the resulting spike rate time series to extract the
# loglikelihood for the given spike train
verbatim = False
mu, tperts, Sptimes, lastSpidx, d, tgrid, \
mu_vals, r_ss_array, tau_mu_array, ISImin, ISImax = args
J, tau = p
if tau>=0.1:
muf_init = mu
s_init = 0.0
x_init = 0.0
# we have one (possibly) very long spike time series;
# for computational reasons we divide it into several parts
dtsim = tgrid[1]-tgrid[0]
T_break = 10000.0 #ms (value not optimized)
N_parts = int(np.floor_divide(Sptimes[-1]-Sptimes[0],T_break) + 1)
loglval = 0.0
for k in range(N_parts):
# generate time points
if k!=N_parts-1:
tgrid = np.arange(k*T_break,(k+1)*T_break+dtsim/2,dtsim)
else: # last part
tgrid = np.arange(k*T_break,Sptimes[-1]+dtsim/2,dtsim)
tperts_part = tperts[(tperts>=tgrid[0]) & (tperts<=tgrid[-1])]
rate, signal, muf_last, s_last, x_last = \
sim_LNexp_sigfix_mupert(tgrid, mu, J, tau, d, tperts_part,
mu_vals, r_ss_array, tau_mu_array,
muf_init, s_init, x_init)
muf_init, s_init, x_init = muf_last, s_last, x_last
ratecumsum = np.cumsum(rate)
Sptimes_tmp = Sptimes[(Sptimes>=tgrid[0]) & (Sptimes<=tgrid[-1])]
lval = loglikelihood_Poisson(tgrid, rate, ratecumsum, Sptimes_tmp,
lastSpidx, ISImin, ISImax)
loglval += lval
if np.isnan(loglval):
print('')
print('problem at J, tau = ')
print(J, tau)
else:
loglval = 1e10
if verbatim:
print('J, tau, logl = ')
print(np.round(p[0],2), np.round(p[1],2), np.round(loglval,2))
return np.abs(loglval)
#def spiketrain_likel_mu_adapt_fast(p, *args):
# verbatim = True
# tau_w = p[0]
# mu, sigma, Dw_vals, mupert_vals, Sptimes, lastSpidx, params, \
# ISImin, ISImax, lastrun = args
# # mu, sigma from previous estimation w/o adaptation; keep sigma constant,
# # but adjust mu0 here such that mean of mu0 - w(t) = mu
# # mupert_vals and Dw_vals may be coarse for application to real neurons
#
# sigma_array = sigma * np.ones_like(params['t_grid'])
# pISI_vals = np.zeros((len(mupert_vals), len(sigma_array)))
# sp_times = np.array([0])
# dummy = np.exp(-params['t_grid']/tau_w)
# N = len(Sptimes)
# loglike_vals = np.zeros_like(Dw_vals)
# # get w_0 values (one for each spike time) based on Sptimes and tau_w:
# w0_vals, w0_mean = get_w0_values_numba(Sptimes, tau_w)
# for iw, w in enumerate(Dw_vals):
# lval = 0.0
# i_ts = 0
# w0_lookup = w*w0_vals
# mu0 = mu + w*w0_mean
# print('Dw={} mu={}'.format(w, mu0)) #TEMP!
# for im, mu1 in enumerate(mupert_vals):
# # effective mean input
# mu_array = mu0 - mu1*dummy
# fvm_dict = pISI_fvm_sg(mu_array, sigma_array, params, fpt=True, rt=sp_times)
# pISI_vals[im,:] = fvm_dict['pISI_vals']
# valid = True
# while i_ts < N-1 and valid:
# i_ts += 1
# if not i_ts-1 in lastSpidx:
# ISI = Sptimes[i_ts] - Sptimes[i_ts-1]
# if ISI>=ISImin and ISI<=ISImax:
# idx, weight = interp1d_getweight(w0_lookup[i_ts-1], mupert_vals)
# pISI_lookup = pISI_vals[idx,:]*(1.0-weight) + \
# pISI_vals[idx+1,:]*weight
# pISI_lookup_val = interpol(ISI, params['t_grid'], pISI_lookup)
# if pISI_lookup_val<=0:
# valid = False
# # neg. pISI value encoutered; this may be resolved by
# # decreasing discretizations steps for pISI_fvm_sg
# # print 'w =', w, ' ==> log-likelihood = nan'
# lval = np.nan
# else:
# lval += np.log( pISI_lookup_val )
# loglike_vals[iw] = lval
#
# iw = np.nanargmax(loglike_vals)
# # loglikelihood maximized along Delta_w for given tau_w:
# lval = np.nanmax(loglike_vals)
#
# if verbatim:
# print('')
# print('Dw, tauw, logl =')
# print(Dw_vals[iw], tau_w, lval)
#
# if lastrun:
# mu0 = mu + Dw_vals[iw]*w0_mean
# return Dw_vals[iw], tau_w, mu0, lval
# else:
# return np.abs(lval)
def spiketrain_likel_musig_adapt(p, *args):
verbatim = True
tau_w, mu, sigma = p
mu_no_adapt, sigma_no_adapt, Dw_vals, mupert_vals, Sptimes, lastSpidx, params, \
ISImin, ISImax, lastrun = args
# get w_0 values (one for each spike time) based on Sptimes and tau_w:
w0_vals, w0_mean = get_w0_values_numba(Sptimes, tau_w)
if mu<=mu_no_adapt or tau_w<1.5*params['tau_m'] or tau_w>1000 or \
sigma<=sigma_no_adapt or sigma>2*sigma_no_adapt:
return 1e10
else:
# input st. dev.
sigma_array = sigma * np.ones_like(params['t_grid'])
pISI_vals = np.zeros((len(mupert_vals), len(sigma_array)))
sp_times = np.array([0])
dummy = np.exp(-params['t_grid']/tau_w)
for im, mu1 in enumerate(mupert_vals):
# effective mean input
mu_array = mu - mu1*dummy
fvm_dict = pISI_fvm_sg(mu_array, sigma_array, params, fpt=True,
rt=sp_times)
pISI_vals[im,:] = fvm_dict['pISI_vals']
N = len(Sptimes)
loglike_vals = np.zeros_like(Dw_vals)
# get w_0 values (one for each spike time) based on Sptimes and tau_w:
w0_vals, _ = get_w0_values_numba(Sptimes, tau_w)
for iw, w in enumerate(Dw_vals):
lval = 0.0
i_ts = 0
w0_lookup = w*w0_vals
valid = True
while i_ts < N-1 and valid:
i_ts += 1
if not i_ts-1 in lastSpidx:
ISI = Sptimes[i_ts] - Sptimes[i_ts-1]
if ISI>=ISImin and ISI<=ISImax:
idx, weight = interp1d_getweight(w0_lookup[i_ts-1], mupert_vals)
pISI_lookup = pISI_vals[idx,:]*(1.0-weight) + \
pISI_vals[idx+1,:]*weight
pISI_lookup_val = interpol(ISI, params['t_grid'], pISI_lookup)
if pISI_lookup_val<=0:
valid = False
# neg. pISI value encoutered; this may be resolved by
# decreasing discretizations steps for pISI_fvm_sg
# print 'w =', w, ' ==> log-likelihood = nan'
lval = np.nan
else:
lval += np.log( pISI_lookup_val )
loglike_vals[iw] = lval
iw = np.nanargmax(loglike_vals)
# loglikelihood maximized along Delta_w for given tau_w:
lval = np.nanmax(loglike_vals)
if verbatim:
print('')
print('Dw, tauw, mu, sigma =')
print(Dw_vals[iw], tau_w, mu, sigma)
if lastrun:
return Dw_vals[iw], tau_w, mu, sigma, lval
else:
return np.abs(lval)
def spiketrain_likel_adapt(p, *args):
verbatim = False
tau_w = p[0]
mu, sigma, Dw_vals, mupert_vals, Sptimes, lastSpidx, params, \
ISImin, ISImax, lastrun = args
# input st. dev.
sigma_array = sigma * np.ones_like(params['t_grid'])
pISI_vals = np.zeros((len(mupert_vals), len(sigma_array)))
sp_times = np.array([0])
for im, mu1 in enumerate(mupert_vals):
# effective mean input
mu_array = mu - mu1*np.exp(-params['t_grid']/tau_w)
fvm_dict = pISI_fvm_sg(mu_array, sigma_array, params, fpt=True,
rt=sp_times)
pISI_vals[im,:] = fvm_dict['pISI_vals']
N = len(Sptimes)
loglike_vals = np.zeros_like(Dw_vals)
# get w_0 values (one for each spike time) based on Sptimes and tau_w:
w0_vals, _ = get_w0_values_numba(Sptimes, tau_w)
for iw, w in enumerate(Dw_vals):
lval = 0.0
i_ts = 0
w0_lookup = w*w0_vals
valid = True
while i_ts < N-1 and valid:
i_ts += 1
if not i_ts-1 in lastSpidx:
ISI = Sptimes[i_ts] - Sptimes[i_ts-1]
if ISI>=ISImin and ISI<=ISImax:
idx, weight = interp1d_getweight(w0_lookup[i_ts-1], mupert_vals)
pISI_lookup = pISI_vals[idx,:]*(1.0-weight) + \
pISI_vals[idx+1,:]*weight
pISI_lookup_val = interpol(ISI, params['t_grid'], pISI_lookup)
if pISI_lookup_val<=0:
valid = False
# neg. pISI value encoutered; this may be resolved by
# decreasing discretizations steps for pISI_fvm_sg
# print 'w =', w, ' ==> log-likelihood = nan'
lval = np.nan
else:
lval += np.log( pISI_lookup_val )
loglike_vals[iw] = lval
iw = np.nanargmax(loglike_vals)
# loglikelihood maximized along Delta_w for given tau_w:
lval = np.nanmax(loglike_vals)
if verbatim:
print('')
print('w, tauw, logl =')
print(Dw_vals[iw], tau_w, lval)
if lastrun:
return Dw_vals[iw], tau_w, lval
else:
return np.abs(lval)
def Jdij_estim_wrapper(args):
# this is called for each postsynaptic neuron and
# estimates connections for all presynaptic neurons
i_N, N, args_fixed = args
Spt_dict, sigma_init, N_tpert, params = args_fixed
ISImin = params['ISI_min']
N_pseudo = params['N_pseudo']
jitter_width = np.diff(params['pseudo_jitter_bnds'])[0]
J_estim_row = np.zeros(N)
J_estim_bias_row = np.zeros(N) # estim. bias
J_estim_z_row = np.zeros(N) # z-score
d_estim_row = np.zeros(N)
logl_coupled_row = np.zeros(N) * np.nan
# omit spikes that follow a previous one too shortly (ISImin)
remain_idx = Spt_dict[i_N]>0 # all true
for i in range(len(Spt_dict[i_N])-1):
if Spt_dict[i_N][i+1]-Spt_dict[i_N][i]<ISImin:
Spt_dict[i_N][i+1] = Spt_dict[i_N][i]
remain_idx[i+1] = False
Spt_dict[i_N] = Spt_dict[i_N][remain_idx]
# 1) estimation of baseline input parameters (mu, sigma) for the (postsyn.)
# neuron (without using the spike times of other neurons); tau_m can be
# fixed to a reasonable value (e.g., in [5,30] ms), but it may also be
# included in the estimation, see baseline_input_inference.py and adjust
# the lines below accordingly
start = time.time()
ISIs = np.diff(Spt_dict[i_N])
ISImax = np.max(ISIs) + 3.0
ISImean = np.mean(ISIs)
print('mean ISI of neuron {n_no} = {ISImean}'.format(n_no=i_N+1,
ISImean=np.round(ISImean,2)))
mu_init = find_mu_init(ISImean, args=(params,sigma_init))
init_vals = np.array([mu_init, sigma_init])
sol = scipy.optimize.minimize(spiketrain_likel_musig, init_vals,
args=(params, ISIs, ISImean, ISImax),
method='nelder-mead',
options={'xatol':0.025, 'fatol':0.01})
mu_estim, sigma_estim = sol.x
print('neuron {n_no}: mu_estim = {mu}, sigma_estim = {sig}'.format(
n_no=i_N+1, mu=np.round(mu_estim,2), sig=np.round(sigma_estim,2)))
args = (params, ISIs, ISImean, ISImax, mu_estim, sigma_estim)
lval, logl_uncoupled, pISI_times, pISI0 = calc_spiketrain_likelihood(args)
dt = pISI_times[1]-pISI_times[0]
ISI0mean = dt*np.sum(pISI0*pISI_times)
# 2) calculate ISI density corrections (pISI1) for generic perturbation
# times (t_pert): N_tpert time values in [0, t_pert_max], where
# t_pert_max > ISI0mean and pISI0[t_pert_max] == epsilon (e.g. 1e-3)
# then (further below) use lookups: t_pert that is closest to the observed
# arrival time
epsilon = 1e-3 #1e-4 to 1e-3
dummy = pISI0.copy()
dummy[pISI_times<ISI0mean] = 0
idx = np.argmin(np.abs(dummy - epsilon))
t_pert_max = pISI_times[idx]
t_pert_vals = np.linspace(0.0, t_pert_max, num=N_tpert)
d_tp = t_pert_vals[1]-t_pert_vals[0]
if params['pISI_method'] == 'fvm':
params['t_grid'] = pISI_times
pISI0, pISI1 = pISI0pISI1_deltaperts_fvm_sg(mu_estim, t_pert_vals,
sigma_estim, params)
elif params['pISI_method'] == 'fourier':
pISI1 = np.zeros((len(t_pert_vals), len(pISI_times)))
n = 2*len(params['freq_vals'])-1 #assuming freq_vals start with 0
pISI_times_tmp = np.arange(0,n)*dt
idcs = pISI_times_tmp<=ISImax
w_vec = 2*np.pi*params['freq_vals']
pISIhat0, pISIhat1 = EIF_pertISIdensityhat_numba(params['V_vals'],
params['V_r_idx'], params['tau_m'], params['V_r'],
params['V_T'], params['Delta_T'], params['T_ref'],
mu_estim, sigma_estim, w_vec, t_pert_vals[1:])
# for small perturbation times interpolate between t_pert=0 and smallest
# t_pert that yields a nonzero output from EIF_FPTpertdensityhat; for
# t_pert=0 use derivative of pISIhat0 w.r.t. Vr
dVr = 0.2 #must be a multiple of d_V
Vr_tp0 = params['V_r']+dVr
kr_tp0 = np.argmin(np.abs(params['V_vals']-Vr_tp0)) # reset index value
pISIhat0_dVr = EIF_ISIdensityhat_numba(params['V_vals'], kr_tp0, params['tau_m'],
Vr_tp0, params['V_T'], params['Delta_T'],
params['T_ref'], mu_estim, sigma_estim, w_vec)
pISI0dVr = np.fft.irfft(pISIhat0_dVr,n)/dt
pISI1[0,:] = (pISI0dVr[idcs] - pISI0)/dVr
for i_tp in range(1,len(t_pert_vals)):
if any(np.real(pISIhat1[i_tp-1,:]) != 0):
pISI1[i_tp,:] = np.fft.irfft(pISIhat1[i_tp-1,:],n)[idcs]/dt
else: #take previous one (should only occur for very small t_perts)
pISI1[i_tp,:] = pISI1[i_tp-1,:]
#pISI_inds_eff = pISI_times<=ISImax
#pISI_times = pISI_times[pISI_inds_eff]
#pISI0 = pISI0[pISI_inds_eff]
#pISI1 = pISI1[:,pISI_inds_eff]
# everything stored now
del pISIhat1 # free some space
# there is a transient peak in pISI1 following t_pert, which causes problems
# for the estimation of inhibitory connections (that are not very weak),
# the following "truncation" over a short period alleviates this difficulty
t_dur = 0.1 # ms
for itp, tp in enumerate(t_pert_vals):
idcs = (pISI_times>tp-dt) & (pISI_times<=tp+t_dur)
idx_tmp = (pISI_times>tp+t_dur)
dummy = pISI1[itp,idx_tmp]
pISI1[itp,idcs] = dummy[0]
print('precalculations for neuron {n_no} took {dur}s'.format(n_no=i_N+1,
dur=np.round(time.time() - start,2)))
# 3) next, for each ISI of the (postsyn.) neuron iN, determine the appropriate
# perturbation times for each presyn. neuron j_N and then determine the
# coupling strength J_ij that optimizes the (partial) likelihood for neuron
# iN, using (looking-up) the appropriate pISI1 corrections
ISIrange = range(len(ISIs))
for j_N in range(N):
if j_N!=i_N and len(Spt_dict[j_N])>0: # otherwise J_ij = 0, (no autapses,
# but this can be easily changed)
# for each pre spike determine the corresponding post ISI and save the
# t_pert lookup index considering delay d for pISI1 at that ISI (looping
# over d_grid values to find optimal delay)
# estimation on actual data:
Jij_estim_tmp = np.zeros_like(params['d_grid'])
loglike_tmp = np.zeros_like(params['d_grid'])
for i_d, delay in enumerate(params['d_grid']):
# generate list of i_tp indices (can be >1 per ISI)
# which indicate which (discrete) t_pert row(s) in pISI1 to use per ISI
tp_idx_list = [[] for l in ISIrange]
for ind, tspj in enumerate(Spt_dict[j_N]):
tspj += delay # mapping from presyn. spike time to postsyn.
# perturbation time
if tspj>Spt_dict[i_N][0] and tspj<Spt_dict[i_N][-1]:
# find the closest previous spike time of neuron i_N which
# determines the ISI under consideration, evaluate the
# duration and save the corresponding i_tp index
idx_prev_tspi = np.argmin( np.abs(
Spt_dict[i_N][Spt_dict[i_N]<tspj]-tspj) )
t_pert_local = tspj-Spt_dict[i_N][idx_prev_tspi]
if t_pert_local<t_pert_max+d_tp:
tp_idx_list[idx_prev_tspi] += \
[np.argmin(np.abs(t_pert_vals-t_pert_local))]
Jij_estim_tmp2 = np.zeros_like(params['J_init'])
loglike_tmp2 = np.zeros_like(params['J_init'])
for i_J, J_init in enumerate(params['J_init']):
args = (ISIs, ISImin, ISImax, tp_idx_list,
pISI_times, pISI0, pISI1, params['J_bnds'])
sol = scipy.optimize.minimize(spiketrain_likel_Jij, J_init, args=args,
method='nelder-mead', options={'xatol':0.05, 'fatol':1e-4})
Jij_estim_tmp2[i_J] = sol.x[0]
loglike_tmp2[i_J] = -sol.fun
J_idx = np.argmax(loglike_tmp2)
Jij_estim_tmp[i_d] = Jij_estim_tmp2[J_idx]
loglike_tmp[i_d] = loglike_tmp2[J_idx]
d_idx = np.argmax(loglike_tmp)
J_estim_row[j_N] = Jij_estim_tmp[d_idx]
d_estim_row[j_N] = params['d_grid'][d_idx]
logl_coupled_row[j_N] = loglike_tmp[d_idx]
print('connection {}<-{} estimated'.format(i_N+1, j_N+1))
if N_pseudo>0:
# estimation on pseudo data:
Jij_estim_pseudo = np.zeros(N_pseudo)
seeds = range(11,11+N_pseudo)
for n in range(N_pseudo):