% 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

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

function u_mat=generate_u_transition(u,frac)
%Function to generate the transition matrix to act on p(u,t) for a  
%change in the utility vector upon synaptic depression after a spike. 
%This function takes as input an initial vector (u) for the utility and the
%fraction (frac) of synaptic utility available after a spike. Its
%implementation is exactly analogous to that for synaptic transition matrix, generated
%using the voltage vectors, that acts on p(v,t)

nu=length(u);
u_mat=sparse(eye(nu,nu));
u=[u 2*u(end)-u(end-1)];
uleft=u;
uright=[u(2:end) u(end)+1];
dus=uright-uleft;
qprob=1;
f_prob=1;

new_us=u*frac;

for binno=1:length(new_us)-1
    leftedge=new_us(binno);
    rightedge=new_us(binno+1);
    newbinwidth=rightedge-leftedge;
    withinbins=find(uleft<=leftedge & uright>=rightedge);   %shifted bin falls entirely within an existing bin
    fullbins=find(uleft>=leftedge & uright<=rightedge);     %shifted bin entirely encompasses an existing bin
    fullbins=setdiff(fullbins,withinbins);
    leftoverhang=find(uleft<leftedge & uright>leftedge & uright<rightedge);
    rightoverhang=find(uleft<rightedge & uright>rightedge & uleft>leftedge);
    if ~isempty(withinbins) u_mat(binno,withinbins)=u_mat(binno,withinbins)+qprob*f_prob; end;
    if ~isempty(fullbins) u_mat(binno,fullbins)=u_mat(binno,fullbins)+qprob*f_prob*dus(fullbins)/newbinwidth; end;
    if ~isempty(leftoverhang) u_mat(binno,leftoverhang)=u_mat(binno,leftoverhang)+qprob*f_prob*(uright(leftoverhang)-leftedge)/newbinwidth; end;
    if ~isempty(rightoverhang) u_mat(binno,rightoverhang)=u_mat(binno,rightoverhang)+qprob*f_prob*(rightedge-uleft(rightoverhang))/newbinwidth; end;
    u_mat(binno,binno)=u_mat(binno,binno)-qprob*f_prob;
end;    

