%----------------------------------------------------------------------
% Physiology 317 - Methods in Computational Neurobiology 
%
% hw4p2.m - Homework #4, Problem #2
%
% Implement synaptic conductances in integrate & fire neuron
%
% M. Nelson, 2004
%----------------------------------------------------------------------

clear;					
figure(1); clf;					
orient portrait

set(gcf,'color','w')			    % set white background
set(gcf,'DefaultTextFontSize',9);	% set default font size


TAU_SYN =  10;	%ms		            % synaptic time constant 
STIM_INTERVAL = 30; %ms

GPEAK = .01;                        % peak synaptic conductance (uS)
GNORM = GPEAK ./(TAU_SYN*exp(-1));  % normalization constant

C = 1; % nF
R = 10; % MOhm
VSPK = 70; % mV
VTHR = 5;  % mV
EEX = +70; % mV

TMAX = 500;                             % set up time vector (msec)
DT = 1;                                 % integration time step (msec)
t=(DT:DT:TMAX)';

u = zeros(length(t),1);
u(STIM_INTERVAL:STIM_INTERVAL:end) = (1/DT);

z = zeros(length(t),1);
g = zeros(length(t),1);
v = zeros(length(t),1);
Isyn = zeros(length(t),1);

for i=2:length(t)
    
    % update synapses
    z(i) = z(i-1) + (-z(i-1)/TAU_SYN + GNORM*u(i))*DT;
    g(i) = g(i-1) + (-g(i-1)/TAU_SYN + z(i-1))*DT;
    
    % update current
    Isyn(i) = g(i-1)*(v(i-1)-EEX);
    
    % update membrane voltage
    if(v(i-1) == VSPK)                  
        v(i) = 0; 
    else                           
        dvdt = (-v(i-1)/R  - Isyn(i-1))/C; 
        v(i) = v(i-1) + dvdt*DT; 
    end
    
    if(v(i) >= VTHR)			
        v(i) = VSPK;
    end
    
end


% plot v, g, and input with approprate scaling factors and offsets
subplot(4,1,1)
plot(t,v,'k');hold on;
plot([0 TMAX],[VTHR VTHR],'r--');
ylabel('V_m');
axis([0 TMAX 0 20])
title('Homework 4 Problem 2');

subplot(4,1,2)
plot(t,Isyn,'b')
ylabel('I_{syn}');

subplot(4,1,3)
plot(t,g,'g')
ylabel('g_{syn}');

subplot(4,1,4)
plot(t,u,'m');
ylabel('u');
axis([0 TMAX -0.5 1.5]);
xlabel('time (msec)')