[dataDir,mEPSCDir,explicitStimulusDir,psthDir,placeCellDataDir] = ...
nSTATRootDir = fileparts(dataDir);
if exist(nSTATRootDir,'dir') == 7 && ~strcmp(pwd,nSTATRootDir)
Direction=3; Neuron=1; Stim=2;
datapath = fullfile(explicitStimulusDir,['Dir' num2str(Direction)], ...
['Neuron' num2str(Neuron)],['Stim' num2str(Stim)]);
data = load(fullfile(datapath,'trngdataBis.mat'));
time=0:.001:(length(data.t)-1)*.001;
spikeTimes = time(data.y==1);
stim = Covariate(time,stimData./10,'Stimulus','time','s','mm',{'stim'});
baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
nst = nspikeTrain(spikeTimes);
nspikeColl = nstColl(nst);
cc = CovColl({stim,baseline});
trial = Trial(nspikeColl,cc);
scrsz = get(0,'ScreenSize');
h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
nst2 = nspikeTrain(spikeTimes);
nst2.setMaxTime(21);nst2.plot;
set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title({'Neural Raster'},'FontWeight','bold','FontSize',16,'FontName','Arial');
'XTick' , 0:1:max(time), ...
stim.getSigInTimeWindow(0,21).plot([],{{' ''k'' '}}); legend off;
set(gca,'ytick',[0 0.5 1]);
hy=ylabel('Displacement [mm]','Interpreter','none'); xlabel('');
set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title({'Stimulus - Whisker Displacement'},'FontWeight','bold',...
'FontSize',16,'FontName','Arial');
'XTick' , 0:1:max(time), ...
stim.derivative.getSigInTimeWindow(0,21).plot([],{{' ''k'' '}}); legend off;
set(gca,'ytick',[-80 0 80]);
hy=ylabel('Displacement Velocity [mm/s]','Interpreter','none');
hx= xlabel('time [s]','Interpreter','none');
set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title({'Displacement Velocity'},'FontWeight','bold',...
'FontSize',16,'FontName','Arial');
'XTick' , 0:1:max(time), ...
maxWindow=1; numWindows=32;
windowTimes =unique(round([0 logspace(log10(delta),...
log10(maxWindow),numWindows)]*sampleRate)./sampleRate);
results =Analysis.computeHistLagForAll(trial2,windowTimes,...
{{'Baseline','\mu'},{'Stimulus','stim'}},'BNLRCG',0,sampleRate,0);
Analyzing Configuration #1: Neuron #1
+Analyzing Configuration #2: Neuron #1
+Analyzing Configuration #3: Neuron #1
+Analyzing Configuration #4: Neuron #1
+Analyzing Configuration #5: Neuron #1
+Analyzing Configuration #6: Neuron #1
+Analyzing Configuration #7: Neuron #1
+Analyzing Configuration #8: Neuron #1
+Analyzing Configuration #9: Neuron #1
+Analyzing Configuration #10: Neuron #1
+Analyzing Configuration #11: Neuron #1
+Analyzing Configuration #12: Neuron #1
+Analyzing Configuration #13: Neuron #1
+Analyzing Configuration #14: Neuron #1
+Analyzing Configuration #15: Neuron #1
+Analyzing Configuration #16: Neuron #1
+Analyzing Configuration #17: Neuron #1
+Analyzing Configuration #18: Neuron #1
+Analyzing Configuration #19: Neuron #1
+Analyzing Configuration #20: Neuron #1
+Analyzing Configuration #21: Neuron #1
+Analyzing Configuration #22: Neuron #1
+Analyzing Configuration #23: Neuron #1
+Analyzing Configuration #24: Neuron #1
+Analyzing Configuration #25: Neuron #1
+Analyzing Configuration #26: Neuron #1
+Analyzing Configuration #27: Neuron #1
+Analyzing Configuration #28: Neuron #1
+Analyzing Configuration #29: Neuron #1
+Analyzing Configuration #30: Neuron #1
KSind = find(results{1}.KSStats.ks_stat == min(results{1}.KSStats.ks_stat));
AICind = find((results{1}.AIC(2:end)-results{1}.AIC(1))== ...
min(results{1}.AIC(2:end)-results{1}.AIC(1))) +1;
BICind = find((results{1}.BIC(2:end)-results{1}.BIC(1))== ...
min(results{1}.BIC(2:end)-results{1}.BIC(1))) +1;
BICind=inf; %sometime BIC is non-decreasing and the index would be 1
windowIndex = min([AICind,BICind]) %use the minimum order model
Summary = FitResSummary(results);
selfHist = windowTimes(1:windowIndex+1);
NeighborHist = []; sampleRate = 1000;
x=0:length(windowTimes)-1;
plot(x,results{1}.KSStats.ks_stat,'.-'); axis tight; hold on;
plot(x(windowIndex),results{1}.KSStats.ks_stat(windowIndex),'r*');
set(gca,'XTick', 0:5:results{1}.numResults-1,'XTickLabel',[],...
'TickLength', [.02 .02] , ...
'XMinorTick', 'on','LineWidth' , 1);
hy=ylabel('KS Statistic');
set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
dAIC = results{1}.AIC-results{1}.AIC(1);
title({'Model Selection via change'; 'in KS Statistic, AIC, and BIC'},...
subplot(7,2,4); plot(x,dAIC,'.-');
set(gca,'XTick', 0:5:results{1}.numResults-1,'XTickLabel',[],...
'TickLength', [.02 .02] , ...
'XMinorTick', 'on','LineWidth' , 1);
hy=ylabel('\Delta AIC');axis tight; hold on;
set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
plot(x(windowIndex),dAIC(windowIndex),'r*');
dBIC = results{1}.BIC-results{1}.BIC(1);
subplot(7,2,6); plot(x,dBIC,'.-');
hy=ylabel('\Delta BIC'); axis tight; hold on;
plot(x(windowIndex),dBIC(windowIndex),'r*');
hx=xlabel('# History Windows, Q');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
'TickLength' , [.02 .02] , ...
'XMinorTick' , 'on' , ...
'XTick' , 0:5:results{1}.numResults-1, ...
% Compare Baseline, Baseline+Stimulus Model, Baseline+History+Stimulus
% Addition of the history effect yields a model that falls within the 95%
c{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[],NeighborHist);
c{1}.setName('Baseline');
c{2} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},...
c{2}.setName('Baseline+Stimulus');
c{3} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},...
sampleRate,windowTimes(1:windowIndex),[]);
c{3}.setName('Baseline+Stimulus+Hist');
results = Analysis.RunAnalysisForAllNeurons(trial2,cfgColl,0);
Analyzing Configuration #1: Neuron #1
+Analyzing Configuration #2: Neuron #1
+Analyzing Configuration #3: Neuron #1
results.lambda.setDataLabels({'\lambda_{const}','\lambda_{const+stim}',...
'\lambda_{const+stim+hist}'});
subplot(7,2,[9 11 13]); results.KSPlot;
subplot(7,2,[10 12 14]); results.plotCoeffs; legend off;
% Generate a known Conditional Intensity Function
% We generated a known conditional intensity function (rate function) and
% generate distinct realizations of point processes consistent with this
% rate function. We use the method of thinning to simulate a point process.
[dataDir,mEPSCDir,explicitStimulusDir,psthDir,placeCellDataDir] = ...
tempData = 1*sin(2*pi*f*time)+mu; %lambda >=0
lambdaData = exp(tempData)./(1+exp(tempData))*(1/delta);
lambda = Covariate(time,lambdaData, '\lambda(t)','time','s',...
'spikes/sec',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}});
spikeCollSim = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations);
scrsz = get(0,'ScreenSize');
h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
subplot(2,2,3);spikeCollSim.plot;
set(gca,'YTick',0:5:numRealizations,'YTickLabel',0:5:numRealizations);
title({[num2str(numRealizations) ' Simulated Point Process Sample Paths']},...
'FontWeight','bold','Fontsize',14,'FontName','Arial');
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
subplot(2,2,1);lambda.plot;
title({'Simulated Conditional Intensity Function (CIF)'},...
'FontWeight','bold','FontSize',14,'FontName','Arial');
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
set(hy,'FontName', 'Arial','FontSize',14,'FontWeight','bold');
x = load(fullfile(psthDir,'Results.mat'));
numTrials = x.Results.Data.Spike_times_STC.balanced_SUA.Nr_trials;
spikeTimes{i}=x.Results.Data.Spike_times_STC.balanced_SUA.spike_times{1,i,cellNum};
nst{i} = nspikeTrain(spikeTimes{i});
nst{i}.setName(num2str(cellNum));
spikeCollReal1=nstColl(nst);
spikeCollReal1.setMinTime(0); spikeCollReal1.setMaxTime(2);
subplot(2,2,2);spikeCollReal1.plot; set(gca,'YTick',0:2:numTrials,...
'YTickLabel',0:2:numTrials);
%set(gca,'xtick',[0:.5:2],'xtickLabel',{'0','0.5','1','1.5','2'});
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
title('Response to Moving Visual Stimulus (Neuron 6)',...
'FontWeight','bold','Fontsize',14,'FontName','Arial');
spikeTimes{i}=x.Results.Data.Spike_times_STC.balanced_SUA.spike_times{1,i,cellNum};
nst{i} = nspikeTrain(spikeTimes{i});
nst{i}.setName(num2str(cellNum));
spikeCollReal2=nstColl(nst);
spikeCollReal2.setMinTime(0); spikeCollReal2.setMaxTime(2);
subplot(2,2,4);spikeCollReal2.plot;
set(gca,'YTick',0:2:numTrials,'YTickLabel',0:2:numTrials);
%set(gca,'xtick',[0:.5:2],'xtickLabel',{'0','0.5','1','1.5','2'});
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
title('Response to Moving Visual Stimulus (Neuron 1)','FontWeight',...
'bold','Fontsize',14,'FontName','Arial');
scrsz = get(0,'ScreenSize');
h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
binsize = .05; %50ms window
psth = spikeCollSim.psth(binsize);
psthGLM = spikeCollSim.psthGLM(binsize);
Running in batch mode: neurons with same name are fit simultaneously
+Analyzing Configuration #1: Neuron #1
true = lambda; %rate*delta = expected number of arrivals per bin
h1=true.plot([],{{' ''b'',''Linewidth'',4'}});
h3=psthGLM.plot([],{{' ''k'',''Linewidth'',4'}});
h2=psth.plot([],{{' ''rx'',''Linewidth'',4'}});
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
ylabel('[spikes/sec]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
h_legend=legend([h1(1) h2(1) h3(1)],'true','PSTH','PSTH_{glm}');
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.005 pos(2)+.095 pos(3:4)]);
subplot(2,3,1);spikeCollSim.plot;
set(gca,'YTick',0:2:spikeCollSim.numSpikeTrains,'YTickLabel',0:2:spikeCollSim.numSpikeTrains);
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
binsize = .05; %50ms window
psthReal1 = spikeCollReal1.psth(binsize);
psthGLMReal1 = spikeCollReal1.psthGLM(binsize);%,[],[],[],[],[],1000);
Running in batch mode: neurons with same name are fit simultaneously
+Analyzing Configuration #1: Neuron #6
h3=psthGLMReal1.plot([],{{' ''k'',''Linewidth'',4'}});
h2=psthReal1.plot([],{{' ''rx'',''Linewidth'',4'}});
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('[spikes/sec]','Interpreter','none','FontName', 'Arial','Fontsize',...
h_legend=legend([h2(1) h3(1)],'PSTH','PSTH_{glm}');
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.005 pos(2)+.07 pos(3:4)]);
subplot(2,3,2); spikeCollReal1.plot;
set(gca,'YTick',0:2:spikeCollReal2.numSpikeTrains,'YTickLabel',0:2:spikeCollReal2.numSpikeTrains);
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
psthReal2 = spikeCollReal2.psth(binsize);
psthGLMReal2 = spikeCollReal2.psthGLM(binsize);%,[],[],[],[],[],1000);
Running in batch mode: neurons with same name are fit simultaneously
+Analyzing Configuration #1: Neuron #1
h3=psthGLMReal2.plot([],{{' ''k'',''Linewidth'',4'}});
h2=psthReal2.plot([],{{' ''rx'',''Linewidth'',4'}});
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('[spikes/sec]','Interpreter','none','FontName', 'Arial','Fontsize',...
h_legend=legend([h2(1) h3(1)],'PSTH','PSTH_{glm}');
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.005 pos(2)+.07 pos(3:4)]);
subplot(2,3,3); spikeCollReal2.plot;
set(gca,'YTick',0:2:spikeCollReal2.numSpikeTrains,'YTickLabel',0:2:spikeCollReal2.numSpikeTrains);
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
scrsz = get(0,'ScreenSize');
h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
subplot(3,2,[3 4]); spikeColl.plot;
set(gca,'ytick',0:10:numRealizations,'ytickLabel',0:10:numRealizations);
set(gca,'xtick',0:.1:Tmax,'xtickLabel',0:.1:Tmax); xlabel('');
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial','Fontsize',...
title('Simulated Neural Raster','Interpreter','none','FontName', 'Arial',...
'Fontsize',14,'FontWeight','bold');
% Plot the actual stimulus effect (not including history)
% The CIF including the history effect is stored in the lambda Covariate
stimData = exp(b0 + u'*b1);
if(strcmp(simTypeSelect,'binomial'))
stimData = stimData./(1+stimData);
%Plot the trial dependence
subplot(3,2,1); plot(time,u,'k','LineWidth',3);
% xlabel('time [s]');ylabel('stimulus');
xlabel('time [s]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Stimulus','Interpreter','none','FontName', 'Arial','Fontsize',...
title('Within Trial Stimulus','Interpreter','none','FontName', 'Arial',...
'Fontsize',14,'FontWeight','bold');
subplot(3,2,2); plot(1:length(b1),b1,'k','LineWidth',3);
xlabel('Trial [k]','Interpreter','none','FontName', 'Arial','Fontsize',...
ylabel('Stimulus Gain','Interpreter','none','FontName', 'Arial','Fontsize',...
title('Across Trial Stimulus Gain','Interpreter','none','FontName',...
'Arial','Fontsize',14,'FontWeight','bold');
imagesc(stimData'./delta); set(gca, 'YDir','normal');
set(gca,'xtick',0:100:Tmax/delta,'xtickLabel',0:.1:Tmax);
set(gca,'ytick',0:10:numRealizations,'ytickLabel',0:10:numRealizations);
xlabel('time [s]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
'Fontsize',12,'FontWeight','bold');
title('True Conditional Intensity Function','Interpreter',...
'none','FontName', 'Arial','Fontsize',14,'FontWeight','bold');
% Generate the actual stimulus effect
minTime=0; maxTime = Tmax;
if(strcmp(fitType,'poisson'))
actStimEffect=exp(stimData + b0)./delta;
elseif(strcmp(fitType,'binomial'))
actStimEffect=exp(stimData + b0)./(1+exp(stimData + b0))./delta;
% Generate the basis function so that the estimated effect can be plotted
% at the same temporal resolution as the theoretical effect
basisWidth = (maxTime-minTime)/numBasis;
unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,...
basisMat = unitPulseBasis.data;
% Generate the estimated stimulus effect
if(strcmp(fitType,'poisson'))
estStimEffect=exp(basisMat*xK)./delta;
elseif(strcmp(fitType,'binomial'))
estStimEffect=exp(basisMat*xK)./(1+exp(basisMat*xK))./delta;
scrsz = get(0,'ScreenSize');
h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.4 scrsz(4)*.8]);
% Plot the actual and estimated stimulus effect as a function of trial and
surf((1:length(b1))',stim.time,actStimEffect,'FaceAlpha',0.1,...
'EdgeAlpha',0.1,'AlphaData',0.1);
hx=xlabel('Trial [k]'); hy=ylabel('time [s]');
hz=zlabel('Stimulus Effect [spikes/sec]'); hold all;
set([hx hy hz],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
surf((1:length(b1))',stim.time,estStimEffect(:,1:length(b1)),...
'FaceAlpha',0.5,'EdgeAlpha',0.1,'AlphaData',0.5); %xlabel('Trial [k]'); ylabel('time [s]'); zlabel('Stimulus Effect');
set(gca,'YDir','reverse');
set(gca,'ytick',0:.1:Tmax,'ytickLabel',0:.1:Tmax);
title('SSGLM Estimated vs. Actual Stimulus Effect','FontWeight','bold',...
h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.4 scrsz(4)*.8]);
% The actual stimulus effect
mesh((1:length(b1))',stim.time,actStimEffect);
hx=xlabel('Trial [k]'); hy=ylabel('time [s]');
zlabel('Stimulus Effect [spikes/sec]'); hold all;
set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
% title('True Stimulus Effect');
title('True Stimulus Effect','FontWeight','bold',...
set(gca,'xtick',[],'xtickLabel',[]);
set(gca,'ytick',[],'ytickLabel',[]);
CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
mesh((1:length(b1))',stim.time,repmat(psthSig.data, [1 numRealizations]));
hx=xlabel('Trial [k]'); hy=ylabel('time [s]');
hz=zlabel('Stimulus Effect [spikes/sec]'); hold all;
set([hx hy hz],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
% title('PSTH Estimated Stimulus Effect');
title('PSTH Estimated Stimulus Effect','FontWeight','bold',...
set(gca,'xtick',[],'xtickLabel',[]);
set(gca,'ytick',[],'ytickLabel',[]);
CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
% The SSGLM estimated stimulus effect
mesh((1:length(b1))',stim.time,estStimEffect);
xlabel('Trial [k]'); ylabel('time [s]');
zlabel('Stimulus Effect [spikes/sec]'); hold all;
hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); hz=get(gca,'ZLabel');
set([hx hy hz],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
% title('SSGLM Estimated Stimulus Efferct');
title('SSGLM Estimated Stimulus Effect','FontWeight','bold',...
set(gca,'xtick',[],'xtickLabel',[]);
set(gca,'ytick',[],'ytickLabel',[]);
set(gca, 'YDir','normal')
minTime=0; maxTime = Tmax;
% Generate the basis function so that the estimated effect can be plotted
% at the same temporal resolution as the theoretical effect
basisWidth = (maxTime-minTime)/numBasis;
unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,...
minTime,maxTime,sampleRate);
basisMat = unitPulseBasis.data;
[spikeRateBinom, ProbMat,sigMat]=DecodingAlgorithms.computeSpikeRateCIs(xK,...
WkuFinal,dN,t0,tf,fitType,delta,gammahat,windowTimes);
lt=find(sigMat(1,:)==1,1,'first');
display(['The learning trial (compared to the first trial) is trial #' ...
num2str(find(sigMat(1,:)==1,1,'first'))]);
The learning trial (compared to the first trial) is trial #6
scrsz = get(0,'ScreenSize');
h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
spikeRateBinom.setName(['(' num2str(Tmax) '-0)^-1*\Lambda(0,' ...
spikeRateBinom.plot([],{{' ''k'',''Linewidth'',4'}});
plot(lt*[1;1],v(3:4),'r','Linewidth',2);
hx=xlabel('Trial [k]','Interpreter','none'); hold all;
hy=ylabel('Average Firing Rate [spikes/sec]','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title(['Learning Trial:' num2str(lt)],'FontWeight','bold',...
h=subplot(2,3,[2 3 5 6]);
imagesc(ProbMat); hold on;
plot3(m,k,1,'r*'); hold on;
set(h,'XAxisLocation','top','YAxisLocation','right');
hx=xlabel('Trial Number','Interpreter','none'); hold all;
hy=ylabel('Trial Number','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
stim1 = Covariate(time, basisMat*stimulus(:,1),'Trial1','time','s',...
temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,1,:)));
stim1.setConfInterval(temp);
stimlt = Covariate(time, basisMat*stimulus(:,lt),'Trial1','time','s',...
temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt,:)));
stimlt.setConfInterval(temp);
stimltm1 = Covariate(time, basisMat*stimulus(:,lt-1),'Trial1','time','s',...
temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt-1,:)));
stimltm1.setConfInterval(temp);
h1=stim1.plot([],{{' ''k'',''Linewidth'',4'}}); hold all;
h2=stimlt.plot([],{{' ''r'',''Linewidth'',4'}});
hx=xlabel('time [s]','Interpreter','none'); hold all;
hy=ylabel('Firing Rate [spikes/sec]','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title({'Learning Trial Vs. Baseline Trial';'with 95% CIs'},'FontWeight','bold',...
h_legend=legend([h1(1) h2(1)],'\lambda_{1}(t)',['\lambda_{' num2str(lt) '}(t)']);
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.03 pos(2)+.01 pos(3:4)]);
clear x y neuron time nst tc tcc z;
load(fullfile(placeCellDataDir,['PlaceCellDataAnimal' num2str(n) '.mat']));
% Create the spikeTrains for each cell
nst{i} = nspikeTrain(neuron{i}.spikeTimes);
% Convert to polar coordinates
[theta,r] = cart2pol(x,y);
% Evaluate the Zernike Polynomials
% Number of polynomials from "An Analysis of Hippocampal
% Spatio-Temporal Representations Using a Bayesian Algorithm for Neural
% Spike Train Decoding" Barbieri et. al 2005
if(~any(mod(l-m,2))) % otherwise the polynomial = 0
z(:,cnt) = zernfun(l,m,r,theta,'norm');
% zernfun by Paul Fricker
% http://www.mathworks.com/matlabcentral/fileexchange/7687
% Data sampled at 30 Hz but just to be sure
sampleRate = round(1/delta);
% Define Covariates for the analysis
baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',...
zernike = Covariate(time,z,'Zernike','time','s','m',{'z1','z2','z3',...
'z4','z5','z6','z7','z8','z9','z10'});
gaussian = Covariate(time,[x y x.^2 y.^2 x.*y],'Gaussian','time',...
's','m',{'x','y','x^2','y^2','x*y'});
covarColl = CovColl({baseline,gaussian,zernike});
% Create the trial structure
spikeColl = nstColl(nst);
trial = Trial(spikeColl,covarColl);
% Define how we want to analyze the data
tc{1} = TrialConfig({{'Baseline','mu'},{'Gaussian',...
'x','y','x^2','y^2','x*y'}},sampleRate,[]);
tc{1}.setName('Gaussian');
tc{2} = TrialConfig({{'Zernike' 'z1','z2','z3','z4','z5','z6',...
'z7','z8','z9','z10'}},sampleRate,[]);
tc{2}.setName('Zernike');
% Perform Analysis (Commented to since data already saved)
results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
resStruct =FitResult.CellArrayToStructure(results);
filename = fullfile(dataDir,['PlaceCellAnimal' num2str(n) 'Results']);
save(filename,'resStruct');
[x_new,y_new]=meshgrid(-1:.01:1); %define new x and y
y_new = flipud(y_new); x_new = fliplr(x_new);
[theta_new,r_new] = cart2pol(x_new,y_new);
%Data for the gaussian fit
newData{1} =ones(size(x_new));
newData{2} =x_new; newData{3} =y_new;
newData{4} =x_new.^2; newData{5} =y_new.^2;
newData{6} =x_new.*y_new;
% Zernike polynomials only defined on the unit disk
temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
clear lambdaGaussian lambdaZernike;
load(fullfile(placeCellDataDir,['PlaceCellDataAnimal' num2str(n) '.mat']));
resData = load(fullfile(dataDir,['PlaceCellAnimal' num2str(n) 'Results.mat']));
results = FitResult.fromStructure(resData.resStruct);
% Evaluate our fits using the new data and the estimated parameters
lambdaGaussian{i} = results{i}.evalLambda(1,newData);
lambdaZernike{i} = results{i}.evalLambda(2,zpoly);
% Plot the receptive fields
% 3d plot of an example place field
% 2d plot of all the cell's fields
tb=annotation(h4,'textbox',...
[0.283261904761904 0.928571428571418 ...
0.392857142857143 0.0595238095238095],...
'String',{['Gaussian Place Fields - Animal#' ...
num2str(n)]},'FitBoxToText','on','Fontsize',11,...
'FontName','Arial','FontWeight','bold','LineStyle',...
'none','HorizontalAlignment','center'); hold on;
annotation(h6,'textbox',...
[0.283261904761904 0.928571428571418 ...
0.392857142857143 0.0595238095238095],...
'String',{['Gaussian Place Fields - Animal#' ...
num2str(n)]},'FitBoxToText','on','Fontsize',11,...
'FontName','Arial','FontWeight','bold','LineStyle',...
'none','HorizontalAlignment','center'); hold on;
pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
axis square; set(gca,'xtick',[],'ytick',[]);
annotation(h5,'textbox',...
[0.303261904761904 0.928571428571418 ...
0.392857142857143 0.0595238095238095],...
'String',{['Zernike Place Fields - Animal#' ...
num2str(n)]},'FitBoxToText','on','Fontsize',11,...
'FontName','Arial','FontWeight','bold','LineStyle','none'); hold on;
annotation(h7,'textbox',...
[0.303261904761904 0.928571428571418 ...
0.392857142857143 0.0595238095238095],...
'String',{['Zernike Place Fields - Animal#' ...
num2str(n)]},'FitBoxToText','on','Fontsize',11,...
'FontName','Arial','FontWeight','bold','LineStyle',...
'none','HorizontalAlignment','center'); hold on;
pcolor(x_new,y_new,lambdaZernike{i}), shading interp
set(gca,'xtick',[],'ytick',[]);
[dataDir,mEPSCDir,explicitStimulusDir,psthDir,placeCellDataDir] = ...
f=2; b1=randn(numRealizations,1);b0=log(10*delta)+randn(numRealizations,1);
expData = exp(b1(i)*x+b0(i));
lambdaData = expData./(1+expData);
lambda = Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
{{' ''b'', ''LineWidth'' ,2'}});
tempLambda = Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
{{' ''b'', ''LineWidth'' ,2'}});
lambda = lambda.merge(tempLambda);
spikeColl = CIF.simulateCIFByThinningFromLambda(...
lambda.getSubSignal(i),1);
nst{i} = spikeColl.getNST(1);
spikeColl = nstColl(nst);scrsz = get(0,'ScreenSize');
h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 ...
scrsz(3)*.6 scrsz(4)*.8]);
subplot(3,1,1); plot(time,x,'k');
set(gca,'xtick',[],'xtickLabel',[]); ylabel('Stimulus');
hx=get(gca,'XLabel'); hy=get(gca,'YLabel');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title('Driving Stimulus','FontWeight','bold',...
'FontSize',14,'FontName','Arial');
subplot(3,1,2); lambda.plot([],{{' ''k'',''Linewidth'',1'}});
hy=ylabel('Firing Rate [spikes/sec]', 'Interpreter','none');
hx=xlabel('','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,...
set(gca,'xtickLabel',[]);
title('Conditional Intensity Functions','FontWeight',...
'bold','FontSize',14,'FontName','Arial');
subplot(3,1,3); spikeColl.plot;
set(gca,'ytick',0:10:numRealizations,'ytickLabel',...
xlabel('time [s]','Interpreter','none');
ylabel('Cell Number','Interpreter','none');
hx=get(gca,'XLabel'); hy=get(gca,'YLabel');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title('Point Process Sample Paths','FontWeight',...
'bold','FontSize',14,'FontName','Arial');
stim = Covariate(time,sin(2*pi*f*time),'Stimulus','time','s','V',{'stim'});
baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
[dataDir,mEPSCDir,explicitStimulusDir,psthDir,placeCellDataDir] = ...
%Process noise covariance only drives the movement velocity
Q=diag([1e-12 1e-12 q q]);
delta = .001; % Time increment
p=1e-6; % in meters^2/s^2
PiT=diag([r r p p]); % Uncertainty in the target state
x0 = [0;0;0;0]; % Initial Position and velocities (states)
xT = [-.35;.2; 0;0];% Final Target
time=0:delta:T; % time vector
A=[1 0 delta 0 ; %State transition matrix
% Simulate a reach trajectory
% Differs from reference by multiplication by delta instead of division so
% that the velocity has units of meters per second
delta/(2)*(pi/T)^2*cos(pi*time(k)/T)*[0;0;...
xT(1)-x0(1);xT(2)-x0(2)]; %Reach to target model
%x(:,k)=A*x(:,k-1)+R*randn(size(x,1),1); %Random walk model
xT =x(:,end); % The target generated by the model
yT=xT; % Assume we have observed the actual target position with uncertainty PiT
%Define Q according to the dynamic range of the movement above
Q=diag(var(diff(x,[],2),[],2))*100;
% Plot the movement trajectories and the hand path
scrsz = get(0,'ScreenSize');
fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
scrsz(3)*.8 scrsz(4)*.8]);
plot(100*x(1,:),100*x(2,:),'k','Linewidth',2);
xlabel('X Position [cm]'); ylabel('Y Position [cm]');
hx=get(gca,'XLabel'); hy=get(gca,'YLabel');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title('Reach Path','FontWeight','bold','Fontsize',14,'FontName','Arial');
axis([sort([100*x0(1)+5, 100*xT(1)-5]), sort([100*x0(2)-5, 100*xT(2)+5])]);
h1=plot(100*x(1,1),100*x(2,1),'bo','MarkerSize',14);
h2=plot(100*x(1,end),100*x(2,end),'ro','MarkerSize',14);
legend([h1 h2],'Start','Finish','Location','NorthEast');
subplot(4,2,5); h1=plot(time,100*x(1,:),'k','Linewidth',2); hold on;
h2=plot(time,100*x(2,:),'k-.','Linewidth',2);
h_legend=legend([h1,h2],'x','y','Location','NorthEast');
set(h_legend,'FontSize',14)
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.06 pos(2)+.01 pos(3:4)]);
hx=xlabel('time [s]'); hy=ylabel('Position [cm]');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
% Plot the velocity profiles
h1=plot(time,100*x(3,:),'k','Linewidth',2); hold on;
h2=plot(time,100*x(4,:),'k-.','Linewidth',2);
h_legend=legend([h1 h2],'v_x','v_y','Location','NorthEast');
set(h_legend,'FontSize',14);
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.06 pos(2)+.01 pos(3:4)]);
hx=xlabel('time [s]'); hy=ylabel('Velocity [cm/s]');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
% Simulate neural responses
% logit(lambda_i*delta) = mu_i + b_x_i*v_x + b_y_i*v_y
% logit(lambda_i*delta) = X_i*beta_i;
bCoeffs=10*(rand(numCells,2)-.5); % b_i = [b_x_i b_y_i] ~ U(-5, 5);
phiMax = atan2(bCoeffs(:,2),bCoeffs(:,1)); % Maximal firing direction of cell
phiMaxNorm = (phiMax+pi)./(2*pi);
meanMu = log(10*delta); % baseline firing rate -10Hz
MuCoeffs = meanMu+randn(numCells,1); % mu_i ~ G(meanMu,1)
dataMat = [ones(length(time),1) x(3,:)' x(4,:)']; % design matrix: X (
coeffs = [MuCoeffs bCoeffs]; % coefficient vector: beta
tempData = exp(dataMat*coeffs(i,:)');
if(strcmp(fitType,'poisson'))
lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
lambda{i}=Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',...
{strcat('\lambda_{',num2str(i),'}')},{{' ''b'' '}});
lambda{i}=lambda{i}.resample(1/delta);
% Generate CIF representation in case we want to use the symbolic
% versions of the PPDecodeFilter (i.e. not PPDecodeFilterLinear
lambdaCIF{i} = CIF([MuCoeffs(i) 0 0 bCoeffs(i,:)],...
{'1','x','y','vx','vy'},{'x','y','vx','vy'},fitType);
% generate one realization for each cell
tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1); nst{i} = tempSpikeColl{i}.getNST(1); % grab the realization
nst{i}.setName(num2str(i)); % give each cell a unique name
h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}});
legend off; hold all; % Plot the CIF
title('Neural Conditional Intensity Functions','FontWeight',...
'bold','Fontsize',14,'FontName','Arial');
hx=xlabel('time [s]','Interpreter','none');
hy=ylabel('Firing Rate [spikes/sec]','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
spikeColl = nstColl(nst); % Create a neural spike train collection
subplot(4,2,[2,4]); spikeColl.plot;
set(gca,'xtick',[],'xtickLabel',[]);
title('Neural Raster','FontWeight','bold','Fontsize',14,...
hx=xlabel('time [s]','Interpreter','none');
hy=ylabel('Cell Number','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
scrsz = get(0,'ScreenSize');
fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
scrsz(3)*.6 scrsz(4)*.9]);
bCoeffs=10*(rand(numCells,2)-.5); % b_i = [b_x_i b_y_i] ~ U(-5, 5);
phiMax = atan2(bCoeffs(:,2),bCoeffs(:,1)); % Maximal firing direction of cell
phiMaxNorm = (phiMax+pi)./(2*pi);
meanMu = log(10*delta); % baseline firing rate
MuCoeffs = meanMu+randn(numCells,1); % mu_i ~ G(meanMu,1)
dataMat = [ones(length(time),1) x(3,:)' x(4,:)']; % design matrix: X (
coeffs = [MuCoeffs bCoeffs]; % coefficient vector: beta
tempData = exp(dataMat*coeffs(i,:)');
if(strcmp(fitType,'poisson'))
% Conditional Intensity Function for ith cell
lambdaData = tempData./(1+tempData);
lambda{i}=Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',...
{strcat('\lambda_{',num2str(i),'}')},{{' ''b'' '}});
lambda{i}=lambda{i}.resample(1/delta);
% Generate CIF representation in case we want to use the symbolic
% versions of the PPDecodeFilter (i.e. not PPDecodeFilterLinear
% generate one realization for each cell
tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1);
nst{i} = tempSpikeColl{i}.getNST(1); % grab the realization
nst{i}.setName(num2str(i)); % give each cell a unique name
% Plot the neural raster across all the cells
spikeColl = nstColl(nst); % Create a neural spike train collection
% Based on the temporal resolution defined by delta, bin the data and get
% a matrix representation of the neural firing
dN=spikeColl.dataToMatrix';
dN(dN>1)=1; % more than one spike per bin will be treated as one spike. In
% general we should pick delta small enough so that there is
[C,N] = size(dN); % N time samples, C cells
beta=[zeros(2,numCells); bCoeffs'];
%Use the Goal Directed Movement Version of the Point Process adaptive
[x_p, W_p, x_u, W_u,x_uT,W_uT,x_pT,W_pT] = ...
DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0, Pi0, yT,PiT,0);
%Use the Free Movement Version of the Point Process adaptive
[x_pf, W_pf, x_uf, W_uf] = ...
DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
subplot(4,2,1:4);h1=plot(100*x(1,:),100*x(2,:),'k','LineWidth',3);
axis([sort([100*x0(1)+5, 100*xT(1)-5]), ...
sort([100*x0(2)-5, 100*xT(2)+5])]);
title('Estimated vs. Actual Reach Paths',...
'FontWeight','bold','Fontsize',12,'FontName','Arial');
subplot(4,2,1:4);h2=plot(100*x_u(1,:)',100*x_u(2,:)','b'); hold all;
subplot(4,2,1:4);h3=plot(100*x_uf(1,:)',100*x_uf(2,:)','g');
hx=xlabel('x [cm]'); hy=ylabel('y [cm]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
h1=plot(100*x0(1),100*x0(2),'bo','MarkerSize',10); hold on;
h2=plot(100*xT(1),100*xT(2),'ro','MarkerSize',10);
legend([h1 h2],'Start','Finish','Location','NorthEast');
h1=plot(time,100*x(1,:),'k','LineWidth',3); hold on;
h2=plot(time,100*x_u(1,:)','b');
h3=plot(time,100*x_uf(1,:)','g');
hy=ylabel('x(t) [cm]'); hx=xlabel('time [s]');
set(gca,'xtick',[],'xtickLabel',[]);
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('X Position','FontWeight','bold','Fontsize',12,'FontName','Arial');
h1=plot(time,100*x(2,:),'k','LineWidth',3); hold on;
h2=plot(time,100*x_u(2,:)','b');
h3=plot(time,100*x_uf(2,:)','g');
h_legend=legend([h1(1) h2(1) h3(1)],'Actual','PPAF+Goal',...
'PPAF','Location','SouthEast');
hy=ylabel('y(t) [cm]'); hx=xlabel('time [s]');
set(gca,'xtick',[],'xtickLabel',[]);
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('Y Position','FontWeight','bold','Fontsize',12,'FontName','Arial');
set(h_legend,'FontSize',10)
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)-.63 pos(2)+.23 pos(3:4)]);
h1=plot(time,100*x(3,:),'k','LineWidth',3); hold on;
h2=plot(time,100*x_u(3,:)','b');
h3=plot(time,100*x_uf(3,:)','g');
hy=ylabel('v_{x}(t) [cm/s]'); hx=xlabel('time [s]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('X Velocity','FontWeight','bold','Fontsize',12,'FontName','Arial');
h1=plot(time,100*x(4,:),'k','LineWidth',3); hold on;
h2=plot(time,100*x_u(4,:)','b');
h3=plot(time,100*x_uf(4,:)','g');
hy=ylabel('v_{y}(t) [cm/s]'); hx=xlabel('time [s]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('Y Velocity','FontWeight','bold','Fontsize',12,'FontName','Arial');
%save paperHybridFilterExample time Tmax delta mstate X p_ij ind A Q Px0
load(fullfile(fileparts(which('nSTATPaperExamples')),'paperHybridFilterExample.mat'));
scrsz = get(0,'ScreenSize');
fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
scrsz(3)*.8 scrsz(4)*.9]);
plot(100*X(1,:),100*X(2,:),'k','Linewidth',2); hx=xlabel('X [cm]');
hy=ylabel('Y [cm]'); hold on;
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
title('Reach Path','FontWeight','bold','Fontsize',14,'FontName','Arial');
h1=plot(100*X(1,1),100*X(2,1),'bo','MarkerSize',16);
h2=plot(100*X(1,end),100*X(2,end),'ro','MarkerSize',16);
legend([h1 h2],'Start','Finish','Location','NorthEast');
plot(time,mstate,'k','Linewidth',2); axis tight; v=axis;
hx=xlabel('time [s]'); hy=ylabel('state');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
set(gca,'YTick',[1 2],'YTickLabel',{'N','M'})
title('Discrete Movement State','FontWeight','bold','Fontsize',14,...
h1=plot(time,100*X(1,1:end),'k','Linewidth',2); hold on;
h2=plot(time,100*X(2,1:end),'k-.','Linewidth',2);
hx=xlabel('time [s]'); hy=ylabel('Position [cm]');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
h_legend=legend([h1,h2],'x','y','Location','NorthEast');
set(h_legend,'FontSize',14)
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.06 pos(2)+.01 pos(3:4)]);
h1=plot(time,100*X(3,1:end),'k','Linewidth',2); hold on;
h2=plot(time,100*X(4,1:end),'k-.','Linewidth',2);
hx=xlabel('time [s]'); hy=ylabel('Velocity [cm/s]');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
h_legend=legend([h1,h2],'v_{x}','v_{y}','Location','NorthEast');
set(h_legend,'FontSize',14)
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)+.06 pos(2)+.01 pos(3:4)]);
meanMu = log(10*delta); % baseline firing rate
MuCoeffs = meanMu+randn(numCells,1); % mu_i ~ G(meanMu,1)
coeffs = [MuCoeffs 0*randn(numCells,2) 10*(rand(numCells,2)-.5) ...
%Add realization by thinning with history
dataMat = [ones(size(X,2),1),X(:,1:end)'];
clear lambda tempSpikeColl lambdaCIF n;
tempData = exp(dataMat*coeffs(i,:)');
if(strcmp(fitType,'binomial'));
lambdaData = tempData./(1+tempData);
lambda{i}=Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',...
{strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
n{i} = tempSpikeColl{i}.getNST(1);
n{i}.setName(num2str(i));
set(gca,'xtick',[],'xtickLabel',[],'ytickLabel',[]);
title('Neural Raster','FontWeight','bold','Fontsize',14,'FontName','Arial');
hx=xlabel('time [s]','Interpreter','none');
hy=ylabel('Cell Number','Interpreter','none');
set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
%Use the data to estimate the process noise for the moving case and
nonMovingInd = intersect(find(X(5,:)==0),find(X(6,:)==0));
movingInd=setdiff(1:size(X,2),nonMovingInd);
Q{2}=diag(var(diff(X(:,movingInd),[],2),[],2));
varNV=diag(var(diff(X(:,nonMovingInd),[],2),[],2));
close all; clear S_est X_est MU_est S_estNT X_estNT MU_estNT;
scrsz = get(0,'ScreenSize');
fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
scrsz(3)*.9 scrsz(4)*.9]);
meanMu = log(10*delta); % baseline firing rate
MuCoeffs = meanMu+randn(numCells,1); % mu_i ~ G(meanMu,1)
coeffs = [MuCoeffs 0*randn(numCells,2) 10*(rand(numCells,2)-.5) ...
%Add realization by thinning with history
dataMat = [ones(size(X,2),1),X(:,1:end)'];
clear lambda tempSpikeColl lambdaCIF nst;
tempData = exp(dataMat*coeffs(i,:)');
if(strcmp(fitType,'binomial'))
lambdaData = tempData./(1+tempData);
lambda{i}=Covariate(time,lambdaData./delta, ...
'\Lambda(t)','time','s','spikes/sec',...
{strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
nst{i} = tempSpikeColl{i}.getNST(1);
nst{i}.setName(num2str(i));
% Decode the x-y trajectory
% Enforce that the maximum time resolution is delta
spikeColl = nstColl(nst);
spikeColl.resample(1/delta);
dN = spikeColl.dataToMatrix;
dN(dN>1)=1; %Avoid more than 1 spike per bin.
% Starting states are equally probable
Mu0=.5*ones(size(p_ij,1),1);
clear x0 yT clear Pi0 PiT;
PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
PiT{2} = 1e-9*eye(size(x0{2},1),size(x0{2},1));
% Run the Hybrid Point Process Filter
[S_est, X_est, W_est, MU_est, X_s, W_s,pNGivenS]=...
DecodingAlgorithms.PPHybridFilterLinear(A, Q, p_ij,Mu0, dN',...
coeffs(:,1),coeffs(:,2:end)',fitType,delta,[],[],x0,Pi0, yT,PiT);
[S_estNT, X_estNT, W_estNT, MU_estNT, X_sNT, W_sNT,pNGivenSNT]=...
DecodingAlgorithms.PPHybridFilterLinear(A, Q, p_ij,Mu0, dN',...
coeffs(:,1),coeffs(:,2:end)',fitType,delta,[],[],x0,Pi0);
%Store the results for computing relevant statistics later
X_estNTAll(:,:,n) = X_estNT;
MU_estNTAll(:,:,n) = MU_estNT;
plot(time,mstate,'k','LineWidth',3); hold all;
plot(time,S_est,'b-.','Linewidth',.5);
plot(time,S_estNT,'g-.','Linewidth',.5); axis tight; v=axis;
axis([v(1) v(2) 0.5 2.5]);
%Movement State Probability (Non-movement State probability is 1-Pr(Movement))
plot(time,MU_est(2,:),'b-.','Linewidth',.5); hold on;
plot(time,MU_estNT(2,:),'g-.','Linewidth',.5); hold on;
axis([min(time) max(time) 0 1.1]);
h1=plot(100*X(1,:)',100*X(2,:)','k'); hold all;
h2=plot(100*X_est(1,:)',100*X_est(2,:)','b-.'); hold all;
h3=plot(100*X_estNT(1,:)',100*X_estNT(2,:)','g-.');
h1=plot(time,100*X(1,:),'k','LineWidth',3); hold on;
h2=plot(time,100*X_est(1,:)','b-.');
h3=plot(time,100*X_estNT(1,:)','g-.');
h1=plot(time,100*X(2,:),'k','LineWidth',3); hold on;
h2=plot(time,100*X_est(2,:)','b-.');
h3=plot(time,100*X_estNT(2,:)','g-.');
h1=plot(time,100*X(3,:),'k','LineWidth',3); hold on;
h2=plot(time,100*X_est(3,:)','b-.');
h3=plot(time,100*X_estNT(3,:)','g-.');
h1=plot(time,100*X(4,:),'k','LineWidth',3); hold on;
h2=plot(time,100*X_est(4,:)','b-.');
h3=plot(time,100*X_estNT(4,:)','g-.');
% Save all the example Data
% save Experiment6ReachExamples X_estAll X_estNTAll S_estAll ...
% S_estNTAll MU_estAll MU_estNTAll;
% load Experiment6ReachExamples;
% Mean Discrete State Estimate
plot(time,mstate,'k','LineWidth',3);
plot(time,mean(S_estAll),'b','LineWidth',3);
plot(time,mean(S_estNTAll),'g','LineWidth',3);
set(gca,'xtick',[],'YTick',[1 2.1],'YTickLabel',{'N','M'});
hy=ylabel('state'); hx=xlabel('time [s]');
set([hy hx],'FontName', 'Arial','FontSize',10,'FontWeight','bold',...
title('Estimated vs. Actual State','FontWeight','bold','Fontsize',...
% Mean State Movement State Probability
plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3);
plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3);
axis([min(time) max(time) 0 1.1]);
hx=xlabel('time [s]'); hy=ylabel('P(s(t)=M | data)');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('Probability of State','FontWeight','bold','Fontsize',12,...
h1=plot(100*X(1,:)',100*X(2,:)','k'); hold all;
mXestAll=mean(100*X_estAll,3);
mXestNTAll=mean(100*X_estNTAll,3);
plot(mXestAll(1,:),mXestAll(2,:),'b','Linewidth',3);
plot(mXestNTAll(1,:),mXestNTAll(2,:),'g','Linewidth',3);
hx=xlabel('x [cm]'); hy=ylabel('y [cm]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
h1=plot(100*X(1,1),100*X(2,1),'bo','MarkerSize',14); hold on;
h2=plot(100*X(1,end),100*X(2,end),'ro','MarkerSize',14);
legend([h1 h2],'Start','Finish','Location','NorthEast');
title('Estimated vs. Actual Reach Path','FontWeight','bold',...
'Fontsize',12,'FontName','Arial');
h1=plot(time,100*X(1,:),'k','LineWidth',3); hold on;
h2=plot(time,mXestAll(1,:),'b','LineWidth',3); hold on;
h3=plot(time,mXestNTAll(1,:),'g','LineWidth',3); hold on;
hy=ylabel('x(t) [cm]'); hx=xlabel('time [s]');
set(gca,'xtick',[],'xtickLabel',[]);
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('X Position','FontWeight','bold','Fontsize',12,'FontName','Arial');
h1=plot(time,100*X(2,:),'k','LineWidth',3); hold on;
h2=plot(time,mXestAll(2,:),'b','LineWidth',3); hold on;
h3=plot(time,mXestNTAll(2,:),'g','LineWidth',3); hold on;
h_legend=legend([h1(1) h2(1) h3(1)],'Actual','PPAF+Goal',...
'PPAF','Location','SouthEast');
hy=ylabel('y(t) [cm]'); hx=xlabel('time [s]');
set(gca,'xtick',[],'xtickLabel',[]);
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('Y Position','FontWeight','bold','Fontsize',12,'FontName','Arial');
set(h_legend,'FontSize',10)
pos = get(h_legend,'position');
set(h_legend, 'position',[pos(1)-.40 pos(2)+.51 pos(3:4)]);
h1=plot(time,100*X(3,:),'k','LineWidth',3); hold on;
h2=plot(time,mXestAll(3,:),'b','LineWidth',3); hold on;
h3=plot(time,mXestNTAll(3,:),'g','LineWidth',3); hold on;
hy=ylabel('v_{x}(t) [cm/s]'); hx=xlabel('time [s]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('X Velocity','FontWeight','bold','Fontsize',12,'FontName','Arial');
h1=plot(time,100*X(4,:),'k','LineWidth',3); hold on;
h2=plot(time,mXestAll(4,:),'b','LineWidth',3); hold on;
h3=plot(time,mXestNTAll(4,:),'g','LineWidth',3); hold on;
hy=ylabel('v_{y}(t) [cm/s]'); hx=xlabel('time [s]');
set([hx, hy],'FontName', 'Arial','FontSize',10,'FontWeight','bold');
title('Y Velocity','FontWeight','bold','Fontsize',12,'FontName','Arial');
function [dataDir,mEPSCDir,explicitStimulusDir,psthDir,placeCellDataDir] = ...
% Resolve local data folders robustly when Live Editor executes from a temp
% location (e.g., /private/var/.../T).
scriptPath = mfilename('fullpath');
candidateRoots = appendCandidateRoot(candidateRoots, fileparts(fileparts(scriptPath)));
paperPath = which('nSTATPaperExamples');
candidateRoots = appendCandidateRoot(candidateRoots, fileparts(fileparts(paperPath)));
installPath = which('nSTAT_Install');
candidateRoots = appendCandidateRoot(candidateRoots, fileparts(installPath));
activeFile = matlab.desktop.editor.getActiveFilename;
candidateRoots = appendCandidateRoot(candidateRoots, fileparts(fileparts(activeFile)));
candidateRoots = appendCandidateRoot(candidateRoots, pwd);
for iRoot = 1:numel(candidateRoots)
candidateDataDir = fullfile(candidateRoots{iRoot}, 'data');
if exist(candidateDataDir, 'dir') == 7
nSTATDir = candidateRoots{iRoot};
error('nSTATPaperExamples:MissingInstallPath', ...
['Could not resolve the nSTAT root path. Checked roots derived from ', ...
'mfilename, which(''nSTATPaperExamples''), which(''nSTAT_Install''), ', ...
'the active editor file, and pwd.']);
dataDir = fullfile(nSTATDir,'data');
mEPSCDir = fullfile(dataDir,'mEPSCs');
explicitStimulusDir = fullfile(dataDir,'Explicit Stimulus');
psthDir = fullfile(dataDir,'PSTH');
placeCellDataDir = fullfile(dataDir,'Place Cells');
if exist(dataDir,'dir') ~= 7
error('nSTATPaperExamples:MissingDataDir', ...
'Could not find local nSTAT data folder at %s', dataDir);
function roots = appendCandidateRoot(roots, startDir)
if ~any(strcmp(roots, thisDir))
roots{end+1} = thisDir; %#ok<AGROW>
parentDir = fileparts(thisDir);
if strcmp(parentDir, thisDir)