% Jon Newman and Ming-fai Fong
% Testing the performance of the optical feedback LED driver circuit for
% injecting OU processes

% First case: Current controlled LED
d = load('2012-04-16_LEDtest_currFeedback.mat');

% histogram parameters
bins = -5:0.25:5; % number of bins
bins1 = -5:0.1:5;

% How many trials
trials = unique(d.trial);

% raw data storage
VV = zeros(length(trials),length(d.trial)/length(trials));
II = zeros(length(trials),length(d.trial)/length(trials));
PP = zeros(length(trials),length(d.trial)/length(trials));

% Parse raw data
for i = 1:length(trials)
    VV(i,:) = d.V_ctrl(d.trial == i);
    II(i,:) = d.I_LED(d.trial == i);
    PP(i,:) = d.V_pd(d.trial == i);
end

% Normalize

VV = (VV - mean(mean(VV')))/mean(std(VV'));
II = (II - mean(mean(II')))/mean(std(II'));
PP = (PP - mean(mean(PP')))/mean(std(PP'));

% histograms
[vh vb] = hist(VV',bins); vh = vh/length(VV);
[ih ib] = hist(II',bins); ih = ih/length(VV);
[ph pb] = hist(PP',bins); ph = ph/length(VV);

% Gaussian fit
fv = fit(vb,mean(vh')','gauss1');
ev = fv(bins1);
fi = fit(ib,mean(ih')','gauss1');
ei = fi(bins1);
fp = fit(pb,mean(ph')','gauss1');
ep = fp(bins1);

% Plot Hisgrams
close all 
figure

subplot(211)
hold on
plot(vb,smooth(vh(:,1),3),'ro')
plot(bins1,ev,'r--','LineWidth',2)
% plot(ib,ih,'ro')
% plot(bins1,ei,'r-')
plot(pb,smooth(ph(:,1),3),'bo')
plot(bins1,ep,'b-')
axis([-3 3 0 0.14]);

%% First case: Optically controlled LED
d = load('2012-04-16_LEDtest_optoFeedback.mat');

% How many trials
trials = unique(d.trial);

% raw data storage
VV = zeros(length(trials),length(d.trial)/length(trials));
II = zeros(length(trials),length(d.trial)/length(trials));
PP = zeros(length(trials),length(d.trial)/length(trials));

% Parse raw data
for i = 1:length(trials)
    VV(i,:) = d.V_ctrl(d.trial == i);
    II(i,:) = d.I_LED(d.trial == i);
    PP(i,:) = d.V_pd(d.trial == i);
end

% Normalize
VV = (VV - mean(mean(VV')))/mean(std(VV'));
II = (II - mean(mean(II')))/mean(std(II'));
PP = (PP - mean(mean(PP')))/mean(std(PP'));

% histograms
[vh vb] = hist(VV',bins); vh = vh/length(VV);
[ih ib] = hist(II',bins); ih = ih/length(VV);
[ph pb] = hist(PP',bins); ph = ph/length(VV);

% Gaussian fit
fv = fit(vb,mean(vh')','gauss1');
ev = fv(bins1);
fi = fit(ib,mean(ih')','gauss1');
ei = fi(bins1);
fp = fit(pb,mean(ph')','gauss1');
ep = fp(bins1);

% Plot Hisgrams

subplot(212)
hold on
plot(vb,smooth(vh(:,1),3),'ro')
plot(bins1,ev,'r--','LineWidth',2)
% plot(ib,ih,'ro')
% plot(bins1,ei,'r-')
plot(pb,smooth(ph(:,1),3),'bo')
plot(bins1,ep,'b-')
axis([-3 3 0 0.14]);



