% This file is licensed under the Allen Institute Terms of Use, which can be found at:
%http://www.alleninstitute.org/Media/policies/terms_of_use_content.html

%------------------------------------------------------------------------------------

%Script to generate data for Fig. S10. This script convolves the first 1222 
%randomly generated synaptic weight distributions q(w) with a Poisson process 
%to generate the tail weight numbers Qn. Please refer to eqns. (6) and (7)
%in the paper for definition of tail-weight numbers. The Poisson process
%is truncated at k = kmax. This script generates the first 50 tail weight 
%numbers for these 1222 randomly generated synaptic weight distributions.

%NOTE: The .mat file FigS10_randdist.mat consisting of the original
%distributions used for FigS10 has also been made available and can be 
%used to reproduce the figure exactly. 

clear variables;

load FigS10_randdist.mat; %using randdist3.m to generate distributions

th=20*10^-3;%V Threshold
lk=1/(20*10^-3);%s^-1 leak constant 1/RC

dv=0.2*10^-3;%V defines max step in potential
v0=(0:dv:th);%V defines the grid for the membrane potential

%initial probability distribution; start at rest
p0=zeros(size(v0));
p0(1)=1;      

th1 = 102; %threshold index

%Initialize for storing
qdw_dist_fin = {};
qdw_dist_fin_probs=[];

tic
for jj=1:length(dist(1,1:1222))
    wts_dist= x*0.02;
    qwts_dist=dist(:,jj);
    qdw_dist= [wts_dist; ones(size(wts_dist));qwts_dist'];
    qdw_dist_fin{jj} = [0 qdw_dist(1,:); 1 qdw_dist(2,:); 0 qdw_dist(3,:)];
    qdw_dist_fin_probs = [qdw_dist_fin_probs;qdw_dist_fin{jj}(3,:)];  
end;

%convolve distribution probabilities with poisson process
kmax = 10;    
lambda = 1;

qdw_dist_fin_probs_prime=zeros(1,100*kmax+1);
qdw_dist_fin_probs_temp=[];

for ll = 1:length(dist(1:1222))
    qdw_dist_fin_probs_prime(ll,:) = exp(-1)*[qdw_dist_fin_probs(ll,:) zeros(1,100*(kmax-1))];
    qdw_dist_fin_probs_temp = qdw_dist_fin_probs(ll,:);
    for k = 2:10
        qdw_dist_fin_probs_temp = conv(qdw_dist_fin_probs_temp,qdw_dist_fin_probs(ll,:));
        qdw_dist_fin_probs_padded = [qdw_dist_fin_probs_temp zeros(1,100*(kmax-k))];
        qdw_dist_fin_probs_prime(ll,:) = qdw_dist_fin_probs_prime(ll,:)+((lambda)^k*exp(-lambda)/factorial(k))*qdw_dist_fin_probs_padded;
    end
    qdw_dist_fin_probs_prime(ll,1)=exp(-1);
end


%Generate tail weight numbers
for kk = 1:length(dist(1,1:1222))
    c_dist = conv(p0,qdw_dist_fin_probs_prime(kk,:));
    r_dist(kk,1) = sum(c_dist(th1:end));
    for i = 2:50;
        c_dist = conv(c_dist,qdw_dist_fin_probs_prime(kk,:));
        r_dist(kk,i) = sum(c_dist(th1:end));
    end
end

toc

save('FigS10_randdist_Poisson_conv.mat','r_dist');



