% Jon Newman
% Turn OU process into analog stimulation waveform for ChR2 excitation

%% Exp. Parameters
% We will make dt 1 millisecond so we get ff = 1000 Hz;

% Overall parameters
mea = 'ollie-363';
DAC_dt = 1/1000; % DAC conversion period (sec)

% pre-stimulation time
voff = -0.5; % LED off voltage signal
start_time = 300; % sec

% OU characteristics
num_real = 2; % number of OU realizations
num_rep = 50; % number of repeats per OU realization
t_rep = 10; % time of one OU realization repitition
tauI = 50e-3; % correlation time of the OU realizations
u_noise  = 2.5; % Mean control voltage in the center of the input range
s_noise = 0.625; % STD control voltage

% Create file name
fid = [ datestr(now,29) '_' mea '_OU-stim_tau'  num2str(tauI) 'sec-u-' num2str(u_noise) '-s-' num2str(s_noise) '_num-real-' num2str(num_real) '_00'];

%% Derive OU snippet
% storage
T = [0 start_time];
C = [0 0];
A = [voff voff];

Td = [0];
Sd = [0];


for j = 1:num_real
    
    % Derive OU snippet
    N=ceil(t_rep / DAC_dt); % number of noise points
    rset=randn(N, 1);
    t_noise = (0:DAC_dt:t_rep-DAC_dt);
    e_noise=zeros(1,N);
    
    % make unit std deviation noise
    A_e = exp(-DAC_dt/tauI);
    sigma=1; % std of the noise
    for s = 1:(N-1)
        e_noise(s+1) = e_noise(s)*A_e + sigma*sqrt(1-A_e^2)*rset(s);
    end
    % scale and shift
    e_noise = s_noise*e_noise + u_noise;
    
    % Make repeated OU
    for i = 1:num_rep
        
        T = [T T(end) + t_noise];
        A = [A e_noise];
        C = [C zeros(1,length(e_noise))];
        
        b_trig_on = dec2bin(1,32);
        b_trig_off = dec2bin(9,32);
        
        % Trigger a new stimulation cycle on bit 0
        Td = [Td T(end) + t_noise(1)];
        Sd = [Sd j];
        Td = [Td T(end) + t_noise(1) + 0.001];
        Sd = [Sd 0];
    end
    
    A(end) = voff;
    
end


%% Plot
close all
figure
subplot(211)
plot(T,A)
xlabel('time (sec)')
ylabel('V_{CTL} (volts)')
subplot(212)
stairs(Td,Sd)
xlabel('time (sec)')
ylabel('Digital port state (uint32)')

%% Make the NeuroRighter open loop stimulation files

makedigfile(fid,Td',Sd');
makeauxfile(fid,T',C',A');





