-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfuns.jl
More file actions
2228 lines (1948 loc) · 75.2 KB
/
funs.jl
File metadata and controls
2228 lines (1948 loc) · 75.2 KB
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
"""
Copyright 2023 Gaston Sivori
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
using LinearAlgebra
using StatsBase
using SparseArrays
using DataStructures
using Distributions
using Plots
using StableRNGs
#quick functions
unzip(a) = map(x->getfield.(a, x), fieldnames(eltype(a)))
tosteps(a) = Int(round(a * sec_to_ms / sim_δt))
totime(a) = a * ms_to_sec * sim_δt
import Base: zero
function zero(::Type{Vector{Int64}})
return Vector{Int64}()
end
#Simple helper function to sort by row depending on first spike.
function first_true_index(row)
idx = findfirst(identity, row)
return isnothing(idx) ? Inf : idx
end
#e.g.
#perm = sortperm(1:size(pats[1], 1), by = row -> first_true_index(pats[1][row, :]))
#sorted_pats1 = pats[1][perm, :]
function bool_matrix_to_sparse_vector(bool_matrix::Matrix{Bool})
size_in = size(bool_matrix, 2)
sparse_vector = Vector{Vector{Int}}(undef,size_in)
for i in 1:size_in
sparse_vector[i] = findall(x -> x, bool_matrix[:, i])
end
return sparse(sparse_vector)
end
"""
zscorer(weights::Vector{Float64},sim_δt::Float64=0.1)
Slowly returns weights back to baseline Gaussian values.
# Inputs:
- `weights::Vector{Float64}`: vector of synaptic weights.
- `τ_z::Float64`: timescale of return (in ms).
- `μ::Float64=0.0`: mean of baseline Gaussian.
- `σ::Float64=1.0`: standard deviation of baseline Gaussian.
- `sim_δt::Float64=0.1`: simuation time step (in ms).
"""
function zscorer(weights::Vector{Float64}, τ_z::Float64, sim_δt::Float64=0.1)
zs = copy(weights)
signs = sign.(weights)
μ_zs = mean(zs)
σ_zs = std(zs)
target_zs = @. ((zs - μ_zs) / σ_zs )
dzs = @. (target_zs - zs) * abs.(zs) / τ_z
zs_weights = @. (zs + dzs * sim_δt )
return zs_weights
end
"""
pfail(weight::Float64)
Probability of transmission failure computation.
# Inputs:
- `weight::Float64`: synaptic weight.
"""
function pfail(weight::Float64)
pf = 1-0.8/(1+exp(-2(abs(weight)-1)))
return pf
end
"""
get_cluster_sizes(rng::StableRNG,n_exc::Int64, μ_cs::Int64, σ_cs::Int64, min_cs::Int64=9)
Samples different cluster sizes to fill up the network connectivity.
# Inputs:
- `rng::StableRNG`: Stable random number generator variable.
- `n_exc::Int64`: number of excitatory cells in network.
- `μ_cs::Int64`: average cluster size.
- `σ_cs::Int64`: standard deviation of cluster sizes.
- `min_cs::Int64`: minimal bound for cluster size.
"""
function get_cluster_sizes(rng::StableRNG,n_exc::Int64, μ_cs::Int64, σ_cs::Int64, min_cs::Int64=14)
remain = n_exc
cs = []
while remain > min_cs
new_cs = Int(ceil(rand(rng,Normal(μ_cs,σ_cs))))
remain -= new_cs
append!(cs,new_cs)
end
if remain <= min_cs
cs[end] += remain
else
append!(cs,remain)
end
return cs
end
"""
zero_bounding(w::AbstractArray, eta::Float64, PI::AbstractArray)
Detects changes of signs for enforcing Dale's Law.
# Inputs:
- `w::AbstractArray`: synaptic weight structure.
- `eta::Float64`: learning rate.
- `PI::AbstractArray`: plasticity induction vector.
"""
function zero_bounding(w::AbstractArray, eta::Float64, PI::AbstractArray)
return any((sign.(w .+ eta*PI) .* sign.(w)) .== 1.0,dims=2)
end
"""
jitter_data(data::AbstractArray, jitter::Float64, sim_δt::Float64)
Performs jittering of {data} by uniformly sampling {jitter} steps each input.
# Inputs:
- `S::AbstractArray`: input boolean vector of spikes.
- `jitter::Float64`: jittering time (in ms).
- `sim_δt`: simulation time step (in ms).
"""
function jitter_data(data::AbstractArray, jitter::Number, sim_δt::Float64)
jit_steps = Int(jitter/sim_δt)
(n_in, sim_len) = size(data)
shuffled_input = zeros(eltype(data),(n_in, sim_len))
for ci = 1:n_in
times = view(data,ci,:)
for (index,each) in enumerate(times)
if each != 0
adj = rand(-jit_steps:jit_steps)
if (index + adj < 1) || (index + adj > sim_len)
adj = -adj # fastest way
end
shuffled_input[ci,index+adj] = 1
end
end
end
return shuffled_input
end
"""
jitter_data(data::AbstractArray, jitter::Float64, sim_δt::Float64)
Performs jittering of {data} by uniformly sampling {jitter} steps each input.
# Inputs:
- `S::SparseMatrixCSC{Bool, Int64}`: input boolean sparse matrix.
- `jitter::Float64`: jittering time (in ms).
- `sim_δt`: simulation time step (in ms).
"""
function jitter_data(data::SparseMatrixCSC{Bool, Int64}, jitter::Number, sim_δt::Float64)
jit_steps = Int(jitter/sim_δt)
rows = Int64[]
cols = Int64[]
vals = Bool[]
for ci = 1:data.m
times,_ = findnz(data[ci,:])
adj = rand(-jit_steps:jit_steps,length(times))
aux = findall(times[1:5] .+ adj[1:5] .< 1)
adj[aux] = -adj[aux]
aux = findall(times[end-4:end] .+ adj[end-4:end] .> data.n) .- 5
adj[length(adj) .+ aux] *= -1
times += adj
append!(cols, times)
append!(vals, trues(length(times)))
append!(rows, ci*ones(length(times)))
end
return sparse(rows, cols, vals, data.m, data.n)
end
"""
NA_rates(v::Float64)
Returns rate parameters for sodium current. HH model.
Ref: Dayan P, Abbott LF (2001) Theoretical Neuroscience; (Eqs. 5.24)
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function NA_rates(v::Float64)
mα = 0.1*(v+40)/(1-exp(-(v+40)/10))
mβ = 4*exp(-(v+65)/18)
m_inf = mα/(mα + mβ)
τ_m = 1/(mα + mβ)
hα = 0.07*exp(-(v+65)/20)
hβ = 1/(1+exp(-(v+35)/10))
h_inf = hα/(hα + hβ)
τ_h = 1/(hα + hβ)
return m_inf, τ_m, h_inf, τ_h
end
"""
K_rates(v::Float64)
Returns rate parameters for potassium current. HH model.
Ref: Dayan P, Abbott LF (2001) Theoretical Neuroscience; (Eqs. 5.22)
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function K_rates(v::Float64)
nα = 0.01*(v+55)/(1-exp(-(v+55)/10))
nβ = 0.125*exp(-(v+65)/80)
n_inf = nα/(nα + nβ)
τ_n = 1/(nα + nβ)
return n_inf, τ_n
end
"""
NAP_rates(v::Float64)
Returns rate parameters for persistent sodium current.
Ref: Lipowsky et al, J.Neurophys 76:2181-2191, 1996.
https://journals.physiology.org/doi/epdf/10.1152/jn.1996.76.4.2181
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function NAP_rates(v::Float64)
mα = -1.74*(v-11)/(exp(-(v-11)/12.94)-1)
mβ = 0.06*(v-5.9)/(exp((v-5.9)/4.47)-1)
m_inf = 1/(1+exp(-(v-(-49.))/5))
m_exp = 1 - exp(-0.1*(mα+mβ))
return m_inf, m_exp
end
"""
Ka_rates(v::Float64)
Returns rate parameters for A-type potassium current (proximal).
Ref: Migliore et al 1999;
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function Ka_rates(v::Float64)
qt = 1^((35-24)/10) # at 35 C
zeta = -1.5 + -1/(1+exp((v-(-40))/5))
nα = exp(1.e-3*zeta*(v-11)*9.648e4/(8.315*(273.16+35)))
nβ = exp(1.e-3*zeta*0.55*(v-11)*9.648e4/(8.315*(273.16+35)))
lα = exp(1.e-3*3*(v-(-56))*9.648e4/(8.315*(273.16+35)))
lβ = exp(1.e-3*3*1*(v-(-56))*9.648e4/(8.315*(273.16+35)))
n_inf = 1/(1 + nα)
τ_n = nβ/(qt*0.05*(1+nα))
l_inf = 1/(1 + lα)
τ_l = lβ/(qt*0.05*(1+lα))#0.26*(v+50)/1
return n_inf, τ_n, l_inf, τ_l
end
"""
H_rates(v::Float64)
Returns rate parameters for Ih current.
Ref: Welie et al. (2006)
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function H_rates(v::Float64)
qt=4.5^((35-33)/10) #35 celcius
lα = exp(0.0378*2.2*(v+75))
lβ = exp(0.0378*2.2*0.4*(v+75))
linf = 1/(1+exp(-(v-(-73))/-8)) # -81 in code
τ_l = lβ/(1.0*qt*0.011*(1+lα))
#denom = 1/(1+exp((v+73)/8)) in paper
#τ_l = 182*exp((v+75)/30.1)/(1+exp((v+75)/12)) in paper
return linf, τ_l
end
"""
Kdr_rates(v::Float64)
Returns rate parameters for delayed rectifying potassium current.
Ref: Migliore et al 1999;
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function Kdr_rates(v::Float64)
qt = 1^((35-24)/10) # at 35 C
nα = exp(1.e-3*-3*(v-13)*9.648e4/(8.315*(273.16+35)))
nβ = exp(1.e-3*-3*0.7*(v-13)*9.648e4/(8.315*(273.16+35)))
n_inf = 1/(1 + nα)
τ_n = nβ/(qt*0.02*(1+nα))
return n_inf, τ_n
end
"""
M_rates(v::Float64)
Returns rate parameters for M- potassium current.
Ref: Yamada, W.M., Koch, C. and Adams, P.R. Multiple
channels and calcium dynamics. In: Methods in Neuronal Modeling,
edited by C. Koch and I. Segev, MIT press, 1989, p 97-134.
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function M_rates(v::Float64)
tadj = 2.3 ^ ((35-36)/10) #35 celcius
τ_peak = 1000. / tadj #in ms
m_inf = 1 / ( 1 + exp(-(v+35)/10) )
τ_m = τ_peak / ( 3.3 * exp((v+35)/20) + exp(-(v+35)/20) )
return m_inf, τ_m
end
"""
HVAc_rates(v::Float64)
Returns rate parameters for HVA calcium current.
Refs: Reuveni et al., 1993; Mainen and Sejnowski, 1996.
# Inputs:
- `v::Float64`: membrane potential (in mV).
"""
function HVAc_rates(v::Float64)
mα = (0.055*(-27-v))/(exp((-27-v)/3.8) - 1)
mβ = (0.94*exp((-75-v)/17))
m_inf = mα/(mα + mβ)
τ_m = (1/(mα + mβ))
hα = (0.000457*exp((-13-v)/50))
hβ = (0.0065/(exp((-v-15)/28)+1))
h_inf = hα/(hα + hβ)
τ_h = (1/(hα + hβ))
return m_inf, τ_m, h_inf, τ_h
end
"""
KCa_rates(Ca::Float64)
Returns rate parameters for K+ calcium-dependent current.
Refs: Mainen and Sejnowski, 1996.
# Inputs:
- `v::Float64`: membrane potential (in mV).
#Typically:
nk_inf, nk_exp, tadj = Kv_rates(Ca)
nk = nk + nexp*(nk_inf - nk)
gk = ghat_k*tadj*nk
Ik = gk*(Vk_r - v_dend) ; Vk_r = -75.0
"""
function KCa_rates(Ca::Float64)
α = 0.01*Ca^1.0
β = 0.02
tadj = 2.72 #2.3^((35-23)/10)
n_inf = α/(α + β)
τ_n = (1/tadj/(α + β))
return n_inf, τ_n, tadj
end
"""
Mg_block(v::Float64, Mg::Float64)
Returns NMDA channels open probability.
Ref: Dayan P, Abbott LF (2001) Theoretical Neuroscience;
# Inputs:
- `v::Float64`: membrane potential (in mV).
- `Mg::Float64`: Magnesium concentration (in mM).
"""
function Mg_block(v::Float64, Mg::Float64)
return (1+exp(-0.062*v)*(Mg/3.57))^-1
end
"""
S(x::Float64,β::Float64,α::Float64=1.0,θ::Float64=0.5)
Returns the activation for parameter x.
# Inputs:
- `x::Float64`: voltage trace (mV).
- `β::Float64`: TBW.
- `α::Float64=1.0`: TBW.
- `θ::Float64=0.5`: TBW.
"""
function S(x::Float64,β::Float64,α::Float64=1.0,θ::Float64=0.5)
# Sigmoidal activation function
return (1+α*exp(β*(-x+θ)))^-1
end
"""
moving_average(A::AbstractArray, m::Int)
Returns the moving average of array A with sliding window m (number of points).
"""
function moving_average(A::AbstractArray, m::Int)
out = similar(A)
R = CartesianIndices(A)
Ifirst, Ilast = first(R), last(R)
I1 = m÷2 * oneunit(Ifirst)
for I in R
n, s = 0, zero(eltype(out))
for J in max(Ifirst, I-I1):min(Ilast, I+I1)
s += A[J]
n += 1
end
out[I] = s/n
end
return out
end
"""
ζ(x::Float64,θ::Float64=0.1,τ::Float64=1.0)
Returns scaled weight based on Alpha function. This function is inspired from spine head volume distributions.
# Inputs:
- `x::Float64`: synaptic weight (a.u.).
- `θ::Float64=0.1`: weight threshold, i.e, x-axis crossing.
- `τ::Float64=1.0`: Alpha function time constant.
"""
function ζ(x::Float64,θ::Float64=0.1,τ::Float64=1.0)
# alpha function
return ((x - θ)/τ)*exp(-(x-θ-τ)/τ)
end
function coef_var(x::AbstractVector)
#Estimate coefficient of variation from data vector x with a sliding window.
return sqrt(var(x[.~iszero.(x)]))/mean(x[.~iszero.(x)])
end
function cv_estimate(x::AbstractVector)
#Estimate coefficient of variation from data vector x.
#Assumes x is log-normally distributed.
return sqrt(exp(var(log.(x[.~iszero.(x)])))-1)
end
function clip(x::AbstractVector, min::Float64, max::Float64)
#Clamps a vector of values between a range(min,max).
clamped_x = x[x .> min]
return clamped_x[clamped_x .< max]
end
function last_input(S::Array{Bool,2})
#Return last spike that ocurred (id,time in steps)
(n,tend) = size(S)
last_input = (1,1)
for ti = tend:-1:1
if any(S[:,ti] .== 1.0)
for ci in 1:n
if S[ci,ti]
which = (ci,ti)
return which
end
end
end
end
return last_input
end
"""
groupbypat(data::Vector{Any}, y_id::Vector{Any}, by::Vector{Any}, sim_δt::Float64)
Returns grouping parameters for patterns in structured input.
# Inputs:
- `data::Vector{Any}`: vector of all spike times.
- `y_id::Vector{Any}`: vector of indices for spike times on data vector.
- `by::Vector{Any}`: group id in an indexed vector representing pattern.
- `sim_δt::Float64`: simulation time step (in ms).
"""
function groupbypat(data::Vector{Any}, y_id::Vector{Any}, by::Vector{Any}, sim_δt::Float64)
xs = []
ys = []
for sp in data
for each in sp
push!(xs, each)
end
end
for ids in y_id
for each in ids
push!(ys,each)
end
end
grouping = zeros(Int64,length(xs))
for (index,(pat,pat_time)) in enumerate(by)
grouping[xs .>= pat_time*sim_δt] .= pat
end
return xs, ys, grouping
end
"""
groupybypat(data::AbstractArray, y_id::AbstractArray, by::AbstractArray, sim_δt::Float64)
Returns grouping parameters for patterns in structured input.
# Inputs:
- `xs::Vector{T}`: spike times in an indexed vector.
- `ys::Vector{T}`: neuron ids in an indexed vector.
- `by`: group id in an indexed vector representing pattern.
- `sim_δt`: simulation time step (in ms).
"""
function groupbypatsyns(data::AbstractArray, y_id::AbstractArray, by::AbstractArray, pat_syns::Tuple, pat_width::Int64, sim_δt::Float64)
xs = []
ys = []
for sp in data
for each in sp
push!(xs, each)
end
end
for ids in y_id
for each in ids
push!(ys,each)
end
end
grouping = zeros(Int64,length(xs))
for (index, (pat, pat_time)) in enumerate(by)
if pat == 0
grouping[xs .>= pat_time*sim_δt] .= pat
else
grouping[(indexin(ys, pat_syns[pat]) .!= nothing) .== (xs .>= pat_time*sim_δt) .== ((xs .<= (pat_time+pat_width)*sim_δt))] .= pat
end
end
return xs, ys, grouping
end
"""
groupybynat(data::AbstractArray, y_id::AbstractArray, by::AbstractArray, sim_δt::Float64)
Returns grouping parameters for patterns in structured input.
# Inputs:
- `xs::Vector{T}`: spike times in an indexed vector.
- `ys::Vector{T}`: neuron ids in an indexed vector.
- `by`: synaptic structure.
- `sim_δt`: simulation time step (in ms).
"""
function groupbynat(data::AbstractArray, y_id::AbstractArray, by::AbstractArray, sim_δt::Float64)
xs = []
ys = []
for sp in data
for each in sp
push!(xs, each)
end
end
for ids in y_id
for each in ids
push!(ys,each)
end
end
grouping = zeros(Int64,length(xs))
for (index,sign) in enumerate(sign.(by))
if sign == -1 #inhibitory
grouping[ys .== index] .= 0
else
grouping[ys .== index] .= 1
end
end
return xs, ys, grouping
end
"""
groupybynat(data::AbstractArray, y_id::AbstractArray, by::AbstractArray, sim_δt::Float64)
Returns grouping parameters for patterns in structured input.
# Inputs:
- `xs::Vector{T}`: spike times in an indexed vector.
- `ys::Vector{T}`: neuron ids in an indexed vector.
"""
function groupbynat(data::AbstractArray, y_id::AbstractArray)
xs = []
ys = []
for sp in data
for each in sp
push!(xs, each)
end
end
for ids in y_id
for each in ids
push!(ys,each)
end
end
grouping = zeros(Int64,length(xs))
grouping[xs .< 0.0] .= 1
return xs, ys, grouping
end
"""
groupbynat(data::AbstractArray, y_id::AbstractArray, exc_n::Int64)
Returns grouping parameters for exc/inh raster plot.
# Inputs:
- `data::Vector{T}`: spike times in an indexed vector.
- `ys::Vector{T}`: neuron ids in an indexed vector.
- `exc_n`: number of excitatory cells.
"""
function groupbynat(data::AbstractArray, y_id::AbstractArray, exc_n::Int64)
xs = []
ys = []
for sp in data
for each in sp
push!(xs, each)
end
end
for ids in y_id
for each in ids
push!(ys,each)
end
end
grouping = zeros(Int64,length(xs))
grouping[ys .> exc_n] .= 1
return xs, ys, grouping
end
"""
compute_fr(S::AbstractArray, sim_length::Float64, tbin::Float64=100.0)
Returns estimated firing rates (tbin=100.0ms.) of a single cell.
# Inputs:
- `S::AbstractArray`: vector of spike times of a single cell.
- `sim_length::Float64`: simulation time length.
- `tbin::Float64`: sliding window time length.
"""
function compute_fr(S::AbstractArray, sim_length::Float64, tbin::Float64=100.0)
frs = zeros(Int(sim_length/tbin)-1)
for fr in collect(1:length(frs))
count = 0
for (id,sp) in enumerate(S)
if sp > (fr-1)*tbin
if sp < fr*tbin
count += 1
else
frs[fr] = count/tbin*1000.0
break
end
end
end
end
return Array{Float64}(frs)
end
"""
get_act_neurs(S::AbstractArray, t::Float64, tbin::Float64=100.0)
Returns active neurons within a sliding window of time (tbin=5.0ms).
# Inputs:
- `S::AbstractArray`: vector of spike times of a single cell.
- `ti::Float64`: simulation time.
- `tbin::Float64`: sliding window time length.
"""
function get_act_neurs(S::AbstractArray, t::Float64, tbin::Float64=5.0)
act_neurs = falses(size(S)[1])
for ci in collect(1:length(act_neurs))
for (id,st) in enumerate(S)
if st > t-tbin
if st < t
act_neurs[ci] = 1
end
else
break
end
end
end
return Array{Float64}(act_neurs)
end
"""
get_exc(W::AbstractArray, exc_n::Int64)
Returns overall excitability of each cell defined as the sum of positive synaptic input.
# Inputs:
- `W::AbstractArray`: recurrent matrix of synaptic connectivity.
- `exc_n::Int64`: number of excitatory cells in the network.
"""
function get_exc(W::AbstractArray, exc_n::Int64)
exc = zeros(size(W)[1])
for ci in collect(1:length(exc))
exc[ci] = sum(W[1:exc_n,ci])
end
return Array{Float64}(exc)
end
"""
get_connections(rng::StableRNG,x::Vector{T}, y::Vector{T}; n=length(x)*length(y)) where {T}
Returns the pairs of a given number of connections between two vectors x and y.
# Inputs:
- `rng::StableRNG`: random number generator from StableRNG package.
- `x::Vector{T}`: first list of indices
- `y::Vector{T}`: second list of indices, starting at size(x)[1]+1.
- `n`: amount of connections.
"""
function get_connections(rng::StableRNG,x::Vector{T}, y::Vector{T}; n=length(x)*length(y)) where {T}
n = round(Int64, n)
xout = Vector{T}(undef,n)
yout = Vector{T}(undef,n)
p = length(x)*length(y)
s = zeros(Int,n)
StatsBase.knuths_sample!(rng,1:p,s)
@inbounds idx = CartesianIndices((length(x),length(y)))[s];
@inbounds for i = 1:n
xout[i] = x[ idx[i][1] ]
yout[i] = y[ idx[i][2] ]
end
return xout, yout
end
"""
all_to_all(x::Vector{T}, y::Vector{T}; n=length(x)*length(y)) where {T}
Returns the pairs of a given number of connections between two vectors x and y.
# Inputs:
- `x::Vector{T}`: first list of indices
- `y::Vector{T}`: second list of indices.
- `n`: amount of connections.
"""
function all_to_all(x::Vector{T}, y::Vector{T}; n=length(x)*length(y)) where {T}
n = round(Int64, n)
xout = Vector{T}(undef,n)
yout = Vector{T}(undef,n)
xout = repeat(x,length(y))
for j = 1:length(y)
yout[1+(j-1)*length(x):j*length(x)] .= y[j]
end
return xout, yout
end
"""
get_dist_clusters_conns(rng::StableRNG,x::Vector{T}, y::Int64, pop_sizes::Array{Int64,1}, conn_probs::Array{Float64,1}) where {T}
Returns the pairs of a given number of clustered connections (defined by a distribution) in a network of x cells.
# Inputs:
- `rng::StableRNG`: random number generator from StableRNG package.
- `x::Vector{T}`: list of cells.
- `y::Int64`: starting index of inh cells.
- `pop_sizes::Array{Int64,1}`: array of clustered connections sizes.
- `conn_probs::Array{Float64,1}`: probability of clustered connections.
- `μ::Array{Float64,1}`: means of synaptic weight distribution (LogNormal).
- `σ::Array{Float64,1}`: standard deviations of synaptic weight distribution (LogNormal).
"""
function get_dist_clusters_conns(x::Vector{T}, y::Int64, pop_sizes::Array{Int64,1}, conn_probs::Array{Float64,1}, μ::Array{Float64,1}, σ::Array{Float64,1}) where {T}
n = length(pop_sizes) # total number of clusters
n_inh = Int.(ceil.(pop_sizes .* .1)) # number of inh cells in each cluster
p = [pop_sizes .* pop_sizes, pop_sizes .* n_inh, pop_sizes .* n_inh, n_inh .* n_inh] # total number of connections x->y
nee_ids = Int.(ceil.(p[1] .* conn_probs[1]))
nei_ids = Int.(ceil.(p[2] .* conn_probs[2]))
nie_ids = Int.(ceil.(p[3] .* conn_probs[3]))
nii_ids = Int.(ceil.(p[4] .* conn_probs[4]))
n_ids = [nee_ids, nei_ids, nie_ids, nii_ids]
pops = length(n_ids)
s = [zeros.(Int,conns) for conns in n_ids]
xout = Vector{T}(undef,0)
yout = Vector{T}(undef,0)
zout = Vector{Float64}(undef,0)
idx = CartesianIndices((length(x), length(x))) # all indices
pope_start = pope_end = x[1]
popi_start = popi_end = Int(y)
for pop_i = 1:n
pope_start = pope_end
pope_end = pope_start + pop_sizes[pop_i]-1
popi_start = popi_end
popi_end = popi_start + n_inh[pop_i]-1
for conn in 1:pops
if ~isempty(1:p[conn][pop_i])
StatsBase.knuths_sample!(rng,1:p[conn][pop_i],s[conn][pop_i])
end
end
for i = 1:n_ids[1][pop_i] #exc->exc
push!(xout, x[ idx[pope_start:pope_end,pope_start:pope_end][s[1][pop_i]][i][1] ])
push!(yout, x[ idx[pope_start:pope_end,pope_start:pope_end][s[1][pop_i]][i][2] ])
weight = rand(rng,Normal(μ[1],σ[1]))
weight = weight * sign(weight)
push!(zout, weight)
end
for i = 1:n_ids[4][pop_i] #inh->inh
push!(xout, x[ idx[popi_start:popi_end,popi_start:popi_end][s[4][pop_i]][i][1] ])
push!(yout, x[ idx[popi_start:popi_end,popi_start:popi_end][s[4][pop_i]][i][2] ])
weight = rand(rng,Normal(μ[4],σ[4]))
weight = -1 * weight * sign.(weight)
push!(zout, weight)
end
for i = 1:n_ids[2][pop_i] #exc->inh
push!(xout, x[ idx[pope_start:pope_end,popi_start:popi_end][s[2][pop_i]][i][1] ])
push!(yout, x[ idx[pope_start:pope_end,popi_start:popi_end][s[2][pop_i]][i][2] ])
weight = rand(rng,Normal(μ[2],σ[2]))
weight = weight * sign.(weight)
push!(zout, weight)
end
for i = 1:n_ids[3][pop_i] #inh->exc
push!(xout, x[ idx[popi_start:popi_end,pope_start:pope_end][s[3][pop_i]][i][1] ])
push!(yout, x[ idx[popi_start:popi_end,pope_start:pope_end][s[3][pop_i]][i][2] ])
weight = rand(rng,Normal(μ[3],σ[3]))
weight = -1 * weight * sign.(weight)
push!(zout, weight)
end
end
return xout, yout, zout
end
"""
function get_clusters_conns(rng::StableRNG,x::Vector{T}, pop_sizes::Vector{Any}, conn_prob::Float64, μ::Float64, σ::Float64) where {T}
Returns the pairs of a given number of clustered connections (defined by a distribution) in a network of x cells.
# Inputs:
- `rng::StableRNG`: random number generator from StableRNG package.
- `x::Vector{T}`: list of cells.
- `y::Int64`: starting index of inh cells.
- `pop_sizes::Vector{Any}`: array of clustered connections sizes.
- `conn_probs::Array{Float64,1}`: probability of clustered connections.
- `μ::Array{Float64,1}`: means of synaptic weight distribution (LogNormal).
- `σ::Array{Float64,1}`: standard deviations of synaptic weight distribution (LogNormal).
"""
function get_clusters_conns(rng::StableRNG,x::Vector{T}, pop_sizes::Vector{Any}, conn_prob::Float64, μ::Float64, std::Float64) where {T}
n = length(pop_sizes) # total number of clusters
p = pop_sizes .* pop_sizes # total number of connections per cluster
ids = Int.(ceil.(p .* conn_prob))
s = [zeros.(Int,conns) for conns in ids]
xout = Vector{T}(undef,0)
yout = Vector{T}(undef,0)
zout = Vector{Float64}(undef,0)
idx = CartesianIndices((length(x), length(x))) # all indices
pope_start = x[1]
pope_end = 0
csid = []
for pop_i = 1:n
pope_start = pope_end+1 # separate clusters
pope_end += pop_sizes[pop_i]
push!(csid, pope_start:pope_end)
StatsBase.knuths_sample!(rng,1:p[pop_i],s[pop_i])
for i = 1:ids[pop_i] #exc->exc
push!(xout, x[ idx[pope_start:pope_end,pope_start:pope_end][s[pop_i]][i][1] ])
push!(yout, x[ idx[pope_start:pope_end,pope_start:pope_end][s[pop_i]][i][2] ])
weight = abs(rand(rng,Normal(μ,std)))
push!(zout, weight)
end
end
return xout, yout, zout, csid
end
"""
vspans(timestamps::Vector{Tuple{Float64, Float64}},pattern::Vector{T}) where {T}
Plots vertical spans of input patterns on current plot.
# Inputs:
- `timestamps::Vector{T}`: array of start/finish timestamps.
- `pattern::Vector{T}`: array of pattern id and startime.
"""
function vspans(h::Plots.Plot{Plots.GRBackend}, timestamps::Vector{Tuple{Float64, Float64}}, pattern::Vector{T}, lims::Tuple{Float64, Float64},alpha::Float64=.05) where {T}
patcl = palette(:default)
patcl = patcl[1:maximum(pattern)[1]]
tstart = lims[1]
tend = lims[2]
for (id, (t0, t1)) in enumerate(timestamps)
(pat,_) = pattern[id]
if pat > 0 && t0 > tstart && t1 < tend
cl = patcl[pat]
vspan!([t0,t1],fillalpha=alpha,color=cl,alpha=0.0,label=nothing,xlim=lims)
end
end
plot!()
end
"""
vspans(timestamps::Vector{Tuple{Float64, Float64}},pattern::Vector{T}) where {T}
Plots vertical spans of input patterns on h subplots.
# Inputs:
- `h::Plots.Plot{Plots.GRBackend}`: Plots figure.
- `timestamps::Vector{T}`: array of start/finish timestamps.
- `pattern::Vector{T}`: array of pattern id and startime.
"""
function vspans(h::Plots.Plot{Plots.GRBackend},whichones::UnitRange{Int64},timestamps::Vector{Tuple{Float64, Float64}}, pattern::Vector{T}, lims::Tuple{Float64, Float64},alpha::Float64=.05) where {T}
patcl = palette(:default)
patcl = patcl[1:maximum(pattern)[1]]
subplots=length(h.subplots)
tstart = lims[1]
tend = lims[2]
for (id, (t0, t1)) in enumerate(timestamps)
(pat,_) = pattern[id]
if pat > 0 && t0 > tstart && t1 < tend
cl = patcl[pat]
for i in whichones
vspan!(h[i],[t0,t1],fillalpha=alpha,color=cl,alpha=0.0,label=nothing,xlim=lims)
end
end
end
end
"""
vspans_states(h::Plots.Plot{Plots.GRBackend}, timestamps::Vector{Tuple{Float64, Float64, Symbol}}, lims::Vector{Float64},alpha::Float64=.05)
Plots vertical spans of state patterns on h subplots.
# Inputs:
- `h::Plots.Plot{Plots.GRBackend}`: Plots figure.
- `timestamps::Vector{T}`: array of start/finish timestamps.
- `lims::Vector{Any}`: vector of xlims and ylims concatenated.
- `alpha::Float64`: transparency.
"""
function vspans_states(h::Plots.Plot{Plots.GRBackend},whichones::UnitRange{Int64},timestamps::Vector{Tuple{Float64, Float64, Symbol}}, lims::Vector{Float64}, alpha::Float64=.05)
patcl = palette(:lightrainbow)
states = unique([state for (_,_,state) in timestamps])
patcl = patcl[1:length(states)]
subplots=length(h.subplots)
tstart = lims[1]
tend = lims[2]
ystart = lims[3]
yend = lims[4]
cl = patcl[1]
for (t0, t1, symb) in timestamps
if t0 >= tstart && t1 <= tend
for (id,state) in enumerate(states)
if state == symb
cl = patcl[id]
end
end
for i in whichones
bar!(h[i],[(t1+t0)/2],[yend],bar_width=[t1-t0],fillalpha=alpha,color=cl,linealpha=0.0,linewidth=0.0,label="",xlim=lims[1:2])
#vspan!(h[i],[t0,t1],fillalpha=alpha,color=cl,alpha=0.0,label=nothing,xlim=lims)
end
end
end
plot!()
end
"""
vspans_states(h::Plots.Plot{Plots.GRBackend}, timestamps::Vector{Tuple{Float64, Float64, Symbol}}, lims::Vector{Float64},alpha::Float64=.05)
Plots vertical spans of state patterns on h subplots.
# Inputs:
- `h::Plots.Plot{Plots.GRBackend}`: Plots figure.
- `timestamps::Vector{T}`: array of start/finish timestamps.
- `lims::Vector{Any}`: vector of xlims and ylims concatenated.
- `alpha::Float64`: transparency.
"""
function vspans_states(h::Plots.Subplot{Plots.GRBackend},whichones::UnitRange{Int64},timestamps::Vector{Tuple{Float64, Float64, Symbol}}, lims::Vector{Float64}, alpha::Float64=.05)
patcl = palette(:lightrainbow)
states = unique([state for (_,_,state) in timestamps])
patcl = patcl[1:length(states)]
tstart = lims[1]
tend = lims[2]
ystart = lims[3]
yend = lims[4]
cl = patcl[1]
for (t0, t1, symb) in timestamps
if t0 >= tstart && t1 <= tend
for (id,state) in enumerate(states)
if state == symb
cl = patcl[id]
end
end
for i in whichones
bar!(h[i],[(t1+t0)/2],[yend],bar_width=[t1-t0],fillalpha=alpha,color=cl,linealpha=0.0,linewidth=0.0,label="",xlim=lims[1:2])
#vspan!(h,[t0,t1],fillalpha=alpha,color=cl,alpha=0.0,label=nothing,xlim=lims)
end
end
end
plot!()
end